Sorting GridView columns in ASP.net


In this article I'm trying to explain how to sort GridView columns based on gridview columns clicking. Once we click the header of the column it's order in Ascending order again we click one more time then it's sorting descending order.

Sorting GridView columns in ASP.net:


In this article I'm trying to explain how to sort GridView columns based on gridview columns clicking. Once we click the header of the column it's order in Ascending order again we click one more time then it's sorting descending order.

Description:


Gridview one of the best feature is sorting Rows based on column selection. For this I just bind employee information to gridview. In that I have few columns one of the column is employee name once I click on employee name column initially it's sorting in ascending order again I click on employee column then it's sorting in descending order. That means we can sort grid rows based on column clicking.

Properties & Events:


For this we must set the gridview AllowSorting property to "true" and wrote the code inside onsorting event of gridview control.
Here, I try to bind gridview columns manually so I must set the gridview column sortExpression which column need to sort.

Source Code:



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Sorting.aspx.cs" Inherits="Sorting" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div align="center">

GridView Sorting<br />
<br />
<asp:GridView ID="GV" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" AutoGenerateColumns="false"
AllowSorting="true" onsorting="GV_Sorting">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
<Columns>
<asp:BoundField DataField="empno" HeaderText="Employee Number"
ReadOnly="true" />
<asp:BoundField DataField="ename" HeaderText="Employee Name" SortExpression="ename" />
<asp:BoundField DataField="job" HeaderText="Job" SortExpression="job" />
<asp:BoundField DataField="mgr" HeaderText="Manager" />
<asp:BoundField DataField="hiredate" HeaderText="HireDate" ReadOnly="true" SortExpression="hiredate" />
<asp:BoundField DataField="sal" HeaderText="Salary" SortExpression="sal" />
<asp:BoundField DataField="comm" HeaderText="Commission" SortExpression="comm" />
</Columns>
</asp:GridView>

</div>
</form>
</body>
</html>


Code Behind:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Sorting : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("DataBase=ENGSOFT;User id=sa;Password=P@ssword9");
SqlDataAdapter da;
DataSet ds;
DataTable dt;
SqlCommand cmd;
int DeptNo = 1;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind_GV();
}
}
protected void Bind_GV()
{
// call Stored procedure in application
cmd = new SqlCommand("Get_Employees", con);
cmd.CommandType = CommandType.StoredProcedure;

// pass parameters to stored procedure
cmd.Parameters.AddWithValue("@DeptNo", DeptNo);
dt = new DataTable();

try
{
// open connection
con.Open();


da = new SqlDataAdapter(cmd);
//fill datatable
da.Fill(dt);

//bind datatable to gridview
if (dt.Rows.Count > 0)
{
GV.DataSource = dt;
GV.DataBind();
}
//if datatable is empty then bind headers to grid view control
else
{
DataRow dr = dt.NewRow();

dt.Rows.Add(dr);
dt.AcceptChanges();
GV.DataSource = dt;
GV.DataBind();
GV.Rows[0].Visible = false;
}
// store DataTable result to Viewstate, using this viewstate object we can fetch data in Sorting event

ViewState["dt"] = dt;
}
catch (Exception ex)
{

}
finally
{
// Close the connection
con.Close();
con.Dispose();
}
}

protected void GV_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["dt"] != null)
dt = ViewState["dt"] as DataTable;
SortDirection dir = SortDirection.Ascending;
if (ViewState["dir"] != null)
dir = (SortDirection)ViewState["dir"];
string sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
ViewState["dir"] = dir;
DataView dv = dt.DefaultView;
dv.Sort = e.SortExpression + " " + sortingDirection;

GV.DataSource = dv;
GV.DataBind();

}
}

In the above code I just normally bind gridview in page load event after that when I click on gridview columns then it will sort in Ascending order at first time again I try to click the same column then it will sort in Descending order.

Refer below sample code for sorting part:



protected void GV_Sorting(object sender, GridViewSortEventArgs e)
{
//fetch database result using viewstate object
if (ViewState["dt"] != null)
dt = ViewState["dt"] as DataTable;

//by default sort direction is Ascending order
SortDirection dir = SortDirection.Ascending;

// Set the Sort Direction if already exists.
if (ViewState["dir"] != null)
dir = (SortDirection)ViewState["dir"];
string sortingDirection = string.Empty;

//set the sorting expression
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}

//store the sort expression in viewstate and call this in front of the code
ViewState["dir"] = dir;

// using DataView we can easily sort the expression and bind this datavew to gridview control after sort

DataView dv = dt.DefaultView;
dv.Sort = e.SortExpression + " " + sortingDirection;

GV.DataSource = dv;
GV.DataBind();

}


OutPut:



1

2


Conclusion:


Using this we can easily sort the grid view control based on column selection. This article will help you someone who are looking for the same.


Attachments

  • Source Code (45216-235856-Source-Code.zip)
  • Comments

    No responses found. Be the first to comment...


  • 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: