2009-11-04 277 views
5

要求DataGridView返回「已選定單元格的行的索引」的最簡潔方法是什麼?這與DataGridView.SelectedRows不一樣。我不允許選擇行或列。所以用戶必須選擇單元塊。我只需要找出哪些行中有選中的單元格。C# - DataGridView和SelectedCells - 查找所選單元格的行索引

是否有一些聰明的lambda表達式我應該使用? 你會做什麼?

如果這有助於: 在我寫我已經從DataGridView繼承和我在我自己的自定義類DataGridViewExt的代碼。

+0

我覺得應該是某種在LINQ語法SELECT DISTINCT的是我應該做的。 – BuddyJoe 2009-11-04 16:27:24

+0

應該做還是可以做? – 2009-11-04 16:30:27

+0

應該是 - 從某種意義上來說,其他人會從現在開始支持這個代碼庫......如果我能夠用1行而不是3到5來描述這個意圖,那麼這個項目會更好。 – BuddyJoe 2009-11-04 16:33:19

回答

9

LINQ的解決方案:

var rowIndexes = dgv.SelectedCells.Cast<DataGridViewCell>() 
            .Select(cell => cell.RowIndex) 
            .Distinct(); 

編輯:

你只是缺少演員。這是因爲DataGridViewSelectedCellCollection沒有實現一個通用的IEnumerable<DataGridViewCell>,只是IEnumerable,所以當你列舉這些值時,它們的類型爲Object。隨着中投,將給予:

int[] rowIndexes = (from sc in this.SelectedCells.Cast<DataGridViewCell>() 
        select sc.RowIndex).Distinct().ToArray(); 
+0

真棒! +1並回答。只是好奇,但備用語法是什麼?我被絆倒了某處:int [] rowIndexes =(從sc在this.SelectedCells中選擇sc.RowIndex).Distinct()。ToArray();你可以添加到答案? – BuddyJoe 2009-11-04 16:40:00

+0

我編輯了我的答案。 – 2009-11-04 16:52:40

+0

好的。需要閱讀LINQ和.Cast <>()中的一兩篇文章。謝謝。 – BuddyJoe 2009-11-04 17:09:21

1
IEnumerable<int> indexes = 
(from c in dataGridView1.SelectedCells.Cast<DataGridViewCell>() 
    select c.RowIndex).Distinct(); 
相關問題