如何检查 DataGridView 中是否存在字符串值

How to check whether a string value is present in a DataGridView

我正在处理具有文本框、按钮和数据网格视图的代码。 当我按下按钮时 DataGridView 上不存在 TextBox 中的值时,我想显示 "Data Not Exist"。

到目前为止,这是我的代码

If DataGridView1.Rows.Contains(TextBox1.Text) = False Then
         MessageBox.Show("Data Not Exist!")
End If

您需要遍历所有行和列

Dim isFound As Boolean = False  

      For Each row As GridViewRow  In DataGridView1.Rows
           for i As Integer = 0 to DataGridView1.Columns.Count -1
         If row.Cells[i].Text = TextBox1.text  Then
            isFound = True
            exit for
         End If
           Next
        Next


 If (isFound) Then
      MessageBox.Show("Data Exists!")
 Else
       MessageBox.Show("Data Not Exists!")
 EndIf

您可以使用 LINQForLoop

轻松完成

此代码将搜索 所有 匹配项,它将在 DataGridView 中找到并提示它在 RowColumn 中看到匹配。

对于 ForLoop,您需要 运行 循环 ColumnRow.

Private Sub SearchUsingForLoop()
    Dim resultString As String = Nothing
    For x = 0 To DataGridView1.ColumnCount - 1
        For y = 0 To DataGridView1.RowCount - 1
            If DataGridView1.Item(x, y).Value.ToString.ToUpper = txtSearch.Text.ToUpper Then
                resultString &= " - Column " & x + 1 & " Row " & y + 1 & vbCrLf
            End If
        Next
    Next
    If resultString <> Nothing Then
        resultString = txtSearch.Text & " found in : " & vbCrLf & resultString
    Else
        resultString = "Data does not exist."
    End If
    MsgBox(resultString)
End Sub

请记住 DatagridViewRowDatagridViewColumn 的索引以 0 开头。

另一种方法是 LINQ:

 Private Sub SearchUsingLINQ()
    Dim resultSet = From dgRow As DataGridViewRow In Me.DataGridView1.Rows, _
           dgCell As DataGridViewCell In dgRow.Cells _
      Where dgCell.Value.ToString.ToUpper = txtSearch.Text.ToUpper _
      Select dgCell

    Dim resultString As String = Nothing
    If resultSet.Count > 0 Then
        resultString = txtSearch.Text & " found in :" & vbCrLf
        For Each dgCells In resultSet
            resultString &= " - Column " & dgCells.ColumnIndex + 1 & " Row " & dgCells.RowIndex + 1 & vbCrLf
        Next
    End If

    If resultString <> Nothing Then
        MsgBox(resultString)
    Else
        MsgBox("Data does not exist.")
    End If
End Sub

请随意使用其中任何一个。但是我建议你先研究iterating一个DataGridView