在不设置选择模式的情况下获取所选行/列计数 [英] Get selected Row/Columns Count without Setting Selection Mode

查看:132
本文介绍了在不设置选择模式的情况下获取所选行/列计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataGridView,我希望提供一个导出所选行和列的功能,以便excel

I have a DataGridView and I wish to provide a feature of Exporting Selected Rows and Columns to excel

但是,我的选定的行数总是出现为零,所以我做了

However, My Selected row count was always coming out to be ZERO, so I did

 dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

现在,我无法选择Individual列,每当我选择任何行,它会选择所有列为完整行选择

Now, I can not select Individual columns, whenever I select any row, It selects all columns being a full row select

与列相同也是如此
如果我执行

Same is the case with Columns as well If I do

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect;

它选择整列。

如果我不做这个选择模式,那么

if I don't do this selection Modes, then

dataGridView1.SelectedRows.Count & dataGridView1.SelectedColumns.Count 

总是返回零。

如何在图像中进行设置?

How Can I make something like in the Image ?

推荐答案

以下是如何获取选定的行:

Here's how you can get the selected rows:

var selectedRows =
    this.dataGridView1.SelectedCells.Cast<DataGridViewCell>()
        .Select(cell => cell.OwningRow)
        .Distinct()
        .OrderBy(row => row.Index);

您可以调用 Count 得到计数,而不是枚举两次,调用 ToArray ,然后获取数组的长度

You can either call Count on that to get the count but, rather than enumerating twice, call ToArray and then get the Length of the array.

这篇关于在不设置选择模式的情况下获取所选行/列计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆