vb.net - 检查Datagridview中是否有重复数据

时间:2018-05-10 01:43:28

标签: vb.net datagridview

如何检查datagridview中是否存在重复?

我有这段代码:

For x As Integer = 0 To DataGridView1.Rows.Count - 1
    For y As Integer = x + 1 To DataGridView1.Rows.Count - 1
        If DataGridView1.Rows(x).Cells(0).Value.ToString = DataGridView1.Rows(y).Cells(0).Value.ToString Then
            MsgBox("Duplicate Data!")
            Exit Sub
        Else
            save_data()
            Me.Close()
        End If
    Next
Next

如果重复数据彼此跟随,则上面的代码是可以的:

Column1 (cell 0)  |  Column2 (cell 1)
------------------|------------------
TEST              |  NAME
TEST              |  NAME2

和"重复数据!"消息框出现。

但是当重复数据不相互跟随时,它将转到将保存它的else语句。像这样:

Column1 (cell 0)  |  Column2 (cell 1)
------------------|------------------
TEST              |  NAME
TEST2             |  NAME3
TEST              |  NAME2

,数据将被保存。如else声明中所示。

我该怎么做才能即使重复数据不相互关联,MsgBox("Duplicate Data!")仍会出现?

1 个答案:

答案 0 :(得分:2)

在你的第二个For循环中你应该用第一个循环检查你所使用的索引以外的所有行,而不是索引+ 1.同样如上所述,清理那个else语句,因为它会阻止整个网格被检查。如果没有找到重复项,请在循环结束时调用Save_Data。使用布尔值来跟踪。

Dim bolDuplicateWasFound As Boolean = False

For x As Integer = 0 To DataGridView1.Rows.Count - 1
    For y As Integer = 0 To DataGridView1.Rows.Count - 1
        If y <> x AndAlso DataGridView1.Rows(x).Cells(0).Value.ToString = DataGridView1.Rows(y).Cells(0).Value.ToString Then
            bolDuplicateWasFound = True
            MsgBox("Duplicate Data!")
            Exit Sub
        End If
    Next
Next

If Not bolDuplicateWasFound Then
    Save_Data()
End If
相关问题