如何设置的DataGridView选定行新添加的行格的时候必然要排序的数据视图?视图、如何设置、时候、数据

2023-09-06 10:06:47 作者:好听的古风名字,好听的古风游戏名字

我有一个的DataGridView 绑定到数据视图。网格可以通过在任何列中的用户进行排序。

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

我通过在数据视图调用NEWROW添加一行到网格的潜在数据表,然后将其添加到数据表的行集合。我怎样才能在网格中选择新添加的行?

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?

我试图通过创建绑定到的BindingContext 的一个 BindingManagerBase 对象做数据视图,然后设置 BindingManagerBase.Position = BindingManagerBase.Count 。这适用于如果在网格未排序,因为新的行被添加到网格的底部。然而,如果排序顺序是这样的,该行没有添加到底层,这是行不通的。

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?

推荐答案

只要你更新绑定数据表中,RowsAdded事件是由DataGridView控件发射,与含有添加的指数DataGridViewRowsAddedEventArgs.RowIndex财产行。

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

 
精彩推荐
图片推荐