How to sort gridview using dropdown

the specific example I am referring to is the site

http://www.iamextreme.net/category.php?CategoryId=1&SubCategoryId=0&SortBy=name

Pay attention to the sorting by the drop-down list. I mainly want to sort products by price, name, popularity

Do I need to query the database and return the sorted data to the gridview again, or am I already sorting the elements in the gridview that already exist?

I tried to do this, but it was the wrong approach, basically I tried to re-populate the data in the page load event, which gave an error.

Now what is the right approach.

+3
source share
2 answers

- DropDownList SelectIndexChanged

protected void DropDownList1_SelectIndexChanged(object sender, EventArgs e)
        {
            gvSorting.Sort(DropDownList1.SelectedValue, SortDirection.Ascending);
        }

GridView

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;
}
+3

, ( , , ).

( SelectedValueChanged DropDownList) . , , , DataSource GridView .

+1

All Articles