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.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Ja va said...

Do you not mention where you cast the list?
Is this incomplete code?
Something like: list = new list