在 Datagridview 中使用 DataTable 时更改 DefaultCellStyle

Change DefaultCellStyle when using a DataTable in Datagridview

*使用 Powershell studio,但我可以使用 C# 答案,因为除了语法外,它大部分是相同的。

上下文如下:

我之前使用的是:

$datagridviewInfo.Rows.Add("123", "456")

填充 DataGridView,但后来我注意到如果 DataGridView 不使用 "DataTable" 作为 DataSource,我无法将 DataGridView 导出到 CSV。

现在我正在创建一个 DataTable 并将我的行添加到该对象。我现在可以成功导出到 CSV。 但是,我无法像以前那样设置我的单元格样式。 如果我这样做是为了测试:

$button1_Click={
 $RowNomPoste = $datagridviewInfo.Rows.Add("Poste", "$poste est inaccessible.")
 $datagridviewInfo.Rows.Item($RowNomPoste).DefaultCellStyle.BackColor = "Red"
}

它有效并给我以红色突出显示的行。但是该方法没有使用数据表,所以它不好,因为后来我无法导出到 CSV。

现在如果我试试这个:

$button2_Click={
 $tableInfoPoste = New-Object system.Data.DataTable "TableInfoPoste"

 $tableInfoPoste.Columns.Add("Propriété")
 $tableInfoPoste.Columns.Add("Valeur")

 $datagridviewInfo.DataSource = $tableInfoPoste

 $RowNomPoste = $tableInfoPoste.Rows.Add("Poste", "$poste est inaccessible.")

 $tableInfoPoste.Rows.Item($RowNomPoste).DefaultCellStyle.BackColor = "Red"

}

它添加了行,但不允许我更改它的 DefaultCellStyle。 它抛出错误:

 Cannont convert argument «index» («System.Data.DataRow»)  «get_Item» to type «System.Int32»: «
ERROR: Cannot convert the value «System.Data.DataRow» of type «System.Data.DataRow» to type «System.Int32».»»

为什么在使用第一种方法将行直接添加到 DataGridView 时有效,但在使用 DataTable 时却无效? 如何在使用 DataTable 的同时正确设置行的样式?

非常感谢。

我是这样处理 RowPrePaint 事件的:

$datagridviewInfo_RowPrePaint=[System.Windows.Forms.DataGridViewRowPrePaintEventHandler]{
 if (($datagridviewInfo.Rows[$_.RowIndex].Cells[1].Value) -like "*inaccessible*")
 {
  $datagridviewInfo.Rows[$_.RowIndex].DefaultCellStyle.BackColor = 'red'
 }


}

感谢 Technet 的 jrv :

https://social.technet.microsoft.com/Forums/windowsserver/en-US/6cb6a5be-08bd-47d4-8783-66d57fc26ead/change-defaultcellstyle-when-using-a-datatable-in-datagridview?forum=winserverpowershell