Reputation: 3424
the specific example i am referring to is this site
http://www.iamextreme.net/category.php?CategoryId=1&SubCategoryId=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.
Upvotes: 3
Views: 4285
Reputation: 108957
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;
}
Upvotes: 3
Reputation: 71563
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.
Upvotes: 1