C# – Total cell count of a DataGridView

cdatagridviewwinforms

I need to get the total number of cells that are present in a datagridview. This is then used to determine if I want to include the column header text when copying/pasting the data, I only want this displayed if all records are selected.

I am using the following code to get the total number of cells but is there a better way to get this value?

var totalCellCount = DataGridView2.ColumnCount * DataGridView2.RowCount;

I couldn't find a property that contained a count of all cells, maybe I am missing it. Is there a better way to get the number of cells?

My datagridview has the ClipboardCopyMode set to EnableWithAutoHeaderText, but I want to set it to EnableAlwaysIncludeHeaderText when they select all rows/columns in the grid. So I am using the total number of cells in the code below:

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

Best Answer

The DataGrid.Items property returns a DataGridItemCollection representing the DataGridItems in the DataGrid.

Each DataGridItem is representative of a single row in the rendered table. Also, the DataGridItem exposes a Cells property which represents the no. of tablecells (in other words, the columns) in the rendered table. From here if you need any other custom scenarios you will have to either add it to the original Question or code a solution

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;

if you want the total number of Rows also try

  1. If you want to get at total items an you want a real total for example if you have multiple pages.. If so you shouldn't be trying to find that information from the GridView but instead look at the underlying DataSource that you bound your GridView.

Example ----

 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);
Related Topic