Count total rows of gridview with pagination

if you’re using sqldatasource or objectdatasource You need to use the ReturnValue of the ObjectDataSourceStatusEventArgs or SqlDataSourceStatusEventArgs while handling the datasource’s Selected event.

If you are using sqldatasource, you can count the total rows using the ‘Selected’ event which gets fired after the select operation has been completed.

protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
  int rowCount = e.AffectedRows;
}  

If you’re using object data source, it’s important to note that the Selected event on the ODS gets called twice, once returning the data set, and again to call the method you specified in the SelectCountMethod property. Simply test to see if the return is an Int32 in the event.

protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
    if (e.ReturnValue.GetType() == typeof(System.Int32))
        int rowCount = (Int32)e.ReturnValue;
}  

You can find a working example at: http://www.webswapp.com/codesamples/aspnet20/dropdownlist_gridview/default.aspx

if your GridView is being filled by a DataSet or DataTable:

int rowCount=((DataTable)Customer).Rows.Count;

If you are binding the list or array of objects then you can do the following:

int rowCount = ((Customer[])gv.DataSource).Count;

Leave a Comment