Thursday, May 5, 2011

Searching through a datagridview control in Visual Studio

There are lots of ways of searching a datagridview in VB. Depending on different situations you might want to choose the one that most suitable to your situation.
Today I was asked by someone how to do a search if he doesn't have a databinding(hence, can't search in bindingsource), meanwhile, he also knows that which column his searching target will be, which makes it quite easy. heres the code:


        For i As Integer = 0 To Datagridview1.RowCount - 1
        'Cell(2) here is the column our results located
            If Datagridview1.Rows(i).Cells(2).Value.ToString.Contains("Cake") Then
                Datagridview1.Rows(i).Selected = True           'Move Cursor to this row
            End If
        Next

If you want to search an entire datagridview without knowing which column, a nested for loop will solve this quite handy as well:

        For i As Integer = 0 To Datagridview1.RowCount - 1
            For k As Integer = 0 To dgvAccural.ColumnCount - 1
                If Datagridview1.Rows(i).Cells(k).Value.ToString.Contains("Cake") Then
                    Datagridview1.Rows(i).Selected = True       'Move Cursor to this row
                End If
            Next
        Next

Above solutions are handy for small recordsets, if you have a very large recordset, it is still recommended to use search in bindingsource, or use LINQ to search through your list

No comments:

Post a Comment