How to sort gridview using a dropdown list
the specific example i am referring to is this site
http://www.iamextreme.net/category.php?CategoryId=1&SubCatego开发者_JS百科ryId=0&SortBy=name
notice the sort by drop down list. basically i want to sort products according to price,name,popularity??
do i have to requery the database and retreive the sorted data in gridview again, or should i already sort the items in the gridview that are already there??
I tried to this but its the wrong approach, basically i was trying to repopulate data in the page load event, which was giving error.
Now what is the correct approach.
You could have something like this in for the DropDownList's SelectIndexChanged Event
protected void DropDownList1_SelectIndexChanged(object sender, EventArgs e)
{
gvSorting.Sort(DropDownList1.SelectedValue, SortDirection.Ascending);
}
and handle GridView's Sorting event
protected void gvSorting_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtSortTable = gvSorting.DataSource as DataTable;
if (dtSortTable != null)
{
DataView dvSortedView = new DataView(dtSortTable);
dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
gvSorting.DataSource = dvSortedView;
gvSorting.DataBind();
}
}
private static string getSortDirectionString(SortDirection sortDireciton)
{
string newSortDirection = String.Empty;
if (sortDireciton == SortDirection.Ascending)
{
newSortDirection = "ASC";
}
else
{
newSortDirection = "DESC";
}
return newSortDirection;
}
You shouldn't have to requery the database, but it might be better overall (to ensure that new stuff gets into the results while users are browsing).
I would respond to an event (in the example case it'd be SelectedValueChanged on the DropDownList) and do the sorting there. I would sort a collection, which you either keep in Session or re-query each time, then set the GridView's DataSource and re-bind.
精彩评论