Monday, May 25, 2009

GridView Sorting

protected void gridViolationDetails_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dtsort = (DataTable)ViewState["viewStatViolation"];

string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, "DESC", gridViolationDetails, dtsort);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, "ASC", gridViolationDetails, dtsort);
}
}

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

private void SortGridView(string sortExpression, string direction,GridView grdV,DataTable dt)
{
DataView dv = new DataView(dt);
dv.Sort = sortExpression + " " + direction;
grdV.DataSource = dv;
grdV.DataBind();
}

No comments: