vb.net - check if there are duplicate data in Datagridview

元气小坏坏 提交于 2020-01-05 04:20:08

问题


How do I check if there are duplicate in datagridview?

I have this code:

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.

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

and the data will be saved. as shown in the else statement.

What should I do so that even if the duplicate data are not following each other the MsgBox("Duplicate Data!") still appears?


回答1:


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


来源:https://stackoverflow.com/questions/50264301/vb-net-check-if-there-are-duplicate-data-in-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!