当网格绑定到排序的DataView时,如何将DataGridView的选定行设置为新添加的行?
我有一个绑定到 DataView
的 DataGridView
。 用户可以在任何列上对网格进行排序。
我通过在 DataView
的底层 DataTable
上调用 NewRow 向网格添加一行,然后将其添加到 DataTable
的 Rows 集合中。 如何选择网格中新添加的行?
我尝试通过创建绑定到 DataView
的 BindingContext
的 BindingManagerBase
对象,然后设置 BindingManagerBase.Position = BindingManagerBase.Count
。 如果网格未排序,则此方法有效,因为新行会添加到网格的底部。 但是,如果排序顺序使得该行不添加到底部,则此方法不起作用。
如何可靠地将网格的选定行设置为新行?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一旦更新绑定的 DataTable,DataGridView 控件就会触发“RowsAdded”事件,其中 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.
Not the most elegant solution, perhaps, but it works for me
不知道它是最好的解决方案,但例如看起来比迭代更好。
Dont know id its the best solution but for instance looks better than iterate.
假设您的数据源中有某种唯一标识符,您可以迭代行集合并进行比较,如下所示:
希望这有帮助!
Assuming you have some sort of unique identifier in your data source you could iterate over your collection of rows and compare, as such:
Hope this helps!