Phillip Wells
Phillip Wells

Reputation: 7622

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

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?

Upvotes: 3

Views: 23756

Answers (3)

Ruben Trancoso
Ruben Trancoso

Reputation: 1440

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]);

Upvotes: 1

stefano
stefano

Reputation: 31

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

Upvotes: 3

Brendan Kendrick
Brendan Kendrick

Reputation: 628

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!

Upvotes: 0

Related Questions