65.9K
CodeProject is changing. Read more.
Home

Sorting with Up and Down icons

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1 vote)

Apr 19, 2010

CPOL

1 min read

viewsIcon

13704

1. First we need to create two variables in ViewState to store current direction and expression:public string CurrentSortExpression { get { if (ViewState["sortExpression"] != null) { return...

1. First we need to create two variables in ViewState to store current direction and expression: public string CurrentSortExpression { get { if (ViewState["sortExpression"] != null) { return ViewState["sortExpression"].ToString(); } else { ViewState["sortExpression"] = string.Empty; return string.Empty; } } set { ViewState["sortExpression"] = value; } } public string CurrentSortDirection { get { if (ViewState["sortDirection"] != null) { return ViewState["sortDirection"].ToString(); } return string.Empty; } set { ViewState["sortDirection"] = value; } } 2. Then we have to implement handler to attach sort icons to header rows: protected void GridViewSortImages(object sender, GridViewRowEventArgs e) { GridView senderGridView = (GridView)sender; Literal space = new Literal(); space.Text = " "; if (e.Row != null && e.Row.RowType == DataControlRowType.Header) { for(int i=0;i<gvusers.columns.count;i++)> { TableCell cell = e.Row.Cells[i]; DataControlField column=gvUsers.Columns[i]; if (cell.HasControls()) { LinkButton button = cell.Controls[0] as LinkButton; if (button != null) { Image image = new Image(); image.ImageUrl = "~/AdminUI/Images/icon-sort_default.gif"; if (CurrentSortExpression==column.SortExpression) { if (CurrentSortDirection=="asc") image.ImageUrl = "~/AdminUI/Images/icon-sort1.gif"; else if (CurrentSortDirection=="desc") image.ImageUrl = "~/AdminUI/Images/icon-sort2.gif"; } cell.Controls.Add(image); } } } } } 3. Farther let's make some logic in Sorting handler for our GridView: protected void gvUsers_Sorting(object sender, GridViewSortEventArgs e) { if (CurrentSortExpression == e.SortExpression.ToString()) { if (CurrentSortDirection == "asc") CurrentSortDirection = "desc"; else CurrentSortDirection = "asc"; } else { CurrentSortExpression = e.SortExpression.ToString(); CurrentSortDirection = "asc"; } BindUsers(0, CurrentSortExpression, (CurrentSortDirection == "asc")?true:false); } 4. And at last lets use GridViewSortImages in RowCreated event: protected void gvUsers_RowCreated(object sender, GridViewRowEventArgs e) { // Some code GridViewSortImages(sender, e); }