ASP.NET GridView Default Sort

I have a simple gridview control associated with an sql data source. Now I have enabled sorting, but when I click on a column to sort, it sorts it in ascending order. When I click the same column again, it sorts it in descending order. I want to change that. I want him to sort Descending on the first click, and ascending on the second. How to do it?

Here is my Gridview control code:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" > <AlternatingRowStyle BackColor="#CCCCCC" /> <Columns> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" /> <asp:BoundField DataField="Matches" HeaderText="Matches" SortExpression="Matches" /> <asp:BoundField DataField="Points" HeaderText="Points" SortExpression="Points" /> <asp:BoundField DataField="Tries" HeaderText="Tries" SortExpression="Tries" /> <asp:BoundField DataField="Conversions" HeaderText="Conversions" SortExpression="Conversions" /> <asp:BoundField DataField="Penalties" HeaderText="Penalties" SortExpression="Penalties" /> <asp:BoundField DataField="Drop Goals" HeaderText="Drop Goals" SortExpression="Drop Goals" /> <asp:BoundField DataField="Yellow Cards" HeaderText="Yellow Cards" SortExpression="Yellow Cards" /> <asp:BoundField DataField="Red Cards" HeaderText="Red Cards" SortExpression="Red Cards" /> </Columns> <FooterStyle BackColor="#CCCCCC" /> <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /> <SortedAscendingCellStyle BackColor="#F1F1F1" /> <SortedAscendingHeaderStyle BackColor="#808080" /> <SortedDescendingCellStyle BackColor="#CAC9C9" /> <SortedDescendingHeaderStyle BackColor="#383838" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT * FROM [statstable]"></asp:SqlDataSource> 
+4
source share
6 answers
 public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { // Set your deault sort expression and direction. if (String.IsNullOrEmpty(MyGridView.SortExpression)) MyGridView.Sort("SortExpression", SortDirection.Ascending); } } 
+12
source

Why is it easy when it can be tough guys?

 protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e) { // If you want to only switch default for some column, disable comment //switch (e.SortExpression) //{ // case "MyDataField01": // case "MyDataField03": if (e.SortExpression != ((GridView)sender).SortExpression) { e.SortDirection = SortDirection.Descending; } // break; // default: // break; //} } 

Of course, bind the OnSorting event in a GridView in aspx. Source: http://csc-technicalnotes.blogspot.com/2010/06/change-gridview-sortdirection-default.html

+3
source

I would recommend that you look at this post and cancel the logic of the up / down flags.

GridView Sort: Sort always grows

Your ASPX page will look like a grid (pay particular attention to the OnSorting part):

 <asp:GridView ID="grdHeader" AllowSorting="true" AllowPaging="false" AutoGenerateColumns="false" Width="780" runat="server" OnSorting="grdHeader_OnSorting" EnableViewState="true"> <Columns> <asp:BoundField DataField="Entitycode" HeaderText="Entity" SortExpression="Entitycode" /> <asp:BoundField DataField="Statusname" HeaderText="Status" SortExpression="Statusname" /> <asp:BoundField DataField="Username" HeaderText="User" SortExpression="Username" /> </Columns> </asp:GridView> 

Then your CodeBehind (aspx.cs) will need to implement the grdHeader_OnSorting method. Variables in GridViewSortEventArgs will tell you which direction the user has asked to sort. In your case, you will do the opposite ... for example:

 protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e) { List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection(); SortDirection dir = e.SortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, dir)); grdHeader.DataSource = items; grdHeader.DataBind(); } 

Here the items.Sort method does all the sorting ... all you do is the result of the sort and binding it to your data source.

If you need more information about the GridView sorting concept, I would recommend looking at this example on MSDN: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sort.aspx

Let me know if there is anything else I can do to clarify.

0
source

I am afraid that the default behavior, if you want to change it, you should implement the OnSorting event in the GridView and switch the behavior based on the sort expression. For example, if the sort expression is TEAM DESC , you must sort TEAM ASC and vice versa.

Something like this (if your SelectCommand is a simple select statement without an order by clause):

  protected void GridView1_Sorting(Object sender, GridViewSortEventArgs e) { string originalSelectCommand = SqlDataSource1.SelectCommand; if (e.SortDirection == "ASC")//sort data source in DESC { if(e.SortExpression=="Team") { SqlDataSource1.SelectCommand=SqlDataSource1.SelectCommand + " Order BY TEAM DESC"; } else if(e.SortExpression=="Another Column") //etc { } } else //Sort data source in ASC { } SqlDataSource1.Select(DataSourceSelectArguments.Empty); GridView1.DataBind(); SqlDataSource1.SelectCommand=originalSelectCommand;//revert back to original w/o order by } 

All you need to do for markup:

  <asp:GridView ID="GridView1" runat="server" OnSorting="GridView1_Sorting" AllowSorting="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" > <AlternatingRowStyle BackColor="#CCCCCC" /> 

Warning: the above code has not been tested at all, but I think it should do what you want.

0
source

I found a solution on another forum, but it still has flaws. I wanted the default sort to sort by default by first clicking in descending order, not ascending order. But when I click on another column again, it sets the sort direction again. It alternates between descending and ascending on each click, regardless of which column. Now I really want the first click on the any column to decrease, and if I click on any column a second time, it should be upward. Example: I have 2 columns, one is salary and the other is age. Now I click on the salary, and the first direction of sorting decreases, not ascending by default (which the code does). Now, when I click on the age, it switches the sort direction in ascending order, I want it to remain the same when I switch to another column, BUT you need to click on the salary again a second time, it should switch to ascending (the reason it was first click). Any suggestions?

Code: `

 public SortDirection GridViewSortDirection { get { if (ViewState["sortDirection"] == null) //if viewstate doesn't contain any value, assume SortDirection.Ascending(cause thats the asp default) ViewState["sortDirection"] = SortDirection.Ascending; return (SortDirection)ViewState["sortDirection"]; } set { ViewState["sortDirection"] = value; //Viewstate sort direction is set as a variable, so can contain either asc or desc } } protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e) { if (ViewState["sortDirection"] == null) { e.SortDirection = SortDirection.Descending; } else if (GridViewSortDirection == SortDirection.Ascending) { e.SortDirection = SortDirection.Descending; } else if (GridViewSortDirection == SortDirection.Descending) { e.SortDirection = SortDirection.Ascending; } GridViewSortDirection = e.SortDirection; } 

`

0
source

I searched for searches because I had the same question and I played, and found that if I added "ORDER BY [Field Name]" in my SQL statement and enabled sorting, whenever I clicked on the header, the order of any of the columns! I see that this is a very old thread, but maybe this will help in the future for someone else. As a deeper answer, here is my code for my data source:

 <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/webvideos.mdb" DeleteCommand="DELETE FROM [Docs] WHERE [ID] = ?" InsertCommand="INSERT INTO [Docs] ([ID], [Filename], [Label], [Section], [Index]) VALUES (?, ?, ?, ?, ?)" SelectCommand="SELECT * FROM [Docs] ORDER BY ID" UpdateCommand="UPDATE [Docs] SET [Filename] = ?, [Label] = ?, [Section] = ?, [Index] = ? WHERE [ID] = ?"> 

And here is my gridview:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="AccessDataSource1" AllowPaging="True" PageSize="20" AllowSorting="True"> <Columns> <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" /> <asp:BoundField DataField="Label" HeaderText="Label" SortExpression="Label" /> <asp:BoundField DataField="Filename" HeaderText="Filename" SortExpression="Filename" /> <asp:BoundField DataField="Section" HeaderText="Section" SortExpression="Section" /> <asp:BoundField DataField="Index" HeaderText="Index" SortExpression="Index" /> </Columns> </asp:GridView> 
0
source

All Articles