Sep 4, 2008

Custom GridView Column Sorting

This article shows custom GriView column sorting and adding sorting indicator image in header binding with WbService.

private const string ASCENDING = "ASC";
private const string DESCENDING = "DESC";
private static int headerIndex = 0;
private static string sortDir = string.Empty;
Image sortImage = new Image();

protected void Page_Load(object sender, EventArgs e)
{
}

protected
void gvPropertyList_Sorting(object sender, GridViewSortEventArgs e)
{
RekabuService.WebService rek = new RekabuService.WebService();
List propertyList = new List();

string sortExpression = e.SortExpression;
headerIndex = 1;
switch (sortExpression)
{
case "status":
headerIndex = 2;
break;
case "location":
headerIndex = 3;
break;
case "listprice":
headerIndex = 4;
break;
case "category":
headerIndex = 5;
break;
case "commission":
headerIndex = 6;
break;

}

ViewState["SortExpression"] = sortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
sortDir = DESCENDING;
orderby = sortExpression + " " + DESCENDING;
propertyList = rek.GetProperties("userid='" + userId + "'", searchText, orderby, 0, Convert.ToInt32(gvPropertyList.PageSize)).ToList();
sortImage.ImageUrl = "~/images/desc.gif";
sortImage.CssClass = "sortImage";
}

else
{

GridViewSortDirection = SortDirection.Ascending;
sortDir = ASCENDING;
orderby = sortExpression + " " + ASCENDING;
propertyList = rek.GetProperties("userid='" + userId + "'", searchText, orderby, 0, Convert.ToInt32(gvPropertyList.PageSize)).ToList();
sortImage.ImageUrl = "~/images/asc.gif";
sortImage.CssClass = "sortImage";

}
gvPropertyList.DataSource = propertyList;
gvPropertyList.DataBind();
gvPropertyList.HeaderRow.Cells[headerIndex].Controls.Add(sortImage);

}
private SortDirection GridViewSortDirection
{
get

{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}

0 comments: