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

By
Advertisement
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.

1 comment:

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

    ReplyDelete

Online Casino