简体   繁体   English

(C#) DataGridView:如何使用单元格和行获取选定的计数?

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

So I have this DataGridView所以我有这个DataGridView

And This code:而这段代码:

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

It counts correctly to 2 if I have 2 completly selected rows.如果我有 2 个完全选择的行,则正确计数为 2。 But I want to check if any cells from 2 different rows or more are selected.但我想检查是否选择了来自 2 个不同行或更多行的任何单元格

In other words: in my picture my current selection is returning 1 at the moment but i want it to return 2.换句话说:在我的图片中,我当前的选择目前返回 1,但我希望它返回 2。

Thank you.谢谢你。

Edit after fix: Working code:修复后编辑:工作代码:

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

To get the number of rows with selected cells :要获取所选单元格的行数:

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

To check if more than one row is selected:要检查是否选择了不止一行:

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

If you have a fairly standard setup where each column is bound to a property of your backing data object, and each row represents one object, the following should work:如果您有一个相当标准的设置,其中每一列都绑定到您的支持数据对象的一个​​属性,并且每一行代表一个对象,则以下内容应该有效:

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

This will return the number of items the different cells are bound to.这将返回不同单元格绑定到的项目数。 Since each item has one row that binds to it, it will return the count of every row with at least one selected cell.由于每个项目都有一行绑定到它,因此它将返回具有至少一个选定单元格的每一行的计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM