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.
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.
Double-click "DataGridView" from the "Toolbox" pane to add one to your form. Double-click "Button" to add a new button.
Video of the Day
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.Name = "ID"; dataGridView1.Columns.Name = "Name"; dataGridView1.Columns.Name = "Price";
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.Index; dataGridView1.Refresh(); dataGridView1.CurrentCell = dataGridView1.Rows.Cells; dataGridView1.Rows.Selected = true; MessageBox.Show ( dataGridView1.CurrentRow.Index.ToString());