How to: Set Alternating Row Styles for the Windows Forms DataGridView Control
Tabular data is often presented to users in a ledger-like format where alternating rows have different background colors. This format makes it easier for users to tell which cells are in each row, especially with wide tables that have many columns.
With the DataGridView control, you can specify complete style information for alternating rows. This enables you use style characteristics like foreground color and font, in addition to background color, to differentiate alternating rows.
There is support for this task in Visual Studio. Also see How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer.
To set alternating row styles programmatically
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque; this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
With Me.dataGridView1 .RowsDefaultCellStyle.BackColor = Color.Bisque .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End With
The styles specified using the RowsDefaultCellStyle and AlternatingRowsDefaultCellStyle properties override the styles specified on the column and DataGridView level, but are overridden by the styles set on the individual row and cell level. For more information, see Cell Styles in the Windows Forms DataGridView Control.
Compiling the Code
This example requires:
A DataGridView control named
For maximum scalability, you should share DataGridViewCellStyle objects across multiple rows, columns, or cells that use the same styles, rather than setting the style properties for each element separately. For more information, see Best Practices for Scaling the Windows Forms DataGridView Control.
Basic Formatting and Styling in the Windows Forms DataGridView Control
Cell Styles in the Windows Forms DataGridView Control
Best Practices for Scaling the Windows Forms DataGridView Control
How to: Set Font and Color Styles in the Windows Forms DataGridView Control