.aspx Page
Thank you for reading this post, don't forget to subscribe!<asp:GridView ID=”GridUsers” runat=”server” AutoGenerateColumns=”False” DataKeyNames=”UserId”
EmptyDataText=”No User Found” CellPadding=”4″ ForeColor=”#333333″ GridLines=”None”
AllowSorting=”True” OnRowDataBound=”GridUsers_RowDataBound” OnSorting=”GridUsers_Sorting” Width=”100%”>
<Columns>
<asp:TemplateField HeaderText=”User Name” SortExpression=”UserName” ItemStyle-ForeColor=”White”>
<ItemTemplate>
<asp:LinkButton ID=”lblUsername” runat=”server” Text='<%# Eval(“UserName”) %>’></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.Cs Page
if (!IsPostBack)
{
ViewState[“SortingDirection”] = “”;
}
protected string SortingDirection
{
set
{
ViewState[“SortingDirection”] = value;
}
get
{
if (ViewState[“SortingDirection”].ToString() == “DESC”)
{
ViewState[“SortingDirection”] = “ASC”;
}
else
{
ViewState[“SortingDirection”] = “DESC”;
}
return ViewState[“SortingDirection”].ToString();
}
}
public SortDirection GridViewSortDirection
{
get
{
if (ViewState[“sortDirection”] == null)
ViewState[“sortDirection”] = SortDirection.Ascending;
return (SortDirection)ViewState[“sortDirection”];
}
set { ViewState[“sortDirection”] = value; }
}
protected void GridUsers_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState[“SortExpression”] = e.SortExpression;
bindgrid(e.SortExpression, SortingDirection);
}
private void bindgrid(string sortExp, string sortDir)
{
DataTable dt = ToDataTable<GetUserInformation>(obj);
DataView dv = new DataView();
dv = dt.DefaultView;
if (sortExp != string.Empty)
{
//dv = new DataView(ds.Tables[0]);
dv.Sort = string.Format(sortExp + ” ” + sortDir);
}
GridUsers.DataSource = dv;
GridUsers.DataBind();
}
protected void GridUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
string st = GridUsers.SortExpression;
LinkButton btnSort;
Image image;
//iterate through all the header cells
foreach (TableCell cell in e.Row.Cells)
{
//check if the header cell has any child controls
if (cell.HasControls())
{
//get reference to the button column
btnSort = (LinkButton)cell.Controls[0];
image = new Image();
if (ViewState[“SortExpression”] != null)
{
//see if the button user clicked on and the sortexpression in the viewstate are same
//this check is needed to figure out whether to add the image to this header column nor not
if (btnSort.CommandArgument == ViewState[“SortExpression”].ToString())
{
//following snippet figure out whether to add the up or down arrow
//based on the sortdirection
if (Convert.ToString(ViewState[“SortingDirection”]) == “ASC”)
{
//Set Image Path
image.ImageUrl = “/DesktopModules/IBL-iBLeague/images/up.png”;
}
else
{
//Set Image Path
image.ImageUrl = “/DesktopModules/IBL-iBLeague/images/down.png”;
}
image.CssClass = “UPSorting”;//Add Css
cell.Controls.Add(image);
}
}
}
}
}
}