views:

4302

answers:

3

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?

A: 

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

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!

Brendan Kendrick
I'm not using an ASP.NET GridView, I'm using a Windows DataGridView.
Phillip Wells
+1  A: 

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

stefano
it not works, the Sort happens before the you get the rowIndex. It will be ever the last position in the view for rows added with Add or AddNew AFAIK.
Ruben Trancoso
A: 

Dont know id its the best solution but for instance looks better than iterate.

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