Paging in ASP.net Gridview



Here an example is given for the paging in gridview control of asp.net.

Suppose we have a list of employee. We want to show employee list. We have taken gridview control.

Steps are given below for showing data in gridview and applying paging on it :
  1. Use gridview control in the .aspx page.
  2. Bind gridview from database and
  3. Apply paging in gridview.

Step 1:

Here we have used gridview control and we have used onpageindexchanging event for paging by setting allowing AllowPaging="true" and PageSize="10". You can change PageSize whatever you want.

<asp:GridView ID="GridView1" runat="server" BackColor="White" AutoGenerateColumns="False" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" AllowPaging="true" PageSize="10" EnableModelValidation="True" GridLines="Horizontal"   PagerSettings-Position="Bottom"
onpageindexchanging="GridView1_PageIndexChanging" >
            <AlternatingRowStyle BackColor="#F7F7F7" />
               <Columns>
                <asp:BoundField DataField="EmpID" HeaderText="Employee ID" />
                <asp:BoundField DataField="EmpName" HeaderText="Employee Name"/>                 
                <asp:BoundField DataField="Salary" HeaderText="Salary" />
            </Columns>
            <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
            <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Center" />
            <RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />

        </asp:GridView>

Step 2:

Bind gridview in .cs file , I have used C# as language for it.

SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ToString());
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {  
            BindEmplyee();
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (e.NewPageIndex >= 0)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindEmplyee();
        }
    }

    private void BindEmplyee()
    {
        SqlDataAdapter sda = new SqlDataAdapter("Select EmpID , EmpName , Salary From Employee",conn);
        DataTable dtEmp = new DataTable();
        sda.Fill(dtEmp);
        GridView1.DataSource = dtEmp;
        GridView1.DataBind();       
    }


Step 3:

In step 2 , I have used GridView1_PageIndexChanging for paging in gridview by setting PageIndex with e.NewPageIndex  in gridview.

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (e.NewPageIndex >= 0)
        {
            GridView1.PageIndex = e.NewPageIndex;
            BindEmplyee();
        }
    }


 Hope you have enjoyed with this example.

Comments

Popular Posts