数据网格中的重复值

时间:2012-02-26 07:51:53

标签: vb.net visual-studio-2010 loops datagridview

我在Visual Basic中使用未绑定的数据网格。为了搜索每个单元格和每列的重复值,我进行了以下循环。但由于某些原因,当我尝试添加第二行时,我收到“InvalidCastException”。

有人可以帮忙吗?

Private Sub AddJudgeBtn_Click(sender As System.Object, e As System.EventArgs) Handles AddJudgeBtn.Click

    Dim exists As Boolean

    ' ToDo: If the value entered is already on the list, don't add again.

    If JudgeList.Rows.Count() > 0 Then
        For Each itm As DataGridViewRow In JudgeList.Rows
            If itm.Cells("JudgeIDNumber").Value = JudgeIDTxt.Text Then
                exists = True
            End If
        Next
    End If

    If exists = False Then
        Dim AddJudge As String()
        Try
            If JudgeList.Rows.Count = 0 Then
                ' There are no judges, by default. These person becomes the head judge.
                AddJudge = {"0", "HJ", JudgeIDTxt.Text, JudgeNameLbl.Text}
                JudgeList.Rows.Add(AddJudge)
            Else
                ' There is already a judge/head judge, this person becomes a regular judge.
                AddJudge = {"2", "J", JudgeIDTxt.Text, JudgeNameLbl.Text}
                JudgeList.Rows.Add(AddJudge)
            End If

        Catch ex As Exception
            ' Do Nothing
        End Try
    End If
    JudgeIDTxt.Clear()
End Sub

编辑:添加整个点击事件。

1 个答案:

答案 0 :(得分:1)

可能的解释是,您的JudgeList DataTable不包含此行所建议的字符串值:

Dim AddJudge As String()

如果是这种情况,那么这将更准确:

Dim AddJudge As Object()

同样适应此代码反映正确的数据类型:

AddJudge = {"2", "J", JudgeIDTxt.Text, JudgeNameLbl.Text}

我猜第一个参数应该是数字而不是字符串类型,即:

AddJudge = {2, "J", JudgeIDTxt.Text, JudgeNameLbl.Text}

您也可以使用:

Dim AddJudge As DataRow = JudgeList.NewRow()
JudgeList("JudgeIDNumber") = 2
' update remaining fields...
JudgeList.Rows.Add(AddJudge)

这将返回使用每列的正确数据类型构建的数据行。