vb.netgridview

GridView Search with textbox string


I have a DataGrid that is populated with (not from a datasource) and I am trying to search the grid based on the text entered into the textbox. When I click the button I get object reference error but I am not sure why. The idea is the search will find the word and then highlight the cells yellow.

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


Solution

  • We know that DataGridView1 is initialized when you have the error because you referred to DataGridView1.RowCount earlier successfully. DataGridView1.Rows(i) is likely valid too, because i is smaller than RowCount. DataGridView1.Rows(i).Cells(j) is likely valid too, because j is smaller than ColumnCount.

    So either DataGridView1.Rows(i).Cells(j).Value or txtGridSearch is Nothing. Check for those cases:

    If (DataGridView1.Rows(i).Cells(j).Value IsNot Nothing) AndAlso (txtGridSearch IsNot Nothing) AndAlso (DataGridView1.Rows(i).Cells(j).Value.ToString = txtGridSearch.Text) Then