How to set selected row of DataGridView to newly-added row when the grid is bound to sorted DataView?

Phillip Wells picture Phillip Wells · Oct 10, 2008 · Viewed 23k times · Source

I have a DataGridView bound to a DataView. The grid can be sorted by the user on any column.

I add a row to the grid by calling NewRow on the DataView's underlying DataTable, then adding it to the DataTable's Rows collection. How can I select the newly-added row in the grid?

I tried doing it by creating a BindingManagerBase object bound to the BindingContext of the DataView, then setting BindingManagerBase.Position = BindingManagerBase.Count. This works if the grid is not sorted, since the new row gets added to the bottom of the grid. However, if the sort order is such that the row is not added to the bottom, this does not work.

How can I reliably set the selected row of the grid to the new row?

Answer

stefano picture stefano · Jan 26, 2009

As soon as you update the bound DataTable, a "RowsAdded" event is fired by the DataGridView control, with the DataGridViewRowsAddedEventArgs.RowIndex property containing the index of the added row.

//local member
private int addedRowIndex;

private void AddMyRow()
{
    //add the DataRow           
    MyDataSet.MyDataTable.Rows.Add(...);

    //RowsAdded event is fired here....

    //select the row
    MyDataGrid.Rows[addedRowIndex].Selected = true;
}

private void MyDataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
    addedRowIndex = e.RowIndex;
}

Not the most elegant solution, perhaps, but it works for me