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

时间:2016-10-28 05:39:57

标签: vb.net datagridview exists

我正在处理具有TextBox,A Button和Datagrid视图的代码。 当我按下按钮时DataGridView上没有TextBox中的值时,我想显示“Data Not Exist”。

这是我目前的代码

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

2 个答案:

答案 0 :(得分:0)

您需要遍历所有行和列

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

答案 1 :(得分:0)

您可以使用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