我需要获取数据 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;
如果你想要总行数也试试
- 如果你想获得项目总数并且你想要一个真实的总数,例如,如果你有多个页面。如果是这样,你不应该试图从 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/