Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use LINQ to find a DataGridView row?

Is there any way to use a LINQ style query to find a DataGridView row? I am trying to find the one bound to a specific object and highlight it.

MyDatagrid.Rows.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;

Error 1 'System.Windows.Forms.DataGridViewRowCollection' does not contain a definition for 'FirstOrDefault' and no extension method 'FirstOrDefault' accepting a first argument of type 'System.Windows.Forms.DataGridViewRowCollection' could be found (are you missing a using directive or an assembly reference?)

like image 903
Darrin Doherty Avatar asked Feb 26 '13 19:02

Darrin Doherty


2 Answers

You need to cast to IEnumerable<DataGridViewRow> since DataGridViewRowCollection only implements IEnumerable:

MyDatagrid.Rows
    .Cast<DataGridViewRow>()
    .FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;
like image 70
Lee Avatar answered Sep 19 '22 16:09

Lee


For those who came here looking for the VB-version, Lee's answer translates to:

MyDatagrid.Rows.Cast(Of DataGridViewRow)().FirstOrDefault(Function(r) r.DataBoundItem Is myItem).Selected = True

Furthermore, if you're like me, and are using this to find your DataGridViewRow from your bound DataTable.DataRow (DataGridView.DataSource = DataTable), then you can access it like this:

Dim MyDataRowSearch() As DataRow = MyDataTable.Select("SomeColumn = SomeValue")
If MyDataRowSearch.Count = 1 Then
  MyDataGrid.Rows.Cast(Of DataGridViewRow)().FirstOrDefault(Function(r) DirectCast(r.DataBoundItem, DataRowView).Row Is MyDataRowSearch(0)).Selected = True
End If

This is much more efficient than looping through your DataGridView looking for matching values.

like image 41
Sturgus Avatar answered Sep 22 '22 16:09

Sturgus