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)     { ...

C# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...

VBScript equivalent string functions in C#.Net

C# Method VBScript Description IndexOf() InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string - InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string ToLower() LCase Converts a specified string to lowercase SubString() Left Returns a specified number of characters from the left side of a string Length() Len Returns the number of characters in a string TrimStart() LTrim Removes spaces on the left side of a string TrimEnd() RTrim Removes spaces on the right side of a string Trim() Trim Removes spaces on both the left and the right side of a string SubString() M...