C# Programming > Data

C# Set DataGridView Selection


When data is added or searched in a DataGridView, it make it easier for the user to programmatically change the DataGridView selection.

Unfortunately, setting the selected item is not as easy as a ListBox for example. The reasons being that DataGridView's usually handle larger amounts of data and they are often bound to data sources. Either way, it's a 3 step process.

Set DataGridView Selection

Here's how to set the active row of a DataGridView. The two example variables will be dataGrid, which is a DataGridView, and index, which is the index of the row you want to select with C# code.

First is to scroll down the DataGridView so the row is visible in the screen:

dataGridView1.FirstDisplayedScrollingRowIndex = index;

Then you must select the row so that binding sources update their Current item:

dataGridView1.CurrentCell = dataGrid.Rows[index].Cells[0];

Finally, you can visually select the row with C#:

dataGridView1.Rows[index].Selected = true;


The C# code above assumes that you are trying to select an entire DataGridView row. However it is simple to adjust if you just want to select a Cell. Otherwise the code will work to set the DataGridView selection.

Back to C# Article List