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

一个人想着一个人 提交于 2019-12-23 23:56:44

问题


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?


回答1:


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




回答2:


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



回答3:


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!



来源:https://stackoverflow.com/questions/191339/how-to-set-selected-row-of-datagridview-to-newly-added-row-when-the-grid-is-boun

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!