如何使用函数防止datagridview重复记录

时间:2019-10-25 12:52:25

标签: vb.net datagridview

我使用函数来防止同一条记录进入我的datagridview但它不起作用,当我将代码分离出来然后它起作用了

我试图将for循环部分分离出来,然后使代码工作,但我希望使用函数来做到这一点,以便使代码看起来更整洁

Private Sub PicFavNote10_Click(sender As Object, e As EventArgs) Handles picFavNote10.Click
       If validationDataGrid(lblNameNote10.Text) <> True Then
           'if item didn added to the favorite data table yet
           'add to favorite table
           addTofavorite(lblUserLogin.Text, lblNameNote10.Text, lblDecpNote10.Text, txtPicNote10.Text, "SmartPhone", lblPriceNote10.Text)
       End If
       lblPriceNote10.Text = FormatCurrency(lblPriceNote10.Text)
   End Sub
   Private Function validationDataGrid(ByRef data As String) As Boolean
       'validation on data grid view
       For Each itm As DataGridViewRow In DGTFavTable.Rows 'loop though every item in datagrid
           If itm.Cells(0).Value = data Then 'check wherter the text already exist
               MsgBox(data & " Already added to your favorite cart")
               Return True
           Else
               Return False
           End If
       Next
   End Function

我希望MsgBox(数据和“已添加到您喜欢的购物车”)会执行,但是validationDataGrid函数返回false值,即使该商品已经添加到喜欢的datagridview中。

1 个答案:

答案 0 :(得分:0)

在循环所有行之前,您需要调用此子项,这是一种有效的解决方法,可以验证DataGridView上的新数据:

Private Sub ForceGridValidation()

    'Get the current cell
    Dim currentCell As DataGridViewCell = DGTFavTable.CurrentCell

    If currentCell IsNot Nothing Then
        Dim colIndex As Integer = currentCell.ColumnIndex
        If colIndex < DGTFavTable.Columns.Count - 1 Then
            DGTFavTable.CurrentCell = DGTFavTable.Item(colIndex + 1, currentCell.RowIndex)

        ElseIf colIndex > 1 Then
            DGTFavTable.CurrentCell = DGTFavTable.Item(colIndex - 1, currentCell.RowIndex)
        End If

        'Set the original cell 
        DGTFavTable.CurrentCell = currentCell
    End If

End Sub
相关问题