Skip to main content

How to Implement Asp.Net GridView Sorting Example Using C#.Net & VB.Net or how to Use of AllowSorting GridView Property.

In this article i am going to explain about How to Implement Asp.Net GridView Sorting Example Using C#.Net & VB.Net or how to Use of AllowSorting GridView Property. This is achieved by using the AllowSorting and OnSorting properties of the GridView and SortExpression attribute of boundfield if you set AutoGenerateColumns to false.

In my previous article i have explained aboutHow To Implement Asp.Net GridView Pagination Using C#.Net & VB.Net , Convert Dataset Datatable To Json Data Array In Asp.Net C#.Net & VB.Net Or How To Use JavaScriptSerializer To Convert Datatable To Json Data Array ,How To Show Tooltip On Mouse Hover In Gridview In Using JQuery In ASP.Net C#.Net & VB.Net,SQL Script To Drop Multiple Tables,Procedures At Once ,SQL Script To Drop Multiple Tables,Procedures At Once ,Convert Dataset Datatable To Json Data Array,SQL Script To Drop Multiple Tables,Procedures At Once In Sql Server,Highlight,Change Color Of Row On Mouseover In Grid View Using CSS - C#.Net ASP.Net VB.Net and many articles in C#.Net,ASP.Net,VB.Net,Grid View,Javascript,jQuery,SQL Server and many other topics.

I have created a asp.net website and added a web form to the project. I have drag and drop the gridview control from the toolbox and added some styles to gridview to format it. Now i have set AllowSorting Property of C#.Net to true and assigned the OnSorting eventhandler. I set AutoGenerateColumns property to false and defined the columns i want to show along with the sortexpression. The entire html markup is given below.

Html Markup:

Asp.Net GridView Sorting Example Using C#.Net & VB.Net | Use of AllowSorting GridView Property


Now in the code behind file in the page_load event i have created a datatable and added some records in it. And binded the datatable to gridview. On OnSorting event first i am deciding field field to sort and the direction to sort. Based on it i am creating dataview from the datatable and passing this sorting condition to the dataview and the final output is again binded to the gridview. The entire code is given below.

C#.Net Code:
using System;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            DataTable dt = GetDataTable();
            grdEmployeeDetails.DataSource = dt;
            grdEmployeeDetails.DataBind();
        }
        catch (Exception ex)
        {
            // handle error
        }
    }
    private DataTable GetDataTable()
    {
        DataTable dTable = new DataTable();
        // Columns to store employee details
        dTable.Columns.Add("EmpId", typeof(int));
        dTable.Columns.Add("Name", typeof(string));
        dTable.Columns.Add("Location", typeof(string));
        dTable.Columns.Add("Designation", typeof(string));
        dTable.Columns.Add("Department", typeof(string));
        dTable.Columns.Add("Salary", typeof(string));

        // Adding sample rows
        dTable.Rows.Add(1, "Arivu", "Denver", "Developer", 
            "Development Team", "$1000/Month");
        dTable.Rows.Add(2, "Benjamin", "Chennai", "Designer", 
            "Design Team", "$1500/Month");
        dTable.Rows.Add(3, "Saxena", "California", "Tester", 
            "Testing Team", "$2000/Month");
        dTable.Rows.Add(4, "Navneet", "Mumbai", "Project Manager", 
            "Development Team", "$2500/Month");
        dTable.Rows.Add(5, "Xavier", "Denver", "Product Manager", 
            "Product Team", "$3000/Month");
        dTable.Rows.Add(6, "Alikhan", "California", "Product Manager", 
            "Product Team", "$3500/Month");

        return dTable;
    }
    protected void grdEmployeeDetails_Sorting(object sender, 
        GridViewSortEventArgs e)
    {
        DataTable dt = GetDataTable();
        {
            string SortDir = string.Empty;
            if (direction == SortDirection.Ascending)
            {
                direction = SortDirection.Descending;
                SortDir = "Desc";
            }
            else
            {
                direction = SortDirection.Ascending;
                SortDir = "Asc";
            }
            DataView sortedView = new DataView(dt);
            sortedView.Sort = e.SortExpression + " " + SortDir;
            grdEmployeeDetails.DataSource = sortedView;
            grdEmployeeDetails.DataBind();
        }
    }
    public SortDirection direction
    {
        get
        {
            if (ViewState["directionState"] == null)
            {
                ViewState["directionState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["directionState"];
        }
        set
        {
            ViewState["directionState"] = value;
        }
    }  

}

VB.Net Code:
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration


Public Partial Class _Default
 Inherits System.Web.UI.Page
 Protected Sub Page_Load(sender As Object, e As EventArgs)
  Try
   Dim dt As DataTable = GetDataTable()
   grdEmployeeDetails.DataSource = dt
   grdEmployeeDetails.DataBind()
    ' handle error
  Catch ex As Exception
  End Try
 End Sub
 Private Function GetDataTable() As DataTable
  Dim dTable As New DataTable()
  ' Columns to store employee details
  dTable.Columns.Add("EmpId", GetType(Integer))
  dTable.Columns.Add("Name", GetType(String))
  dTable.Columns.Add("Location", GetType(String))
  dTable.Columns.Add("Designation", GetType(String))
  dTable.Columns.Add("Department", GetType(String))
  dTable.Columns.Add("Salary", GetType(String))

  ' Adding sample rows
  dTable.Rows.Add(1, "Arivu", "Denver", "Developer", "Development Team", "$1000/Month")
  dTable.Rows.Add(2, "Benjamin", "Chennai", "Designer", "Design Team", "$1500/Month")
  dTable.Rows.Add(3, "Saxena", "California", "Tester", "Testing Team", "$2000/Month")
  dTable.Rows.Add(4, "Navneet", "Mumbai", "Project Manager", "Development Team", "$2500/Month")
  dTable.Rows.Add(5, "Xavier", "Denver", "Product Manager", "Product Team", "$3000/Month")
  dTable.Rows.Add(6, "Alikhan", "California", "Product Manager", "Product Team", "$3500/Month")

  Return dTable
 End Function
 Protected Sub grdEmployeeDetails_Sorting(sender As Object, e As GridViewSortEventArgs)
  Dim dt As DataTable = GetDataTable()
  If True Then
   Dim SortDir As String = String.Empty
   If direction = SortDirection.Ascending Then
    direction = SortDirection.Descending
    SortDir = "Desc"
   Else
    direction = SortDirection.Ascending
    SortDir = "Asc"
   End If
   Dim sortedView As New DataView(dt)
   sortedView.Sort = Convert.ToString(e.SortExpression + " ") & SortDir
   grdEmployeeDetails.DataSource = sortedView
   grdEmployeeDetails.DataBind()
  End If
 End Sub
 Public Property direction() As SortDirection
  Get
   If ViewState("directionState") Is Nothing Then
    ViewState("directionState") = SortDirection.Ascending
   End If
   Return DirectCast(ViewState("directionState"), SortDirection)
  End Get
  Set
   ViewState("directionState") = value
  End Set
 End Property

End Class

Now the output will look like below.

Output:

Sourcecode Download:
Sourcecode of How to Implement Asp.Net GridView Sorting Example Using C#.Net & VB.Net or how to Use of AllowSorting GridView Property.

Comments

  1. Nice post, find asp.net ebooks for free download available here
    http://www.frebookscenter.blogspot.in/2014/04/aspbooks.html

    ReplyDelete

Post a Comment

Popular posts from this blog

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     {         sb.Append( "Minus " );         inputNo = -inputNo;     }     string [] words0 = { "" , "One " ,

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw