tags:

views:

259

answers:

3

I'm using a stored procedure in a sql database as the data source for a SqlDataSourceControl on my .aspx page. I'm then using the SqlDataSourceControl as the data source for a gridview on my page. Paging is set to true on the gridview. What i would like to do is set the text of a label to the total number of rows in the gridview. I can use this code

'labelRowCount.Text = GridView2.Rows.Count & " layers found"

to return the number of results per page, but it doesn't give me the total. I've looked in several places and haven't been successful in finding a solution.

+1  A: 

Hi,

You should use the underlying datasource that the gridview is bound to (grid.DataSource). For instance if you have bound the grid to a datatable then just cast the grids datasource into the datatable and the use the rows.count property to get the total record count. Another alternative would be to get a reference to the the grids datasource object before you set it to the grid so you can get the record count directly.

So for example (assuming you are bound to a DataTable)

int count = ((DataTable)grid.DataSource).Rows.Count;

Enjoy!

Doug
A: 

GridView2.Rows saves only the rows that are visible, so when page-size is 5 you get only 5 records. As Doug suggested you have to set the labelRowCount.Text ondatabound and not on every postback, because on postback - when the datasource is not binded again - the datasource will be nothing. So a good place could be where you bind the grid to the datasource.

Tim Schmelter
A: 

Put an event handler on "selected" for the SQL DataSource. That event handler has an argument of type SqlDataSourceStatusEventArgs. In there AffectedRows is the row count of the entire data set (not just that shown on the current page). So catch that and write it out to your label:

protected void SqlDataSource_Selected(object sender,SqlDataSourceStatusEventArgs e)
{
    if (e.Exception != null)
    {
        // do something useful, then...
        e.ExceptionHandled = true;
    }
    else
        labelRowCount.Text = String.Format("{0} layers found", e.AffectedRows);
}
philw