2016-04-15 58 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然后”你正在作出一个对象之间的比较,一个整数和一个字符串...这应该失败。 –