2013-02-26 53 views
13

有什麼辦法可以使用LINQ風格的查詢來查找DataGridView行嗎?我試圖找到綁定到特定對象並突出顯示的對象。如何使用LINQ查找DataGridView行?

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

錯誤1「System.Windows.Forms.DataGridViewRowCollection」不包含關於「FirstOrDefault」和沒有擴展方法「FirstOrDefault」接受型的第一參數「System.Windows.Forms.DataGridViewRowCollection的定義'可以找到(是否缺少using指令或程序集引用?)

回答

30

你需要轉換爲IEnumerable<DataGridViewRow>因爲DataGridViewRowCollection只實現IEnumerable

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

對於那些誰來到這裏尋找VB版,李的回答翻譯成:

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

此外,如果你像我一樣,並以此來從找到你的DataGridViewRow您綁定DataTable.DataRowDataGridView.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 

這是不是通過你的DataGridView循環查找匹配值更有效。