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. How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer
How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer
How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer
How to: Set Alternating Row Styles for the Windows Forms DataGridView Control Using the Designer
To set alternating row styles programmatically
Set the properties of the DataGridViewCellStyle objects returned by the RowsDefaultCellStyle and AlternatingRowsDefaultCellStyle properties of the DataGridView.
With Me.dataGridView1 .RowsDefaultCellStyle.BackColor = Color.Bisque .AlternatingRowsDefaultCellStyle.BackColor = Color.Beige End With
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque; this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige;
Note 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
dataGridView1
.References to the System, System.Drawing, and System.Windows.Forms assemblies.
Robust Programming
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.
See Also
Tasks
How to: Set Font and Color Styles in the Windows Forms DataGridView Control
Reference
System.Windows.Forms.DataGridView.AlternatingRowsDefaultCellStyle
System.Windows.Forms.DataGridView.RowsDefaultCellStyle
DataGridView
DataGridViewCellStyle
Concepts
Cell Styles in the Windows Forms DataGridView Control
Best Practices for Scaling the Windows Forms DataGridView Control
Other Resources
Basic Formatting and Styling in the Windows Forms DataGridView Control