How to sort grid view column when user click header on the grid view column?


In this article I have explained about how to sort grid view data if user click on the restrict use column header text. For example if user have lots of date in the grid view suppose he want to sort employee name order for that situation we need to sort by employee name.

Description:
Here in this example I have filter data using data view control and bind in grid view again, without using database connection again. Refer below example

Client side


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Grid View Sorting using Dataview</title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False"
PageSize="20" AllowPaging="True" AllowSorting="True"
OnSorting="GridView1_Sorting" CellPadding="4" ForeColor="#333333"
GridLines="None">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:TemplateField HeaderText="Employee no" SortExpression="eno">
<ItemTemplate>
<%#Eval("eno")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp name" SortExpression="empname">
<ItemTemplate>
<%#Eval("empname")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtempname" runat="server" Text='<%#Bind("empname")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Employee Name cannot be blank!"
ControlToValidate="txtempname" Display="None"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<ItemTemplate>
<%#Eval("sal")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtsal" runat="server" Text='<%#Bind("sal")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Employee Salary cannot be blank!"
ControlToValidate="txtsal" Display="None"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
<br />
</div>
</form>
</body>
</html>

Server Side

using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Session["dt"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

//Set & get sort state in viewstate
private string GVSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}

private string GetSortDirection()
{
switch (GVSortDirection)
{
//If previous sort direction if ascending order then assign new direction as descending order
case "ASC":
GVSortDirection = "DESC";
break;

//If previous sort direction if descending order then assign new direction as ascending order
case "DESC":
GVSortDirection = "ASC";
break;
}
return GVSortDirection;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)Session["dt"];
if (dataTable != null)
{
//Create new dataview instance and pass datatable
DataView dataView = new DataView(dataTable);

//get sort direction from the get sort direction method
string sortDirection = GetSortDirection();

//Sort dataview data based on the sort directin value
dataView.Sort = e.SortExpression + " " + sortDirection;

//Assign datasource and bind data to grid view
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
}


Output:
Output

Source Code Detail:
Here with I have attached entire source code download it and try to sort Grid view data on header text click.
Front End : ASP.NET
Code Behind : C#

Conclusion:
I hope this article help to know about sorting in grid view control.


Attachments

  • Source Code (43578-191729-Gridview_Sorting.rar)
  • Comments

    Author: SIVA RAMAMOORTHY12 Apr 2012 Member Level: Gold   Points : 0

    Hi Ravindra,

    Awesome article..

    Thanks alot..

    Author: Chetan23 May 2012 Member Level: Bronze   Points : 0

    hi

    i want to do with javascript

    what i suppose to do. . . ??

    Guest Author: Seethala11 Apr 2013

    This code perfectly working.Very Useful.Thank You



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: