Pagging and Sorting For GridView

Introduction:

Here I am explaining Paging and Sorting in GridView using Asp.Net and C#.Net.

Description:

I have one gridview with some data here my requirement is apply paging for the grid view and when i am click on column name the records in the table are sorted.
Now we will design the page like this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Allow Paging and Sorting::Venu</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grid" runat="server" AllowPaging="true" AllowSorting="true" PageSize="5"
            OnPageIndexChanging="grid_PageIndexChanging" OnSorting="grid_Sorting" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField HeaderText="Employee Name" DataField="Employee" SortExpression="Employee" />
                <asp:BoundField HeaderText="Salary" DataField="Salary" SortExpression="Salary" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

 After Completion of aspx page design write the following code in .cs file
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 _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["Sortby"] = null;
        if (!IsPostBack)
        {
            BindData();
        }

    }
    public void BindData()
    {
        SqlConnection con = new SqlConnection("server=ADMINISTRATOR00;database=Acadamics;uid=ACMCPRJ;pwd=projects");
        SqlDataAdapter adapter = new SqlDataAdapter("select * from Employee", con);
        DataTable table = new DataTable();
        adapter.Fill(table);
        if (table.Rows.Count != 0)
        {
            DataView dv = table.DefaultView;
            if (Session["Sortby"] != null)
            {
                dv.Sort = Session["Sortby"].ToString();
            }
            grid.DataSource = table;
            grid.DataBind();
        }
       
    }
    protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grid.PageIndex = e.NewPageIndex;
        BindData();
    }
    protected void grid_Sorting(object sender, GridViewSortEventArgs e)
    {
        Session["Sortby"] = e.SortExpression;
        BindData();
    }
}

Then run the application the page shows like below..

Employee Name Salary
venu 12000
surendra 10000
venu 10000
surendra 12000
gopi 1234
1 2
Click on column name Employee then sorting done and the page shows like below..

Employee Name Salary
gopi 1234
prasanna 4253245
surendra 10000
surendra 12000
venu 12000
1 2