我对我的代码有一些疑问。我是VB2005的初学者,我想从我的txtISBNInfo& amp;中添加一些我的dgCart(DataGrid)项目。 txtTitleInfo(文本框)。加上它后,itemx必须限制为3,而dgCart(DataGrid)不应包含任何加倍或重复的ov项。我该怎么办?
在我的for each
中,它将确定它是否存在,然后只有在确定它不存在之后才添加新行。我的意思是......在这里,我向你展示了我的代码,但遗憾的是它不起作用......
Private Sub btnAddToCart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddToCart.Click
Dim IsFound As Boolean = False
Dim Count As Integer = dgCart.Rows.Count
For Each dgvRow As DataGridViewRow In dgCart.Rows
If dgvRow.Cells("clmISBN").Value.ToString = txtISBNInfo.Text Then
IsFound = True
'at this point you can actually exit for because you have the info you need.
End If
Next
If IsFound Then
dgCart.Rows.Add(txtISBNInfo.Text, txtTitleInfo.Text)
Else
MsgBox("Already in list!")
End If
End Sub
答案 0 :(得分:1)
我认为你几乎已经拥有了它,但你在最后交换了if
语句
Private Sub btnAddToCart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddToCart.Click
''//Set a flag saying that we have not found the row yet
Dim IsFound As Boolean = False
''//Loop through each row
For Each dgvRow As DataGridViewRow In dgCart.Rows
''//Compare the cell to our inputed
If dgvRow.Cells("clmISBN").Value.ToString = txtISBNInfo.Text Then
''//Flag the we found the item
IsFound = True
''//No need to loop through the remaining rows, exit the loop
Exit For
End If
Next
''If the item was found in the datagrid
If IsFound Then
MsgBox("Already in list!")
Else ''//Otherwise
''//Add it
dgCart.Rows.Add(txtISBNInfo.Text, txtTitleInfo.Text)
End If
End Sub