winforms 如何使用LINQ查找DataGridView行?

qxsslcnc  于 2023-04-21  发布在  其他
关注(0)|答案(2)|浏览(153)

是否有任何方法可以使用LINQ样式查询来查找DataGridView行?我正在尝试查找绑定到特定对象的行并突出显示它。

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

错误1“System.Windows.Forms.DataGridViewRowCollection”不包含“FirstOrDefault”的定义,并且找不到接受类型为“System.Windows.Forms.DataGridViewRowCollection”的第一个参数的扩展方法“FirstOrDefault”(是否缺少using指令或程序集引用?)

5jvtdoz2

5jvtdoz21#

你需要强制转换为IEnumerable<DataGridViewRow>,因为DataGridViewRowCollection只实现了IEnumerable

using System.Linq;

MyDatagrid.Rows
    .Cast<DataGridViewRow>()
    .FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;
fxnxkyjh

fxnxkyjh2#

对于那些来这里寻找VB版本的人来说,Lee的回答是:

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

此外,如果你像我一样,使用它从绑定的DataTable.DataRowDataGridView.DataSource = DataTable)中找到DataGridViewRow,那么你可以这样访问它:

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

这比在DataGridView中循环查找匹配值要高效得多。

相关问题