DataGridView 使用文本框字符串搜索[重复]

问题描述 投票:0回答:1

我有一个填充了(不是来自数据源)的 DataGridView,我试图根据输入到文本框中的文本来搜索网格。当我单击按钮时,出现对象引用错误,但我不确定原因。这个想法是搜索将找到该单词,然后将单元格突出显示为黄色。

Private Sub btnApply_Click(sender As Object, e As EventArgs) Handles btnApply.Click
        Dim temp As Integer = 0
        For i As Integer = 0 To DataGridView1.RowCount - 1
            For j As Integer = 0 To DataGridView1.ColumnCount - 1
                If DataGridView1.Rows(i).Cells(j).Value.ToString = txtGridSearch.Text Then --'Object reference not set to an instance of an object
                    temp = 1
                    DataGridView1.Rows(i).Cells(j).Style.BackColor = Color.Yellow
                End If
            Next
        Next
        If temp = 0 Then
            MsgBox("Item not found")
        End If
    End Sub

vb.net gridview
1个回答
2
投票

我们知道当您出现错误时,

DataGridView1
会被初始化,因为您之前成功引用了
DataGridView1.RowCount
DataGridView1.Rows(i)
也可能有效,因为
i
小于
RowCount
DataGridView1.Rows(i).Cells(j)
也可能有效,因为
j
小于
ColumnCount

所以

DataGridView1.Rows(i).Cells(j).Value
txtGridSearch
都是
Nothing
。检查这些情况:

If (DataGridView1.Rows(i).Cells(j).Value IsNot Nothing) AndAlso (txtGridSearch IsNot Nothing) AndAlso (DataGridView1.Rows(i).Cells(j).Value.ToString = txtGridSearch.Text) Then
© www.soinside.com 2019 - 2024. All rights reserved.