Monday, 16 January 2012

Enable Paging to GridView Control in ASP.NET 4.0

To enable paging to the GridView control we have to specify some of its properties like AllowPaging, PageSize and have to handle its event PageIndexChanging.

First, take a GridViewControl on your .aspx page and specify its following properties... (Your declaration of GridView might be like this.



<asp:GridView ID="GridManageWard" runat="server"
         EnablePersistedSelection="true"
         AllowPaging="True"
         PageSize="7"
         CellPadding="3" GridLines="Vertical"
         Height="46px"  Width="263px"
         BackColor="White" BorderColor="#999999"
         BorderStyle="Solid" BorderWidth="1px"
         ForeColor="Black"
         onpageindexchanging="GridManageWard_PageIndexChanging">

            In the above declaration properties highlighted with different color are necessary for paging, rest of them are for the look of the control.

            Now, after creating the gridview control you have to bind datasource to it. You can get data from datasource and bind datasource to the gridview on the Page's Load event as below.


     protected void Page_Load(object sender, EventArgs e)
    {
          // this check is for checking whether the page is loading for the first time or not
         if (!IsPostBack)
         {
              // here we are making an object of class ClsManageWard which is a user defined class 
             // and provides  function for retrieving records from the database
               ClsManageWard ward = new ClsManageWard();

                // here we are taking DataTable to store the data and getting records by calling getWards() method
                 DataTable dt = ward.getWards();

                 //Specify the datasource for the gridview
                 GridManageWard.DataSource = dt;

                // Specifying DataKeyNames 
            GridManageWard.DataKeyNames = new string[] { "Id" };
            GridManageWard.DataBind();



    }


              Now, handle the PageIndexChanging event of the control as described below:



  protected void GridManageWard_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        //here we have furthur taken the DataTable and from DataKeyNames we can allow our gridview
        // to show pages

        ClsManageWard ward = new ClsManageWard();

        DataTable dt = ward.getWards();

        // we have to specify DataSource, PageIndex and have to bind gridview
        GridManageWard.DataSource = dt;
        GridManageWard.PageIndex = e.NewPageIndex;
        GridManageWard.DataBind();
    }

         This will make your gridview showing its contents in different pages.

         You can view the snapshots here:
         
           First Page:



             Second Page:










No comments:

Post a Comment