如何设置的DataGridView选定行新添加的行格的时候必然要排序的数据视图? [英] How to set selected row of DataGridView to newly-added row when the grid is bound to sorted DataView?

查看:144
本文介绍了如何设置的DataGridView选定行新添加的行格的时候必然要排序的数据视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的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

这篇关于如何设置的DataGridView选定行新添加的行格的时候必然要排序的数据视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆