Reputation: 1598
I'm using an unbound data grid in Visual Basic. I made the following loop for the purpose of searching each cell and each column for a duplicate value. But for some reason I get a "InvalidCastException" when I try to add a second row.
Can anyone help?
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
EDIT: Adding the entire click event.
Upvotes: 1
Views: 1536
Reputation: 117047
A possible explanation is that your JudgeList
DataTable does not consist out of only string values as suggested by this line:
Dim AddJudge As String()
If this is the case then this would be more accurate:
Dim AddJudge As Object()
Also adapt this code reflect the correct data types:
AddJudge = {"2", "J", JudgeIDTxt.Text, JudgeNameLbl.Text}
I am guessing the first parameter should be numeric and not of string type, i.e:
AddJudge = {2, "J", JudgeIDTxt.Text, JudgeNameLbl.Text}
You can also use:
Dim AddJudge As DataRow = JudgeList.NewRow()
JudgeList("JudgeIDNumber") = 2
' update remaining fields...
JudgeList.Rows.Add(AddJudge)
Which will return a data row that is build up with the correct data types for each column.
Upvotes: 1