【问题标题】:How to check if there are any duplicate values in a Column in a DataGridview?如何检查 DataGridview 的列中是否有任何重复值?
【发布时间】:2013-12-27 11:23:36
【问题描述】:

我有一个 DataGridView,在保存数据之前,我想检查特定列是否在任何行中有任何重复值。

 If DataGridView1.Rows.Count > 2 Then
            Dim count As Integer = 0
            Dim i As Integer = 0
            While DataGridView1.Rows.Count - 1

                Dim j As Integer = 1


                While DataGridView1.Rows.Count - 1

                    Dim str As String = DataGridView1.Rows(i).Cells("ColLedger").Value()
                    Dim str1 As String = DataGridView1.Rows(j).Cells("ColLedger").Value()


                    If str1 = str Then
                        count = count + 1
                    End If

                    j += 1



                End While
                i += 1
            End While


            If count > 0 Then
                MsgBox(count)
            End If

我收到索引超出范围错误。我不确定我做错了什么。

如果可以使用在线工具轻松转换,我也会接受 c# 答案。

【问题讨论】:

    标签: c# .net vb.net datagridview


    【解决方案1】:

    这应该可以。我认为您的错误在于While DataGridView1.Rows.Count - 1 行,这没有意义。不过,没有Option Explicit 并没有错,因为框架可以将整数与布尔值进行比较(True = 1,False = 0),但这不是你想要的。我总是建议打开 Option Explicit,要么将其添加到您的代码中,要么只需在编译设置中打开它。

    Dim Count as integer = 0
    For i = 0 To dgv.RowCount - 2
      For a = i + 1 To dgv.RowCount - 1
         if dgv.Rows(i).Cells("ColLedger").Value = dgv.Rows(a).Cells("ColLedger").Value Then Count += 1
      Next
    Next
    MsgBox(Count.ToString)
    

    【讨论】:

    • 好作品!顺便说一句,你能告诉我如何检查显示文本而不是组合框的值吗?如dgv.Rows(a).Cells("ColLedger").Text
    • 显示文本就是.ToString函数转换成字符串的Value。所以使用dgv.Rows(a).Cells("ColLedger").Value.ToString()。我刚刚编辑了我的答案以排除重复项(第二个循环仅在第一个循环的当前位置之后开始)。
    • @Jens 我正在使用数据集填充该组合框,并且我有两个单独的字段用于其 DisplayMember 和 ValueMember 。 Dim Count as integer = 0 For i = 0 To dgv.RowCount - 2 For a = i + 1 To dgv.RowCount - 1 if dgv.Rows(i).Cells("ColLedger").Value = dgv.Rows(a).Cells("ColLedger").Value Then Count += 1 Next Next MsgBox(Count.ToString) 只是让我得到值成员而不是显示成员我想知道在 Datagridview Combobox 的情况下是否可能
    • 您可能应该为此制定一个新问题,我不是这方面的真正专家。 :-)
    • @Jens 你能帮我解决我的问题吗? stackoverflow.com/questions/38420644/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    相关资源
    最近更新 更多