Adham Adham - 8 months ago 41
ASP.NET (C#) Question

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

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.


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;

Later you can access the Count from the session.