每当我添加一个Item时,我都会尝试检查DataGridView中的每一行,以避免重复。但是我的代码只允许我检查我添加的第一个数据。
以下是我的代码:
For Each row In BarcodePrintListGrid.Rows
If Label44.Text = row.Cells("Barcode ID").Value Then
MetroMessageBox.Show(Me, "Item Already Added", "System Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Label47.Text = "None"
Label44.Text = "None"
Label42.Text = "None"
Label31.Text = "None"
Label40.Text = "0"
TextBox1.Clear()
Exit For
Else
BarcodePrintListGrid.Rows.Add(Label47.Text, Label44.Text, Label42.Text, Label31.Text, Label40.Text, 1)
MetroMessageBox.Show(Me, "Item Added to List", "System Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
Label47.Text = "None"
Label44.Text = "None"
Label42.Text = "None"
Label31.Text = "None"
Label40.Text = "0"
TextBox1.Clear()
Exit For
End If
Next
答案 0 :(得分:1)
您必须等到循环已遍历DataGridView
的所有行,然后才决定是否添加该行。
尝试使用此代码:
Dim test As Boolean = False
For Each row In BarcodePrintListGrid.Rows
If Label44.Text = row.Cells("Barcode ID").Value Then
test=true
Exit For
End If
Next
if test=false then
BarcodePrintListGrid.Rows.Add(Label47.Text, Label44.Text, Label42.Text, Label31.Text, Label40.Text, 1)
MetroMessageBox.Show(Me, "Item Added to List", "System Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
else
MetroMessageBox.Show(Me, "Item Already Added", "System Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
end if
Label47.Text = "None"
Label44.Text = "None"
Label42.Text = "None"
Label31.Text = "None"
Label40.Text = "0"
TextBox1.Clear()