Search code examples
c#winformsdatagrid

How to programmatically set focus on a row in a WinForms DataGrid when selecting it?


I have a WinForms DataGrid (not DataGridView). When I manually select a row, the row indicator, shown in the first image below, shows on the selected rows. However, if I set the DataGrid's datasource after a save and programmatically select the second row using: datagrid.Select(1), the second row gets the highlighted background color but the focus indicator is on the first row as shown in the second image below.

Is there a way to make the selected row get focus and have the indicator display for the row?

enter image description here

enter image description here


Solution

  • Since this is the old System.Windows.Forms.DataGrid, the Row selection method is slightly different than the DataGridView's.

    You can select a Row, as you're doing, with the Select() method.
    This doesn't change the Current Row. To make a Row the Current, you can use the CurrentRowIndex property.
    Combined, these two move the selection and set the Current Row.

     // Selects and highlights the Row at index 1
     dataGrid.Select(1);
     // Make the Row at index 1 the Current
     dataGrid.CurrentRowIndex = 1;
    

    Something similar in a DataGridView:
    (One of the methods that can be used to achieve this result)

    // Move the focus and selects the Row at index 1
    dataGridView.Rows[1].Selected = true;
    // Make the Row at index 1 the Current setting the CurrentCell property
    dataGridView.CurrentCell = dataGridView.Rows[1].Cells[0];