Object reference not set to an instance of an object on retrieving text from datagridview

337 views Asked by At

I have a Datagridview that is bound to a database using binding source. I want to highlight the row or text that has the value that I am searching. But for some reason, it gives me this error:

Object reference not set to an instance of an object.

It points to the line:

Dim cell As DataGridViewCell = (EmployeesDataGridView.Rows(gridRow).Cells(gridColumn))

Dim someText As String = txtSearchLastName.Text
    Dim gridRow As Integer = 0
    Dim gridColumn As Integer = 0
    For Each Row As DataGridViewRow In EmployeesDataGridView.Rows
        For Each column As DataGridViewColumn In EmployeesDataGridView.Columns
            Dim cell As DataGridViewCell = (EmployeesDataGridView.Rows(gridRow).Cells(gridColumn))
            If cell.Value.ToString.ToUpper.Contains(someText.ToUpper) Then
                cell.Style.BackColor = Color.Yellow
            End If
            gridColumn += 1
        Next column
        gridColumn = 0
        gridRow += 1
    Next Row

I've read the meaning of this error, but I cannot correlate its meaning to my code. Thanks.

1

There are 1 answers

1
H. Mahida On BEST ANSWER

Do it like;

 For Each row As DataGridViewRow In EmployeesDataGridView.rows

     For Each cell As DataGridViewCell In row.cells

          If cell.Value.ToString.ToUpper.Contains(someText.ToUpper) Then
               cell.Style.BackColor = Color.Yellow
          End If

     Next

 Next

Hope it helps...!!!