Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row and Column count of data grid in C#

Tags:

c#

datagrid

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#?

like image 471
SyncMaster Avatar asked May 08 '09 07:05

SyncMaster


3 Answers

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;
like image 85
Cerebrus Avatar answered Nov 12 '22 14:11

Cerebrus


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
like image 35
Eoin Campbell Avatar answered Nov 12 '22 13:11

Eoin Campbell


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.

like image 4
Bogdan M Avatar answered Nov 12 '22 12:11

Bogdan M