question

venkateshpadmanabhan-5594 avatar image
0 Votes"
venkateshpadmanabhan-5594 asked LanHuang-MSFT answered

Gridview - Multi-column sorting

Hi.
I am using VS 2017 and ASP.NET C# website. I am trying to achieve multi column sorting in Gridview ? I have added allowsorting to true and added sortexpression on all BoundField columns. However, the sorting does not work on multiple columns. Below is the code used . How to fix this?

 <div class="table-responsive">
                         <asp:GridView ID="grdSearch" runat="server" 
                             GridLines="Both" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false" ShowHeaderWhenEmpty="true"
                             PageSize="25" OnPageIndexChanging="grdSearch_PageIndexChanging"   >                           
                             <EmptyDataTemplate>No Records Available</EmptyDataTemplate>
                             <Columns>
                                 <asp:BoundField DataField="Description" SortExpression="Description" HeaderText="Class" />
                                 <asp:BoundField DataField="DK1" SortExpression="DK1" HeaderText="Key 1" ItemStyle-Width="100px" ItemStyle-Wrap="true" />
                                 <asp:BoundField DataField="DK2" SortExpression="DK2" HeaderText="Key 2" ItemStyle-Width="100px" ItemStyle-Wrap="true" />
                                 <asp:BoundField DataField="DK3" SortExpression="DK3" HeaderText="Key 3" ItemStyle-Width="100px" ItemStyle-Wrap="true" />                          
                      
                                 <asp:TemplateField>
                                     <ItemTemplate>
                                         <asp:HyperLink ID="lnkEdit" runat="server"
                                             NavigateUrl='link'
                                             Target="_blank"
                                             Text='View Image'                                           
                                         </asp:HyperLink>
                                     </ItemTemplate>
                                 </asp:TemplateField>                               
                             </Columns>
                         </asp:GridView>
                     </div>              
             </ContentTemplate>
         </asp:UpdatePanel>
dotnet-aspnet-generaldotnet-aspnet-webpages
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The GridView sorts one column at a time. To sort multiple columns you'll need to design and write code to remember the sort fields and order. Then programmatically sort the data source.

Do a Google search.

https://www.google.com/search?q=Gridview+sort+multiple+columns

0 Votes 0 ·

Hi. I have tried the google search, before posting the question here.

0 Votes 0 ·
AgaveJoe avatar image AgaveJoe venkateshpadmanabhan-5594 ·

Hi. I have tried the google search, before posting the question here.

And what were the results? Can share the code you've tried?


0 Votes 0 ·
surferonwww avatar image
0 Votes"
surferonwww answered

You have to use the data source control with the GridView such as the SqlDataSource and ObjectDataSoure to enable sorting.

Otherwise you will have to write the code to enable sorting by yourself. Shown blow is sample:

.aspx.cs

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;
 using System.Web.UI;
 using System.Web.UI.WebControls;
 using System.Data;
     
 public partial class _0055_GridViewSorting : System.Web.UI.Page
 {
     // Create DataView as data source of GridView
     protected DataView CreateDataSource()
     {
         DataTable dt = new DataTable();
         DataRow dr;
     
         dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
         dt.Columns.Add(new DataColumn("Name", typeof(string)));
         dt.Columns.Add(new DataColumn("Type", typeof(string)));
         dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
         dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
         dt.Columns.Add(new DataColumn("Amount", typeof(Int32)));
         dt.Columns.Add(new DataColumn("CatID", typeof(Int32)));
         dt.Columns.Add(new DataColumn("Note", typeof(string)));
         dt.Columns.Add(new DataColumn("Disc", typeof(bool)));
         dt.Columns.Add(new DataColumn("Date", typeof(DateTime)));
     
         for (int i = 0; i < 15; i++)
         {
             dr = dt.NewRow();
             dr["ID"] = i;
             dr["Name"] = "Product Name_" + i.ToString();
             dr["Type"] = "Product Type " + (100 - i).ToString();
             dr["Price"] = 123000 * (i + 1);
             dr["Qty"] = (i + 1) * 20;
             dr["Amount"] = 123000 * (i + 1) * (i + 1);
             dr["CatID"] = 100 - i;
             dr["Note"] = "Note_" + i.ToString();
             dr["Disc"] = (i % 2 == 0) ? true : false;
             dr["Date"] = DateTime.Now.AddDays(i);
             dt.Rows.Add(dr);
         }
         return new DataView(dt);
     }
     
     protected void Page_Load(object sender, EventArgs e)
     {
         if (!Page.IsPostBack)
         {
             GridView1.DataSource = CreateDataSource();
             GridView1.DataBind();
         }
     }
     
     protected void GridView1_Sorting(object sender, 
                                       GridViewSortEventArgs e)
     {
         GridView gv = (GridView)sender;
         DataView view = CreateDataSource();
         string exp = e.SortExpression;
     
         // switch ASC / DESC when same LinkButton is clicked
         if (gv.Attributes["CurrentSortField"] != null &&
             gv.Attributes["CurrentSortDir"] != null)
         {
             if (exp == gv.Attributes["CurrentSortField"])
             {
                 if (gv.Attributes["CurrentSortDir"] == "ASC")
                 {
                     exp = exp + " DESC";
                     gv.Attributes["CurrentSortDir"] = "DESC";
                 }
                 else
                 {
                     exp = exp + " ASC";
                     gv.Attributes["CurrentSortDir"] = "ASC";
                 }
             }
             else
             {
                 gv.Attributes["CurrentSortField"] = exp;
                 exp = exp + " ASC";
                 gv.Attributes["CurrentSortDir"] = "ASC";
             }
         }
     
         view.Sort = exp;
         gv.DataSource = view;
         gv.DataBind();
     }
 }

.aspx

 <%@ Page Language="C#" AutoEventWireup="true" 
     CodeFile="0055-GridViewSorting.aspx.cs" 
     Inherits="_0055_GridViewSorting" %>
     
 <!DOCTYPE html>
     
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
     <title></title>
 </head>
 <body>
     <form id="form1" runat="server">
         <asp:GridView ID="GridView1" runat="server"
             AllowSorting="True"
             CurrentSortField=""
             CurrentSortDir=""
             onsorting="GridView1_Sorting">
         </asp:GridView>
     </form>
 </body>
 </html>


Result

239687-image2.jpg



image2.jpg (284.9 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

LanHuang-MSFT avatar image
0 Votes"
LanHuang-MSFT answered

Hi @venkateshpadmanabhan-5594,
You need to use gridView.Sorting Event:Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation.
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.gridview.sorting?view=netframework-4.8
You can refer to the example in the official documentation.

 protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
   {
    
     //Retrieve the table from the session object.
     DataTable dt = Session["TaskTable"] as DataTable;
    
     if (dt != null)
     {
    
       //Sort the data.
       dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
       TaskGridView.DataSource = Session["TaskTable"];
       TaskGridView.DataBind();
     }
    
   }
    
   private string GetSortDirection(string column)
   {
    
     // By default, set the sort direction to ascending.
     string sortDirection = "ASC";
    
     // Retrieve the last column that was sorted.
     string sortExpression = ViewState["SortExpression"] as string;
    
     if (sortExpression != null)
     {
       // Check if the same column is being sorted.
       // Otherwise, the default value can be returned.
       if (sortExpression == column)
       {
         string lastDirection = ViewState["SortDirection"] as string;
         if ((lastDirection != null) && (lastDirection == "ASC"))
         {
           sortDirection = "DESC";
         }
       }
     }
    
     // Save new values in ViewState.
     ViewState["SortDirection"] = sortDirection;
     ViewState["SortExpression"] = column;
    
     return sortDirection;
   }

Best regards,
Lan Huang


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.