问题
I want to color entire rows of a System.Windows.Forms.DataGrid
based on the content of one cell of the Row.
I couldn't find any way to do that, since there is no .Rows
-Property of the DataGrid or a .Row
-Property of the DataGridTextBoxColumn (or any similar).
Searching for solutions in the internet also didn't help me so far.
Switching to DataGridView
is unfortunately not an option.
So the question remains: How can I change the color of a DataGrid row?
回答1:
Thanks to this link (provided by @Monty) I was able to solve the problem.
You have to format every Cell on its own, so you have to hook up on the SetCellFormat
-Event of every Column:
AddHandler column.SetCellFormat, AddressOf FormatGridRow
In the EventHandler you can check for example the cell value of another column of the same row and change the color of the current cell accordingly. When every cell of the row gets formatted this way, it seems like the row as a whole is formatted.
Private Sub FormatGridRow(ByVal sender As Object, ByVal e As DataGridFormatCellEventArgs)
Dim Cell As DataGridColumnStyle = sender
Dim ColumnStyles As GridColumnStylesCollection = Cell.DataGridTableStyle.GridColumnStyles
Dim columnIndex As Integer = ColumnStyles.IndexOf(ColumnStyles.Item("ColumnName"))
If Cell.DataGridTableTableStyle.DataGrid(e.Row, columnIndex).ToString() = "SomeValue" Then
e.BackBrush = New SolidBrush(Color.Red) 'this does only change the Cell`s background
End If
End Sub
来源:https://stackoverflow.com/questions/35556821/change-color-of-datagrid-row