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
Row and Column count of data grid in C#
提问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.Items
property returns a DataGridItemCollection
representing the DataGridItems
in the DataGrid.
该DataGrid.Items
属性返回一个DataGridItemCollection
表示DataGridItems
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.
每个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.DataGrid
is a display widget control, and not a container for records. There is no DataGrid.Rows.Count
property or something similar for finding out the number of columns. What you have to do is to look behind the DataGrid, at the DataSource
property, which in most cases is a DataTable
and take what information you need from there.
其次,我要补充的是, aSystem.Windows.Forms.DataGrid
是一个显示小部件控件,而不是记录的容器。没有DataGrid.Rows.Count
用于找出列数的属性或类似的东西。您需要做的是查看 DataGrid 后面的DataSource
属性,在大多数情况下是一个属性,DataTable
并从那里获取您需要的信息。