Count items in datasource of gridview (.net)
I have a GridView and bind a list to it:
List<T> items = T.GetItems();
GridView.DataSource = items.OrderBy(x => x.SomeValue);
GridView.DataBind();
Now in the process of databinding, I would like to access the total number of items in the datasource.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
//access total numb开发者_如何学Pythoner of datasource items
}
GridView.Rows or GridView.DataKeys is no help because the gridview is being built at this point. Of course, I could use items.Count() but I would prefer to access the underlying datasource directly.
Update
The solutions posted work without the OrderBy statement which I included later.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
var count = ((ICollection<T>)GridView.DataSource).Count;
}
I guess you could access the count of items by doing something like below:
int count = (GridView1.DataSource as List<T>).Count;
Hope this Helps!!
Edit 1:
Added full method used.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int count = (GridView1.DataSource as List<string>).Count;
}
With my update included, the items count can be accessed with
var count = ((IEnumerable<T>)GridView.DataSource).Count();
精彩评论