*Using Powershell studio but I could work with a C# answer since it's mostly the same except for syntax.
Here is the context:
I was previously using:
$datagridviewInfo.Rows.Add("123", "456")
To populate a DataGridView, but I noticed afterwards I couldn't export the DataGridView to CSV if it didn't use a "DataTable" as it's DataSource.
So now i'm creating a DataTable and adding my rows to this object. I can now export sucessfully to CSV. HOWEVER, I can't manage to style my cells like I was able to before. If I do this to test :
$button1_Click={
$RowNomPoste = $datagridviewInfo.Rows.Add("Poste", "$poste est inaccessible.")
$datagridviewInfo.Rows.Item($RowNomPoste).DefaultCellStyle.BackColor = "Red"
}
It works and gives me that row highlighted in red. However that method isn't using a DataTable so it's no good since later on I can't export to CSV.
Now if I try this :
$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"
}
It adds the row but won't allow me to change it's DefaultCellStyle. It throws the error :
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».»»
Why is it working when using the first method of adding rows directly to DataGridView but NOT when using a DataTable? How can I use a DataTable but still style my row properly?
Much appreciated.
I got it working with the RowPrePaint event like this :
$datagridviewInfo_RowPrePaint=[System.Windows.Forms.DataGridViewRowPrePaintEventHandler]{
if (($datagridviewInfo.Rows[$_.RowIndex].Cells[1].Value) -like "*inaccessible*")
{
$datagridviewInfo.Rows[$_.RowIndex].DefaultCellStyle.BackColor = 'red'
}
}
All thanks to jrv at Technet :