验证DataGridView 1中的特定单元格

时间:2013-05-30 02:00:15

标签: vb.net

如何将值文本框传递到 DataGridView 时, DataGridView 行详细信息验证是否已存在?

这是我的功能:argAccount& argPortfolio是文本框值

Function fnValidateAccountPortfolio(ByVal argAccount As String, ByVal 
argPortfolio As String) As Boolean
    Try
        For Each row As DataGridViewRow In Form1.DataGridView1.Rows
            If Not row.IsNewRow Then
                MessageBox.Show(row.Cells(0).Value.ToString & "  Is Already
                Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            End If
        Next
    Catch ex As Exception
        Exit Function
    End Try
End Function

Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Handles BtnSave.Click
  If fnValidateAccountPortfolio(txtAccount.Text, txtPortfolio.Text) = False
  Then
    MessageBox.Show("Successfully Saved", "Save", MessageBoxButtons.OK,
    MessageBoxIcon.Information)
  End If
end sub

1 个答案:

答案 0 :(得分:0)

根据我提供的link这是您要找的内容吗?

Function fnValidateAccountPortfolio(ByVal argAccount As String, ByVal argPortfolio As String) As Boolean

    Dim found As Boolean = False

    For Each Row As DataGridViewRow In DataGridView1.Rows
        For Each cell As DataGridViewCell In Row.Cells
            If Not (cell.Value Is Nothing) Then
               If (CStr(cell.Value).Trim() = argAccount OR CStr(cell.Value).Trim() = argPortfolio)  Then
                  MessageBox.Show(cell.Value.ToString()) ' You could show the value here just to validate but remove it later.
                  found = True
                  Exit For
               End If
            End If

        Next
        If (found) Then
            Exit For
        End If
    Next

    Return found
End Function

因此,您将调用此函数,如

if (fnValidateAccountPortfolio("1001","PortfolioHere")) Then
    MessageBox.Show("Entry exist already in the DataGrid!!!")
Else
    MessageBox.Show("Successfully Saved", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
End if