C#中数据网格的行数和列数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/838679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:36:50  来源:igfitidea点击:

Row and Column count of data grid in C#

c#datagrid

提问by SyncMaster

Consider I have a data grid, I need to find the number of rows and coulmns in the data grid. How can I do this in C#?

考虑我有一个数据网格,我需要找到数据网格中的行数和列数。我怎样才能在 C# 中做到这一点?

采纳答案by Cerebrus

The DataGrid.Itemsproperty returns a DataGridItemCollectionrepresenting the DataGridItemsin the DataGrid.

DataGrid.Items属性返回一个DataGridItemCollection表示DataGridItemsDataGrid 中的 。

Each DataGridItemis representative of a single row in the rendered table. Also, the DataGridItemexposes a Cellsproperty which represents the no. of tablecells (in other words, the columns) in the rendered table.

每个DataGridItem代表渲染表中的一行。此外,DataGridItem公开了一个Cells代表否的属性。呈现的表格中的表格单元格(换句话说,列)。

int rowCount = myGrid.Items.Count;

// Get the no. of columns in the first row.
int colCount = myGrid.Items[0].Cells.Count;

回答by Eoin Campbell

DataGrids represent actual DataItems.

DataGrids 代表实际的数据项。

DataGrid dg = new DataGrid();

dg.Items.Count; //Number of Items...i.e. Rows;
dg.Items[0].Cells.Count; //Number of columns for that Items

回答by Bogdan M

First of all, to answer your question:

首先,回答你的问题:

DataGrid dataGrid = new DataGrid();
int rowCount = dataGrid.BindingContext[dataGrid.DataSource].Count;

or, if you know for sure the type of the DataSource:

或者,如果您确定知道数据源的类型:

int rowCount = ((DataTable)this.dataGrid.DataSource).Rows.Count;
int columnCount = ((DataTable)this.dataGrid.DataSource).Columns.Count;

((DataTable)this.dataGrid.DataSource).Columns.Count;

Second of all, what I want to add is that a System.Windows.Forms.DataGridis a display widget control, and not a container for records. There is no DataGrid.Rows.Countproperty or something similar for finding out the number of columns. What you have to do is to look behind the DataGrid, at the DataSourceproperty, which in most cases is a DataTableand take what information you need from there.

其次,我要补充的是, aSystem.Windows.Forms.DataGrid是一个显示小部件控件,而不是记录的容器。没有DataGrid.Rows.Count用于找出列数的属性或类似的东西。您需要做的是查看 DataGrid 后面的DataSource属性,在大多数情况下是一个属性,DataTable并从那里获取您需要的信息。