C# DataGridView Row Colors (Alternating)

Use the AlternatingRowsDefaultCellStyle property on DataGridView.

Alternating row colors improve the usability of DataGridView. They help users avoid confusing rows if they are working in an application. We use C# code to populate rows in a DataGridView and then adjust the colors to be alternating.DataGridView

Example. The first part of this demonstration requires the Form1_Load event handler in your project. Double-click on the window containing your DataGridView to generate the method. Next, insert the code that calls Add on the Columns and Rows.

Tip: This is just one way you can populate a DataGridView. Other approaches are available.

Adding rows to DataGridView: C# using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Add a column. this.dataGridView1.Columns.Add("Name", "Text"); // Put all these strings into rows. string[] input = new string[] { "Alternating", "Row", "Colors", "Are", "Neat" }; foreach (string val in input) { this.dataGridView1.Rows.Add(new string[] { val }); } } } }

BackColor. To finish the project, we need to modify the AlternatingRowsDefaultCellStyle property. Find this in your Properties panel and then use the CellStyle Builder to change the BackColor and ForeColor. These settings affect every other row.ForeColor, BackColor

Summary. We added columns and rows to a DataGridView. We then changed its color settings so that alternating rows are visibly different. In some applications, alternating colors reduce the chance that the data are read wrong by the user.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to