Scroll To Top
Reader Level:

Grid View Paging and Sorting in ASP.Net

By Jagdeep Singh Jhass on Nov 02, 2010
In this article you will learn how to create Grid View Paging and Sorting in ASP.Net

Step 1. Create new project in visual studio.

Step 2. Open default.aspx and drag and drop GridView control in design view.

Step 3. Open default.aspx.cs and add following line in using directives:

using System.Data.SqlClient;

Step 4. Open Web.config and add following line just above <system.web>:

add name="con" connectionString="Data Source=.\sqlexpress;initial catalog=database_name;integrated security=true;" providerName="System.Data.SqlClient"/>

Step 5. Open properties of GridView, change AllowSorting and AllowPaging property to True.

Step 6. Open default.aspx.cs and add following lines:

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
    protected void Page_Load(object sender, EventArgs e)
            DataSet ds = new DataSet();
            DataView dv = new DataView();
dv = binddata();
            GridView1.DataSource = dv;
    private DataView binddata()
  SqlDataAdapter adp = new SqlDataAdapter("select data from table", conn);
        if (ViewState["sortexp"] != null)
            dv = new DataView(ds.Tables[0]);
            dv.Sort = (string)ViewState["sortexp"];
            dv = ds.Tables[0].DefaultView;
        return dv;

    protected void paging(object sender, GridViewPageEventArgs e)
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = binddata();
    protected void sorting(object sender, GridViewSortEventArgs e)
        ViewState["sortexp"] = e.SortExpression;
        GridView1.DataSource = binddata();

Step 7. Open properties of GridView and click on events, change PageIndexChanging to paging and Sorting to sorting.

Step 8. Build the project.