Here is complete code for allow sorting in asp.net gridview:
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{ ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{ ViewState["dirState"] = value;
}
}
protected void gvShowRecord_Sorting(object sender, GridViewSortEventArgs e)
{
string sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(BindGridOfParticipantDetail());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
gvShowRecord.DataSource = sortedView;
gvShowRecord.DataBind();
}
}
and design page require some settings as
1. AllowSorting="True" onsorting="gvShowRecord_Sorting"
2. <asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{ ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{ ViewState["dirState"] = value;
}
}
protected void gvShowRecord_Sorting(object sender, GridViewSortEventArgs e)
{
string sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView(BindGridOfParticipantDetail());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
gvShowRecord.DataSource = sortedView;
gvShowRecord.DataBind();
}
}
and design page require some settings as
1. AllowSorting="True" onsorting="gvShowRecord_Sorting"
2. <asp:BoundField HeaderText="First Name" DataField="FirstName" SortExpression="FirstName" />