Sorting GridView

Johnbhatt
Posted by Johnbhatt under ASP.NET category on | Points: 40 | Views : 1351
Code for ASPX Page. GridView.

<asp:GridView ID="gvDetails" runat="server" 
AutoGenerateColumns="False"
onsorting="gvDetails_Sorting">
<Columns>
<asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
<ItemTemplate>
<asp:Label ID="lblFname" runat="server" Text='<%#Eval("FirstName")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
<ItemTemplate>
<asp:Label ID="lblLname" runat="server" Text='<%#Eval("LastName")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location" SortExpression="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>



Code for gvDetails_Sorting Event in aspx.cs page.

SortDirection Function:
public SortDirection dir
{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}

protected void gvDetails_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(BindGridView());
sortedView.Sort = e.SortExpression + " " + sortingDirection;
gvDetails.DataSource = sortedView;
gvDetails.DataBind();
}


Enjoy....

Comments or Responses

Login to post response