Results 1 to 2 of 2
  1. #1

    Thread Starter
    New Member
    Join Date
    Apr 2016

    Stuck finding specific String in a DataGridView


    I have a DataGridView on my form that is populated with data from a website table.
    Now I would like to be able to search for a specific String or Value in the 'entire' grid.
    When the String is found, I would like to get the index of the row it was found on.

    I've tried several methods, none of them seem to work, I always get the error Object is not an instance...
    Like this piece of code below which should paint the cell of the searched string - that I've put into tb1 - yellow, but each time I get the same error.

    Dim searchedText As String = tb1.Text
    Dim gridRow As Integer = 0
    Dim gridColumn As Integer = 0
            For Each Row As DataGridViewRow In dgv.Rows
                For Each column As DataGridViewColumn In dgv.Columns
                    Dim cell As DataGridViewCell = (dgv.Rows(gridRow).Cells(gridColumn))
                    If cell.Value.ToString.Contains(searchedText) Then
                        cell.Style.BackColor = Color.Yellow
                    End If
                    gridColumn += 1
                Next column
                gridColumn = 0
                gridRow += 1
            Next Row
    In this case the error is on the following line:

    If cell.Value.ToString.Contains(searchedText) Then

    Object reference not set to an instance of an object.

    I even tried like every code snippet I could find, modified them to my needs, but I keep getting the same error.

    Is there anything I did wrong with my DataGridView?

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Bristol, UK

    Re: Stuck finding specific String in a DataGridView

    The implication is that there is no value in the cell (and therefore the value cannot be converted to a String).

    Try this modified version:
    If cell.Value IsNot Nothing AndAlso cell.Value.ToString.Contains(searchedText) Then

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts


Click Here to Expand Forum to Full Width