【问题标题】:How to Select New DataTableRow in DataGridView如何在 DataGridView 中选择新的 DataTableRow
【发布时间】:2014-04-23 00:43:49
【问题描述】:

我正在尝试在绑定到项目数据表的 DataGridView 中选择一个新添加的项目。我知道我们可以遍历 DataGridView 并找到它...

选择行(DataGridView 循环)

Private Sub SelectNewDgvItem(ByVal Item As clsItem, ByVal Dgv As DataGridView)
    For each r as DataGridViewRow In Dgv.Rows
        If r.Cells("PK_Item").Value = Item.PK_Item Then
           r.Selected()

           'Ensures visibility of the row if r.Cells("PK_Item") is visible
           Dgv.CurrentCell = r.Cells("PK_Item") 
           Exit For
        End If
    Next
End Sub

我想知道我们是否可以使用 DataTable 选择 DataGridView 行

【问题讨论】:

  • 你当然可以,只要在你的数据表中找到行的索引,然后在datagridview中设置选中的行。
  • @MrCoDeXeR,这不一定是真的。如果数据已经过排序和/或过滤,那么网格中的索引可能与表中的索引不匹配。
  • 当然,但他没有说任何关于它被排序或过滤的事情。如果这是真的,按我说的做就好了。
  • 此外,如果他决定过滤或排序,这可以事先完成,然后选择。以后如果他那样做,那索引肯定不一样了。
  • 是的,对不起,我忘了提到它应该对已排序和未排序的数据执行此操作。感谢您的帮助!

标签: vb.net datagridview datatable


【解决方案1】:

正确的方法是将DataTable 绑定到BindingSource,然后将BindingSource 绑定到DataGridView。然后可以调用BindingSourceFind 方法来获取行的索引,该索引可能与原始DataTable 中对应行的索引匹配也可能不匹配。然后,您可以使用该索引从网格的Rows 集合中获取DataGridViewRow 和/或您可以将其分配给BindingSourcePosition 属性以使其成为UI 中的当前行。这只是在 WinForms 中绑定时通常应使用BindingSource 的一个示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    相关资源
    最近更新 更多