3

我有一个 DataGrid,它与一个 DataTable 绑定,该 DataTable 有两列存储序列,在我的 DataGrid 中,这些序列列与 DataGridViewComboBoxes 绑定。用户可以从组合框设置序列。序列列中的默认值为 0。

我只想在按钮单击时检查两列中的重复性,用户不应该在两列中选择任何重复值。

如果我通过使用 DataView 的 ToTable 方法来查找不同的值来实现它,它也会采用值为“0”的行

如果我对 DataTable 上的列实施唯一约束,它也会检查 0。

如果尝试使用 0 删除值,它也会更改 DataGrid 因为 DataGrid 与 DataTable 绑定

如果我尝试从现有数据表中声明一个新的数据表,它也会自动绑定到数据网格。

请帮我。

4

1 回答 1

2

以下是如何检查 DataTable 中的重复值的示例:

Option Strict On

Module Module1
  Sub Main()
    Dim dt As New DataTable
    dt.Columns.Add("mycolumn", GetType(Integer))
    dt.Rows.Add({"1"})
    dt.Rows.Add({"2"})
    dt.Rows.Add({"2"})
    dt.Rows.Add({"4"})
    dt.Rows.Add({"7"})
    Dim duplicateDictionary As New Dictionary(Of Integer, Integer) 'value, count

    For Each row As DataRow In dt.Rows
      Dim count As Integer = 0
      Dim value As Integer = CInt(row("mycolumn"))
      duplicateDictionary.TryGetValue(value, count)
      duplicateDictionary(value) = count + 1
    Next

    For Each kv As KeyValuePair(Of Integer, Integer) In duplicateDictionary
      If kv.Value > 1 Then 'we have a duplicate
        Debug.WriteLine("{0} is a duplicated value, encountered {1} times", kv.Key, kv.Value)
      End If
    Next
  End Sub
End Module

添加一个 UniqueConstraint 也是可能的,但我发现它有时过于侵入,这取决于您的编辑工作方式。对于直接网格内编辑,您可能希望用户将无效记录保存在内存中,并允许修复错误,显示验证错误而不是约束违反异常。当然,您永远不会将无效数据保存到数据库中。

于 2013-06-14T13:31:16.443 回答