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:
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
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();
}
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.
Do you not mention where you cast the list?
ReplyDeleteIs this incomplete code?
Something like: list = new list