How to Set the DataGridView CurrentRow

By Jaime Avelar

Setting the current row of a "DataGridView" control in your C# application can be somewhat confusing if you're not familiar with the "CurrentCell" property. The "CurrentCell" property will set the selected cell into view if it is not currently displayed. Programmers often forget to refresh their "DataGridView" after they have selected a row. The "CurrentRow" property locates the row containing the current cell.

Things You'll Need

  • Microsoft Visual Studio

Step 1

Open Microsoft Visual Studio and click "New Project..." from the left pane of your screen. Expand "Other Languages," expand "Visual C#," and click "Windows." Double-click "Windows Forms Application" to create a new project.

Step 2

Double-click "DataGridView" from the "Toolbox" pane to add one to your form. Double-click "Button" to add a new button.

Step 3

Double-click the form to create a form load event. Copy and paste the following code to populate the "DataGridView" control with four rows of data:dataGridView1.ColumnCount = 3; dataGridView1.Columns[0].Name = "ID"; dataGridView1.Columns[1].Name = "Name"; dataGridView1.Columns[2].Name = "Price"; string[] row = new string[] { "1", "Item 1", "150" }; dataGridView1.Rows.Add(row); row = new string[] { "2", "Item 2", "250" }; dataGridView1.Rows.Add(row); row = new string[] { "3", "Item 3", "125" }; dataGridView1.Rows.Add(row); row = new string[] { "4", "Item 4", "75" }; dataGridView1.Rows.Add(row);

Step 4

Switch back to form design and double-click "button1" to create a click event for this button. Copy and paste the following code to set row number three as the current row:dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows[2].Index; dataGridView1.Refresh(); dataGridView1.CurrentCell = dataGridView1.Rows[2].Cells[1]; dataGridView1.Rows[2].Selected = true;MessageBox.Show ( dataGridView1.CurrentRow.Index.ToString());