How to set a selected row of a DataGridView for a newly added row when the grid is tied to sorting a DataView?

I have a DataGridView associated with a DataView . The grid can be sorted by the user in any column.

I add a row to the grid by calling NewRow in the DataView below the DataTable , and then adding it to the DataTable row collection. How can I select a newly added row in a grid?

I tried to do this by creating a BindingManagerBase object associated with the BindingContext DataView , then setting BindingManagerBase.Position = BindingManagerBase.Count . This works if the grid is not sorted, as a new row is added to the bottom of the grid. However, if the sort order is such that the row is not added at the bottom, this does not work.

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

+2
source share
3 answers

Once you update the associated DataTable, the RowsAdded event is fired by the DataGridView control, and the DataGridViewRowsAddedEventArgs.RowIndex property contains 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, maybe, but it works for me

+3
source

I don’t know how to determine its best solution, but, for example, it looks better than iteration.

  DataRowView drv = (DataRowView)source.AddNew(); grupoTableAdapter.Update(drv.Row); grupoBindingSource.Position = grupoBindingSource.Find("ID", drv.Row.ItemArray[0]); 
+1
source

Assuming you have some sort of unique identifier in your data source, you can iterate over your collection of rows and compare:

 Dim myRecentItemID As Integer = 3 For Each row As GridViewRow In gvIndividuals.Rows Dim drv As DataRowView = DirectCast(row.DataItem, DataRowView) If CInt(drv("ItemID")) = myRecentItemID Then gvIndividuals.EditIndex = row.RowIndex End If Next 

Hope this helps!

0
source

All Articles