2011-03-16 28 views
0

我對我的代碼進行了一些查詢。我是VB2005的初學者,我想在我的txtISBNInfo & txtTitleInfo(Textbox)中添加一些我的dgCart(DataGrid)的項目。在加載它時,itemx必須被限制爲3,並且dgCart(DataGrid)不應該包含任何加倍或重複項目。我該怎麼辦? 在我的for each它將確定它是否存在,然後才確定它不存在,添加一個新行。我的意思是......在這裏,我告訴你我的代碼,但遺憾的是它不工作...我對我的代碼進行了一些查詢n使用DataGrid的VB2005

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 

回答

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 
相關問題