Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the count of records in the DataSource of the GridView

Tags:

c#

.net

asp.net

I have a grid view already binded with model, Now I want to get the count of the rows in this GridView's Datatable ? not on the page count.

like image 777
Adham Avatar asked Dec 12 '22 17:12

Adham


2 Answers

You can cast datasource in collection and then count as follow

var count = ((ICollection<T>)GridView.DataSource).Count;

Or if you have datatable as source then

DataTable dt = gridView.DataSource as DataTable; 
 int count = dt.Rows.Count;
like image 139
शेखर Avatar answered Dec 14 '22 06:12

शेखर


You can convert the GridView's DataSource to DataTable or DataView and then count the rows.

DataTable dt = (DataTable) gridView.DataSource; 
int count = dt.Rows.Count;

But this will be available only at the time of binding, not across the postback.

To get the row count on post back, you can store the DataTable or its row count in session before binding it to the GridView.

DataTable dt = GetDataSourceTable();
Session["RowsCount"] = dt.Rows.Count;
Session["DataTable"] = dt; //Should be avoided since session are per user. 
gridView.DataSource = dt;
gridView.DataBind();

Later you can access the Count from the session.

like image 25
Habib Avatar answered Dec 14 '22 07:12

Habib