How to Set the DataGridView CurrentRow

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.

...
Populate data grid with data in C#.

Step

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

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

Step

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:

Step

dataGridView1.ColumnCount = 3; dataGridView1.Columns[0].Name = "ID"; dataGridView1.Columns[1].Name = "Name"; dataGridView1.Columns[2].Name = "Price";

Step

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:

Step

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