2012-02-13 80 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