簡體   English   中英

(C#) DataGridView:如何使用單元格和行獲取選定的計數?

[英](C#) DataGridView: How to get Selected Count with cells AND rows?

所以我有這個DataGridView

而這段代碼:

if(dataGridView1.SelectedRows.Count > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }

如果我有 2 個完全選擇的行,則正確計數為 2。 但我想檢查是否選擇了來自 2 個不同行或更多行的任何單元格

換句話說:在我的圖片中,我當前的選擇目前返回 1,但我希望它返回 2。

謝謝你。

修復后編輯:工作代碼:

if(dataGridView1.SelectedCells.Cast<DataGridViewCell>().Select(c => c.RowIndex).Distinct().Count() > 1)
        {
            MessageBox.Show("Error: More than one value selected");
            return false;
        }

要獲取所選單元格的行數:

int count = dataGridView1.SelectedCells.Cast<DataGridViewCell>()
                                       .Select(c => c.RowIndex).Distinct().Count();

要檢查是否選擇了不止一行:

var selectedCells = dataGridView1.SelectedCells;
bool check = selectedCells.Count > 0 
         && selectedCells.Cast<DataGridViewCell>().Any(c => c.RowIndex != selectedCells[0].RowIndex);

如果您有一個相當標准的設置,其中每一列都綁定到您的支持數據對象的一個​​屬性,並且每一行代表一個對象,則以下內容應該有效:

dataGridView1.SelectedCells.Select(c => c.Item).Distinct().Count()

這將返回不同單元格綁定到的項目數。 由於每個項目都有一行綁定到它,因此它將返回具有至少一個選定單元格的每一行的計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM