![](/img/trans.png)
[英]How can i use LINQ to pass highlighted Cells to another DataGridView?
[英]How can I use LINQ to find a DataGridView row?
有沒有辦法使用LINQ樣式查詢來查找DataGridView行? 我試圖找到綁定到特定對象的那個並突出顯示它。
MyDatagrid.Rows.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;
錯誤1'System.Windows.Forms.DataGridViewRowCollection'不包含'FirstOrDefault'的定義,並且沒有可以找到接受類型'System.Windows.Forms.DataGridViewRowCollection'的第一個參數的擴展方法'FirstOrDefault'(你錯過了嗎?使用指令或程序集引用?)
您需要轉換為IEnumerable<DataGridViewRow>
因為DataGridViewRowCollection
只實現IEnumerable
:
MyDatagrid.Rows
.Cast<DataGridViewRow>()
.FirstOrDefault(r => r.DataBoundItem == myItem).Selected = true;
對於那些來這里尋找VB版本的人來說,Lee的答案轉化為:
MyDatagrid.Rows.Cast(Of DataGridViewRow)().FirstOrDefault(Function(r) r.DataBoundItem Is myItem).Selected = True
此外,如果您像我一樣,並且正在使用它從綁定的DataTable.DataRow
( DataGridView.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
尋找匹配值要高效得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.