问题
how I do a sorting in a gridView with data bound by a ObjectDataSource?
回答1:
Here is a question that has been previously answered.
For the actual sorting, you would call
collectionOfObjects.OrderBy(x => x.PropertyToSortOn);
You could use a switch to change what to sort on based on what is passed into the method via the args. So it would look a little more like this
switch(propertyName)
{
case "property1":
collectionOfObjects.OrderBy(x => x.PropertyToSortOn);
break;
case "property2":
collectionOfObjects.OrderBy(x => x.OtherPropertyToSortOn);
break;
...
}
Hope this helps! :)
回答2:
If is more easy for you, why dont you try to sort it from the store procedure or the query. Maybe is not the optimun solution but it could be easier.
EDIT
IF you want to do it programattically with the gridview controls, Take a look at this code:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtSortTable = GridView1.DataSource as DataTable;
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
GridView1.DataSource = dvSortedView;
GridView1.DataBind();
}
}
private string getSortDirectionString(SortDirection sortDireciton)
{
string newSortDirection = String.Empty;
if (sortDireciton == SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
来源:https://stackoverflow.com/questions/4876660/asp-net-sorting-with-gridview-and-objectdatasource