c# - DataGridView 的总单元格数

标签 c# winforms datagridview

我需要获取数据 GridView 中存在的单元格总数。然后用于确定我是否要在复制/粘贴数据时包含列标题文本,我只希望在选择所有记录时显示它。

我正在使用以下代码来获取单元格总数,但是否有更好的方法来获取此值?

var totalCellCount = DataGridView2.ColumnCount * DataGridView2.RowCount;

我找不到包含所有单元格计数的属性,也许我遗漏了它。有没有更好的方法来获取单元格的数量?

我的 datagridview 将 ClipboardCopyMode 设置为 EnableWithAutoHeaderText,但我想在他们选择网格。所以我在下面的代码中使用了单元格总数:

private void DataGridView_KeyPress(object sender, KeyPressEventArgs e)
{
     if (m_RecordCount == 0)
     return;

      var totalCellCount = DataGridView2.ColumnCount * DataGridView2.RowCount;

      if (DataGridView2.SelectedCells.Count == totalCellCount)
      {
          if (e.KeyChar == (char)3)
          {
            DataGridView2.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            var clipboardContent = this.DataGridView2.GetClipboardContent();

            if (clipboardContent != null)
            {
                Clipboard.SetText(clipboardContent.GetText(TextDataFormat.Text));
            }
            e.Handled = true;
           }
       }
   }  

最佳答案

DataGrid.Items 属性返回一个 DataGridItemCollection,表示 DataGrid 中的 DataGridItems

每个 DataGridItem 代表渲染表中的一行。此外,DataGridItem 公开了一个代表编号的 Cells 属性。呈现表格中的表格单元格(换句话说,列)。从这里如果您需要任何其他自定义场景,您必须将其添加到原始问题或编写解决方案

var rowCount = DataGridView2.Items.Count; //Number of Items...i.e. Rows;

// Get the no. of columns in the first row.
var colCount = DataGridView2.Items[0].Cells.Count;

如果你想要总行数也试试

  1. 如果你想获得项目总数并且你想要一个真实的总数,例如,如果你有多个页面。如果是这样,你不应该试图从 GridView 中找到该信息,而是查看你绑定(bind)您的 GridView。

例子----

 List<SomeObject> lis = GetYourData();
 DataGrid.DataSource = list;
 DataGrid.DataBind();

 // if you want to get the count for a specific page
 int currentPage = 2;
 int countForPage2 = (list.Count > currentPage * totalItemsPerPage)) ?
     totalItemsPerPage : list.Count - ((currentPage - 1) * totalItemsPerPage);

关于c# - DataGridView 的总单元格数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9263586/

相关文章:

C# 鼠标右键单击和控制焦点

c# - Windows 窗体应用程序中的非抗锯齿手形光标

.net - 如何检查datagridview单元格是否为空

c# - LINQ -> XML 处理不存在的元素节点

c# - 匹配模式后从字符串中剪切文本

c# - 我习惯于让 IDE 在 vb.net 下为我创建事件签名,如何使用 C# 来创建事件签名?

c# - 如何在 Datagridview C# 中为特定列设置列标题文本

c# - 将 datagridview 中的数据导出到 excel 工作表窗口窗体

C# 可变长度 args,哪个更好,为什么是 : __arglist, params 数组或 Dictionary<T,K>?

c# - Java TCP 客户端和 C# 服务器;客户端仅在服务器关闭后才收到消息