This blog, and the source code it provides, demonstrate how to handle the Windows Forms DataGridView CellFormatting event to set the BackColor of a cell based on the cell's value. The example application in the source code provides users a way to mark inactive customers and/or customers who have not placed an order in the last 30 days. The CellFormatting event occurs when the contents of a cell in a Windows Forms DataGridView control needs to be formatted for display. To set the BackColor of a cells based on their values, create a CellFormatting event handler. Within the handler add code to set the BackColor of individual cells based on their value. Code Example 1 Private Sub customerDataGridView_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles customerDataGridView.CellFormatting 2 3 ' If the column being formatted is the column named 'Status' .. 4 If Me.customerDataGridView.Columns(e.ColumnIndex).Name = "Status" Then 5 If e.Value IsNot Nothing Then 6 ' If the value of the cell is "Inactive" AND this form's inactiveCustomersCheckBox control is checked.. 7 If e.Value.ToString = "Inactive" And Me.inactiveCustomersCheckBox.Checked Then 8 ' Set the BackColor of the cell to yellow. 9 e.CellStyle.BackColor = Color.Yellow 10 End If 11 End If 12 End If 13 14 ' If the column being formatted is the column named 'LastOrderDate'.. 15 If Me.customerDataGridView.Columns(e.ColumnIndex).Name = "LastOrderDate" Then 16 If e.Value IsNot Nothing Then 17 ' If LastOrderDate was more than 30 days ago AND this form's ordersOverdueCheckBox control is checked.. 18 If Date.Now.Subtract(CType(e.Value, Date)).Days > 30 And Me.orderOverdueCheckBox.Checked Then 19 ' Set the BackColor of the cell to yellow-green. 20 e.CellStyle.BackColor = Color.YellowGreen 21 End If 22 End If 23 End If 24 End Sub The CellFormatting event occurs every time each cell is painted, so you should avoid lengthy processing when handling this event. For more information visit the link below: DataGridView.CellFormatting Event Click the link above to download Visual Basic source code in a Visual Studio 2005 solution which demonstrates how to handle the Windows Forms DataGridView CellFormatting event to set the BackColor of a cell based on the cell's value.

评论