If your DataGridView is bound to a data source, you may want to format the grid's Rows when the DataBinding is complete.
Subscribe to the DataBindingComplete event.
After that, you need to handle Cell value changes, to format the Row based on the value of a Column in the current Row.
Subscribe to the CellValueChanged event.
I'm using a helper method to determine what is the current what is the value of the Cell that determines the Font Style change, what is the current Font of its OwningRow, then change the Font Style to the Style specified if all criteria are met, otherwise, revert to default Font Style.
Note: the DataGridViewRow.DefaultCellStyle may be null, since the Row may inherit the Font from the DataGridView.DefaultCellStyle
, so we need to check the DataGridViewRow.InheritedStyle value.
There's an assignment that uses a coalesce expression in the helper method:
Dim rowFont = If(row.DefaultCellStyle.Font, row.InheritedStyle.Font)
If this syntax is not available in your VB.Net version, use an extended form as:
Dim rowFont = If(row.DefaultCellStyle.Font Is Nothing, row.InheritedStyle.Font, row.DefaultCellStyle.Font)
Or do nothing if the current Cell value is null (Nothing
) or is DbNull.Value: it can be if the DataGridView.DataSource
is set to a DataTable, for example.
If you want to interpret null Cell values as 0
, change the code accordingly.
Private Sub DetailDataGridView_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DetailDataGridView.CellValueChanged
If e.ColumnIndex = 4 Then
ToggleRowFontStyle(Of Integer)(DetailDataGridView(4, e.RowIndex), 0, FontStyle.Strikeout)
End If
End Sub
Private Sub DetailDataGridView_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles DetailDataGridView.DataBindingComplete
For Each row As DataGridViewRow In DetailDataGridView.Rows
ToggleRowFontStyle(Of Integer)(DetailDataGridView(4, row.Index), 0, FontStyle.Strikeout)
Next
End Sub
Helper method:
Private Sub ToggleRowFontStyle(Of T)(cell As DataGridViewCell, toggleValue As T, toggleFontStyle As FontStyle)
If cell.Value Is Nothing OrElse cell.Value Is DBNull.Value Then Return
Dim row As DataGridViewRow = cell.OwningRow
Dim cellValue As T = CType(Convert.ChangeType(cell.Value, GetType(T)), T)
Dim rowFont = If(row.DefaultCellStyle.Font, row.InheritedStyle.Font)
If cellValue.Equals(toggleValue) Then
If rowFont.Style <> toggleFontStyle Then
rowFont = New Font(rowFont, toggleFontStyle)
End If
Else
If rowFont.Style = toggleFontStyle Then
rowFont = New Font(rowFont, FontStyle.Regular)
End If
End If
row.DefaultCellStyle.Font = rowFont
End Sub