首页 文章

DataGridView的总细胞计数

提问于
浏览
1

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

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

var totalCellCount = DataGridView2.ColumnCount * DataGridView2.RowCount;

我找不到包含所有细胞计数的属性,也许我错过了它 . 有没有更好的方法来获得细胞数量?

我的datagridview将 ClipboardCopyMode 设置为 EnableWithAutoHeaderText ,但我想在选择网格中的所有行/列时将其设置为 EnableAlwaysIncludeHeaderText . 所以我使用下面代码中的单元格总数:

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;
           }
       }
   }

1 回答

  • 4

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

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

    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;
    

    如果你想要总行数也尝试

    • 如果你想获得总项目你需要一个真正的总数,例如,如果你有多个页面..如果是这样你不应该试图从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);
    

相关问题