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#.?
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.
int rowCount = myGrid.Items.Count;
// Get the no. of columns in the first row.
int colCount = myGrid.Items[0].Cells.Count;
DataGrids represent actual DataItems.
DataGrid dg = new DataGrid();
dg.Items.Count; //Number of Items...i.e. Rows;
dg.Items[0].Cells.Count; //Number of columns for that Items
First of all, to answer your question:
DataGrid dataGrid = new DataGrid();<br />
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.