GridView Sorting in ASP.Net Using C#

We will use one GridView and its sorting event, then we write some code in that event for making name ascending and descending.

Initial chamber

Step 1

Open your Visual Studio 2010 and create an Empty Website, provide a suitable name (gridviewsorting_demo).

Step 2

In Solution Explorer you get your empty website, then add two web forms and a SQL Server Database as in the following.

For Web Form:

Autocomplete_demo (your empty website) then right-click then select Add New Item -> Web Form. Name it gridviewsorting_demo.aspx.

For SQL Server Database

gridviewsorting_demo (your empty website) then right-click then select Add New Item -> SQL Server Database. (Add a database inside the App_Data_folder).

DATABASE CHAMBER

Step 3

In Server Explorer, click on your database (Database.mdf) then select Tables -> Add New Table. Make the table like this.

Table tbl_data (Don't Forget to make ID as IS Identity -- True)


table design

Design chamber

Step 4

Now open your gridviewsorting_demo.aspx file, where we create our design for GridView sorting.

Gridviewsorting_demo.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8. </head>  
  9. <body>  
  10.     <form id="form1" runat="server">  
  11.     <div>  
  12.       
  13.         <table style="width:100%;">  
  14.             <tr>  
  15.                 <td>  
  16.                      </td>  
  17.                 <td>  
  18.                      </td>  
  19.                 <td>  
  20.                      </td>  
  21.             </tr>  
  22.             <tr>  
  23.                 <td>  
  24.                      </td>  
  25.                 <td>  
  26.                     <asp:GridView ID="GridView1" runat="server" AllowSorting="True"   
  27.                         AutoGenerateColumns="False" BackColor="White" BorderColor="#999999"   
  28.                         BorderStyle="Solid" BorderWidth="1px" CellPadding="3" DataKeyNames="id"   
  29.                         ForeColor="Black" GridLines="Vertical" onsorting="GridView1_Sorting">  
  30.                         <AlternatingRowStyle BackColor="#CCCCCC" />  
  31.                         <Columns>  
  32.                             <asp:TemplateField HeaderText="Id" SortExpression="id">  
  33.                                 <%--<EditItemTemplate>  
  34.                                     <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("id") %>'></asp:TextBox>  
  35.                                 </EditItemTemplate>--%>  
  36.                                 <ItemTemplate>  
  37.                                     <asp:Label ID="Label1" runat="server" Text='<%# Bind("id") %>'></asp:Label>  
  38.                                 </ItemTemplate>  
  39.                             </asp:TemplateField>  
  40.                             <asp:TemplateField HeaderText="First Name" SortExpression="fname">  
  41.                                 <EditItemTemplate>  
  42.                                     <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("fname") %>'></asp:TextBox>  
  43.                                 </EditItemTemplate>  
  44.                                 <ItemTemplate>  
  45.                                     <asp:Label ID="Label2" runat="server" Text='<%# Bind("fname") %>'></asp:Label>  
  46.                                 </ItemTemplate>  
  47.                             </asp:TemplateField>  
  48.                             <asp:TemplateField HeaderText="Last Name" SortExpression="lname">  
  49.                                 <EditItemTemplate>  
  50.                                     <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("lname") %>'></asp:TextBox>  
  51.                                 </EditItemTemplate>  
  52.                                 <ItemTemplate>  
  53.                                     <asp:Label ID="Label3" runat="server" Text='<%# Bind("lname") %>'></asp:Label>  
  54.                                 </ItemTemplate>  
  55.                             </asp:TemplateField>  
  56.                             <asp:TemplateField HeaderText="City" SortExpression="city">  
  57.                                 <EditItemTemplate>  
  58.                                     <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("city") %>'></asp:TextBox>  
  59.                                 </EditItemTemplate>  
  60.                                 <ItemTemplate>  
  61.                                     <asp:Label ID="Label4" runat="server" Text='<%# Bind("city") %>'></asp:Label>  
  62.                                 </ItemTemplate>  
  63.                             </asp:TemplateField>  
  64.                         </Columns>  
  65.                         <FooterStyle BackColor="#CCCCCC" />  
  66.                         <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />  
  67.                         <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />  
  68.                         <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />  
  69.                         <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  70.                         <SortedAscendingHeaderStyle BackColor="#808080" />  
  71.                         <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  72.                         <SortedDescendingHeaderStyle BackColor="#383838" />  
  73.                     </asp:GridView>  
  74.                 </td>  
  75.                 <td>  
  76.                      </td>  
  77.             </tr>  
  78.             <tr>  
  79.                 <td>  
  80.                      </td>  
  81.                 <td>  
  82.                      </td>  
  83.                 <td>  
  84.                      </td>  
  85.             </tr>  
  86.         </table>  
  87.       
  88.     </div>  
  89.     </form>  
  90. </body>  
  91. </html>  
Now for those of who are using the Template Field here, you need to embed a single thing into the code, a Sort Expression, whatever the field is for (like if it is the firstname, then write like sort expression=”firstname”). The following code displays it.

code

Your design looks like the following:

gridview

Code chamber

Step 5

Open your gridviewsorting_demo.aspx.cs and write some code for the application to make it work.

gridviewsorting_demo.aspx.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Data.SqlClient;  
  9.   
  10. public partial class _Default : System.Web.UI.Page  
  11. {  
  12.    
  13.     protected void Page_Load(object sender, EventArgs e)  
  14.     {  
  15.         if (!Page.IsPostBack)  
  16.         {  
  17.             refreshdata();  
  18.         }  
  19.   
  20.     }  
  21.         public void refreshdata()  
  22.         {  
  23.           
  24.             SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");  
  25.             SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
  26.             SqlDataAdapter sda = new SqlDataAdapter(cmd);  
  27.             DataTable dt = new DataTable();  
  28.             sda.Fill(dt);  
  29.             GridView1.DataSource = dt;  
  30.               GridView1.DataBind();  
  31.               ViewState["dirState"] = dt;  
  32.               ViewState["sortdr"] = "Asc";  
  33.               
  34.           
  35.         }  
  36.         protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)  
  37.         {  
  38.             DataTable dtrslt= (DataTable)ViewState["dirState"];  
  39.             if (dtrslt.Rows.Count > 0)  
  40.             {  
  41.                 if (Convert.ToString(ViewState["sortdr"]) == "Asc")  
  42.                 {  
  43.                     dtrslt.DefaultView.Sort = e.SortExpression + " Desc";  
  44.                     ViewState["sortdr"] = "Desc";  
  45.                 }  
  46.                 else  
  47.                 {  
  48.                     dtrslt.DefaultView.Sort = e.SortExpression + " Asc";  
  49.                     ViewState["sortdr"] = "Asc";  
  50.                 }  
  51.                 GridView1.DataSource = dtrslt;  
  52.                 GridView1.DataBind();   
  53.               
  54.                  
  55.             }  
  56.   
  57.         }  
  58. }  
Output chamber
Output

stored data

I hope you liked this. Thank you for reading. Have a good day.

 

Up Next
    Ebook Download
    View all
    Learn
    View all