How to Set the DataGridView CurrentRow

Techwalla may earn compensation through affiliate links in this story. Learn more about our affiliate and product review process here.
Populate data grid with data in C#.

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.

Advertisement

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.

Video of the Day

Step 2

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

Advertisement

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";

Advertisement

Advertisement

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

Video of the Day

Advertisement

Advertisement

references