vb.net-检查Datagridview中是否有重复数据 [英] vb.net - check if there are duplicate data in Datagridview
问题描述
如何检查datagridview中是否存在重复项?
How do I check if there are duplicate in 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
如果重复数据像下面这样互相重复,则上面的代码可以:
the code above is okay if the duplicate data is following each other like this:
Column1 (cell 0) | Column2 (cell 1)
------------------|------------------
TEST | NAME
TEST | NAME2
和重复数据!出现消息框。
and the "Duplicate Data!" Message Box appears.
但是,当重复的数据不互相跟踪时,它将转到 else
语句,其中它将被保存。像这样:
But when the duplicate data is not following each other it will go to the else
statement where it will be saved. Like this:
Column1 (cell 0) | Column2 (cell 1)
------------------|------------------
TEST | NAME
TEST2 | NAME3
TEST | NAME2
,数据将被保存。如 else
语句中所示。
and the data will be saved. as shown in the else
statement.
我应该怎么做,即使重复的数据不在每个后面其他 MsgBox(重复数据!)
仍然出现吗?
What should I do so that even if the duplicate data are not following each other the MsgBox("Duplicate Data!")
still appears?
推荐答案
在第二个For循环中,您应检查除第一个循环所处的索引以外的所有行,而不是索引+1。此外,如前所述,请清理else语句,因为它将阻止检查整个网格。如果找不到重复项,请在循环结束时调用您的Save_Data。
In your second For Loop you should check ALL rows other than the index you're on with the first loop, instead of index + 1. Also as mentioned, clean up that else statement because it will prevent the whole grid from being checked. Call your Save_Data at the end of looping if no duplicates were found. Use a Boolean to keep track.
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
这篇关于vb.net-检查Datagridview中是否有重复数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!