C# 如何使用 LINQ 查找 DataGridView 行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15098071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use LINQ to find a DataGridView row?
提问by Darrin Doherty
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.
有没有办法使用 LINQ 样式查询来查找 DataGridView 行?我试图找到绑定到特定对象的那个并突出显示它。
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?)
错误 1“System.Windows.Forms.DataGridViewRowCollection”不包含“FirstOrDefault”的定义,并且找不到接受“System.Windows.Forms.DataGridViewRowCollection”类型的第一个参数的扩展方法“FirstOrDefault”(您是否缺少使用指令或程序集引用?)
采纳答案by Lee
You need to cast to IEnumerable<DataGridViewRow>
since DataGridViewRowCollection
only implements IEnumerable
:
您需要强制转换为IEnumerable<DataGridViewRow>
因为DataGridViewRowCollection
仅实现IEnumerable
:
MyDatagrid.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;
回答by Sturgus
For those who came here looking for the VB-version, Lee's answer translates to:
对于那些来这里寻找 VB 版本的人,Lee 的回答转化为:
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:
此外,如果你像我一样,并且正在使用它DataGridViewRow
从你的边界DataTable.DataRow
( DataGridView.DataSource = DataTable
) 中找到你的,那么你可以像这样访问它:
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.
这比循环DataGridView
查找匹配值要高效得多。