简体   繁体   中英

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

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.

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...!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM