I have a gridview with sorting enabled:
<asp:GridView ID="grid1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" AllowSorting="true" OnSorting="grid1_Sorting">
<Columns>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID="NameLabel" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Then in my sorting event I have
VB.NET
Page load
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ViewState("Order") = "DESC"
End If
End Sub
Protected Sub grid1_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grid1.Sorting
Select Case e.SortExpression
Case "Name"
If ViewState("Order") = "DESC" Then
grid1.DataSource = DescData()
grid1.DataBind()
ViewState("Order") = "ASC"
Exit Select
Else
grid1.DataSource = AscData()
grid1.DataBind()
ViewState("SortOrder") = "DESC"
Exit Select
End If
End Select
C#
protected void grid1_Sorting(object sender, GridViewSortEventArgs e)
{
switch (e.SortExpression) {
case "Name":
if (e.SortDirection == SortDirection.Ascending) {
grid1.DataSource = AscendingData();
grid1.DataBind();
e.SortDirection = SortDirection.Descending;
break;
} else {
grid1.DataSource = DescendingData();
grid1.DataBind();
e.SortDirection = SortDirection.Ascending;
break;
}
break;
}
}
I've read many articles but most seem to target a dataTable or using Viewstate. This gives me the impression I am missing something to get the above working.
The problem I have is when I click a column to sort it goes through BOTH if conditions (that is Ascending and then Descending code) but I don't understand why?