How can I use LINQ to find a DataGridView row?

后端 未结 2 834
我在风中等你
我在风中等你 2021-01-04 01:24

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


        
2条回答
  •  北海茫月
    2021-01-04 01:54

    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.

提交回复
热议问题