2016-04-15 101 views
1

你們能幫助我如何做到這一點嗎?我想要添加項目的行驗證。我有一個datagridview名爲datagridview1與列dgvTxtItemCode,dgvTxtItemDesc等。我想添加一個驗證,其中每當輸入相同的項目代碼或項目描述時,會出現一個消息框,說明它已經添加。vb.net中的Datagridview RowValidation

因此,這裏是我的代碼,

Function isAlreadyAdded(itemCode As String, itemName As String) As Boolean 
    Dim bFLAG As Boolean 
    For Each r As DataGridViewRow In DataGridView1.Rows 
     If r.Cells(0).Value = r.Index = itemCode AndAlso r.Index = itemName Then 
      bFLAG = True 
      Exit For 
     End If 
    Next 
    Return bFLAG 
End Function 



    Private Sub AddDelivery_RowValidating(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DataGridView1.RowValidating 
    With DataGridView1 
     If isAlreadyAdded(.Rows(e.RowIndex).Cells(dgvTxtItemDesc.Name).Value, e.RowIndex) Then 
      MessageBox.Show("Item was already added!", "Duplicate", MessageBoxButtons.OK, MessageBoxIcon.Warning) 
      e.Cancel = True 
      Exit Sub 
     End If 
    End With 
End Sub 

這是我的頂峯,所以我真的需要你的幫助。感謝你們。

+0

它說'GNC-SAK-062'這是我的itemCode,無法轉換爲布爾值 – noob

+0

爲什麼不在'CellValidating'上做這件事? – jmcilhinney

+0

你的意思是代替.rows,它會是.cells? – noob

回答

0

嘗試處理cellvalidating事件而不是rowvalidating。就像這樣:

Private Sub AddDelivery_RowValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DgOperacionsArticles.CellValidating 
    With DataGridView1 
     If isAlreadyAdded(.Rows(e.RowIndex).Cells(dgvTxtItemDesc.Name).Value, e.RowIndex)=True Then 
      MessageBox.Show("Item was already added!", "Duplicate", MessageBoxButtons.OK, MessageBoxIcon.Warning) 
      e.Cancel = True 
      Exit Sub 
     End If 
    End With 
End Sub 

而且也,以確保這個工程,definí布爾爲False默認:

Dim bFLAG As Boolean = False 

希望這有助於!

+0

它不工作先生。它說像我的項目代碼不能轉換爲雙重 – noob

+0

我認爲你在這一行中有一個問題:「如果r.Cells(0).Value = r.Index = itemCode AndAlso r.Index = itemName然後」你正在作出一個對象之間的比較,一個整數和一個字符串...這應該失敗。 –