ASP.NET GridView Row Count with ObjectDataSource

Continuing my ASP.NET GridView Tips and Tricks series, this post shows how to get the total row count when the ASP.NET GridView is bound with an ObjectDataSource.

To get the total row count returned from an ObjectDataSource, we will use the ObjectDataSource.Selected Event. In this example, I am using a ObjectDataSource bound to a List<Employees> collection. I am also using a Label Control called lblCount to display the total rows returned. The mark up is similar to the one shown below:

ObjectDataSource Row Count

The Selected event checks the values of a return value, output parameters or exceptions. The return value, output parameters, and exception handling properties are available from the ObjectDataSourceStatusEventArgs object, associated with the event. Use the following code to display the row count

ObjectDataSource Row Count

Note: In this example, I have cast to List<Employees>. If you are returning a DataTable from your ObjectDataSource method, then use this code instead, which gets the ReturnValue property, casts it to a DataTable and then retrieves the Count from the Rows collection.

if(e.Exception == null && e.ReturnValue != null){
e.AffectedRows = ((DataTable)e.ReturnValue).Rows.Count;
lblCnt.Text = e.AffectedRows.ToString();
}

ObjectDataSource Row Count

Alternatively, you can also use the ObjectDataSource.SelectCountMethod Property which identifies a business object method that you can add to your Business layer to return a total row count. The SelectCountMethod property will work only if the EnablePaging property is set to true on the ObjectDataSource.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: