Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

Paging And Sorting in GridView in ASP.NET

Article:
Viewed:  2173 
Posted On:  23/01/2013 09:44:32 
In this article I am going to explain how we can achieve paging and sorting in a GridView in asp.net 

In this article I am going to explain how we can achieve paging and sorting in grid view in asp.net.

Below is my data table structure ...

DataTable.png

Figure 1.

Table with Data..

TableWithData.png

Figure 2.

Below is my aspx code:

<%@ 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>Paging And Sorting in GridView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="2" cellspacing="2" width="50%" align="center" border="1">
            <tr>
                <td>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
                        OnPageIndexChanging="GridView1_PageIndexChanging" OnSorting="GridView1_Sorting"
                        AllowPaging="true" PageSize="2" AllowSorting="true" AutoGenerateColumns="false">                       
RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <EditRowStyle BackColor="#999999" />
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                        <Columns>
                            <asp:BoundField DataField="Emp_ID" HeaderText="Employee ID" SortExpression="Emp_ID" />
                            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                            <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />
                            <asp:BoundField DataField="Mobile" HeaderText="Mobile" SortExpression="Mobile" />
                           <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                            <asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
                            <asp:BoundField DataField="JoinDate" HeaderText="Join Date" SortExpression="JoinDate" />
                        </Columns>
                    </asp:GridView>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>
 

This is my aspx.cs code

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Collections.Generic;
 
public partial class _Default : System.Web.UI.Page
{
    SqlDataAdapter da;
    DataSet ds = new DataSet(); 

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ViewState["sortOrder"] = "";
            BindGrid();
        }
    } 

    public void BindGrid()
    {
        try
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString; 
            SqlCommand cmd = new SqlCommand("SELECT * FROM EMPLOYEE", con); 

            da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
 
            if (!object.Equals(ds.Tables[0], null))
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataView DV = ds.Tables[0].DefaultView;
                    if (Session["sortBy"] != null)
                    {
                        DV.Sort = string.Format("{0} {1}", Session["sortBy"].ToString(), Session["sortOrder"].ToString());
                    }
                    Session["DataTable2CSV"] = DV.Table;
                    GridView1.DataSource = DV;
                    GridView1.DataBind();
                }
                else
                {
                    GridView1.DataSource = null;
                    GridView1.DataBind();
                }
            }
            else
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }
        catch (SqlException ex)
        {
        }
    } 

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        Session["sortBy"] = e.SortExpression;
        Session["sortOrder"] = sortOrder;
        BindGrid();
    }

    public string sortOrder
    {
        get
        {
            if (ViewState["sortOrder"].ToString() == "desc")
            {
                ViewState["sortOrder"] = "asc";
            }
            else
            {
                ViewState["sortOrder"] = "desc";
            }
            return ViewState["sortOrder"].ToString();
        }
        set
        {
            ViewState["sortOrder"] = value;
        }
    }
}

I define my connection string in web.config file see below image..

ShowingConnInWebConfig.png

Figure 3.

When I run my application then:

UI.png

Figure 4.

When I do sort by name

SortByName.png

Figure 5.

When do sorting by join date..

SortByJoinDate.png

Figure 6.

To see paging I set AllowPaging="true" and PageSize="2"

Paging1.png

Figure 7.

When move to next page

Paging2.png

Figure 8.

 

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us