Monday 4 November 2013

Sorting GridView By Columns Header In Asp.Net Ascending and Descending in ASP.NET using C#/VB.NET

Hi friends, in this article I will explain about Sorting GridView By Columns Header In Asp.Net Ascending and Descending in ASP.NET using C#/VB.NET.
I already explained in the previous articles Ajax ModalPopUpExtender Example to edit the GridView row values in ASP.NETHow to Bind Nested Gridview with expand collapse from Database in asp.net with C#/VB.NET and How to Export Gridview data to PDF File in ASP.NET using C#/VB.NET
I created Employee table in Database as shown in the below figure.

In ASP.NET:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Sorting GridView By Columns Header In Asp.Net Ascending and Descending in ASP.NET using C#/VB.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView runat="server" ID="grdSort" OnSorting="grdSort_Sorting" AutoGenerateColumns="false" AllowSorting="true" >
    <Columns>
<asp:TemplateField HeaderText="ID" SortExpression="Emp_ID">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%#Eval("Emp_ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Eval("Name")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Department Name" SortExpression="DepartmentName">
<ItemTemplate>
<asp:Label ID="lblDName" runat="server" Text='<%#Eval("DepartmentName")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DOJ" SortExpression="DOJ">
<ItemTemplate>
<%--<asp:Label ID="lblDOJ" runat="server" Text='<%#Eval("DOJ")%>'/>--%>
<%# string.IsNullOrEmpty(Convert.ToString(Eval("DOJ", "{0:dd-MMM-yyyy}"))) ? "" : Eval("DOJ", "{0:dd-MMM-yyyy}")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
    </asp:GridView>
    </div>
    </form>
</body>
</html>

In C#.NET:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class GridViewSort : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grdSort.DataSource = BindData();
            grdSort.DataBind();
        }
    }
    protected void grdSort_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sortingDirection = string.Empty;
        if (sortDirection == SortDirection.Ascending)
        {
            sortDirection = SortDirection.Descending;
            sortingDirection = "Desc";
        }
        else
        {
            sortDirection = SortDirection.Ascending;
            sortingDirection = "Asc";
        }
        DataView sortedView = new DataView(BindData());
        sortedView.Sort = e.SortExpression + " " + sortingDirection;
        grdSort.DataSource = sortedView;
        grdSort.DataBind();
    }
    protected DataTable BindData()
    {
        DataTable ds = new DataTable();
        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from Employee",con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        return ds;
    }
    public SortDirection sortDirection
    {
        get
        {
            if (ViewState["Sort"] == null)
            {
                ViewState["Sort"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["Sort"];
        }
        set
        {
            ViewState["Sort"] = value;
        }
    }

}


In VB.NET:
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient

Partial Public Class GridViewSort
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            grdSort.DataSource = BindData()
            grdSort.DataBind()
        End If
    End Sub
    Protected Sub grdSort_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
        Dim sortingDirection As String = String.Empty
        If sortDirection = SortDirection.Ascending Then
            sortDirection = SortDirection.Descending
            sortingDirection = "Desc"
        Else
            sortDirection = SortDirection.Ascending
            sortingDirection = "Asc"
        End If
        Dim sortedView As New DataView(BindData())
        sortedView.Sort = e.SortExpression & " " & sortingDirection
        grdSort.DataSource = sortedView
        grdSort.DataBind()
    End Sub
    Protected Function BindData() As DataTable
        Dim ds As New DataTable()
        Dim con As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("con").ConnectionString)
        Dim cmd As New SqlCommand("Select * from Employee", con)
        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)
        Return ds
    End Function
    Public Property sortDirection() As SortDirection
        Get
            If ViewState("Sort") Is Nothing Then
                ViewState("Sort") = SortDirection.Ascending
            End If
            Return CType(ViewState("Sort"), SortDirection)
        End Get
        Set(ByVal value As SortDirection)
            ViewState("Sort") = value
        End Set
    End Property

End Class



The output of the above code as shown in the below figure.

When we sort on the ID column then it will shown in the descending order as shown in the below figure.

No comments:

Post a Comment

© 2012-2018 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.