2012-02-13 71 views
1

我需要获取datagridview中存在的细胞总数。然后,这用于确定在复制/粘贴数据时是否要包含列标题文本,我只希望在选中所有记录时显示该文本。DataGridView的细胞总数

我使用下面的代码来获取单元格的总数,但有没有更好的方法来获得这个值?

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

回答

3

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中找到这些信息,而是看看你绑定GridView的底层DataSource。

例----

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); 
+0

但是如果我想细胞的总数,我还是要乘两个数字,是否正确? – Taryn 2012-02-13 16:07:00

+0

你有寻呼吗?如果是这样,那么我的答案将需要扩大..让我知道,以便我可以附加一个额外的选项,如果你有多个页面 – MethodMan 2012-02-13 16:23:49

+0

我没有分页。我使用单元格的总数来确定是否应该包含列标题文本,因此如果它们将数据粘贴到Excel中,它们就会包含标题。我更新了我的OP更多细节。 – Taryn 2012-02-13 17:39:02