C# DataGridView Row Colors: Alternating

One of the easiest ways to improve the usability and performance of your DataGridView control is to add alternating row colors. This can help users avoid confusing rows if they are working in an application. We use the C# language to populate rows in a DataGridView and then adjust the colors to be alternating.

DataGridView row colors

This article uses the AlternatingRowsDefaultCellStyle property on DataGridView.

Add rows

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 collections. This is just one way you can populate a DataGridView.

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 });
	    }
	}
    }
}

Adjust colors

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

CellStyle Builder

Summary

In this tutorial, we saw how you can add columns and rows to a DataGridView and then change its color settings so that alternating rows are visibly different. In some applications, alternating colors can reduce the chance that the data are read wrong by the user.

Windows Forms
.NET