Saturday, 10 December 2011

GridView paging manually in Asp.net C#

To do the paging just add a page in your project then add a gridview control on it like below:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand Name" HeaderText="Brand Name" />
             <asp:BoundField DataField="Category Name" HeaderText="Category Name" />
             <asp:BoundField DataField="Product Name" HeaderText="Product Name" />
         </Columns>
        </asp:GridView>   


Now under page load event first bind the data with the gridview and then cache the datasource which we will use to rebind when page index change. Sample code is given below:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {                 
            DataTable dt=clsDBUtility.GetDataTable("SELECT B.Name [Brand Name],C.Name [Category Name], " +
                    "P.Name [Product Name] FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3");
            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["Data"] = dt;
        }
    }    


Now under gridview PageIndexChanging event write the below code:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = (DataTable)Cache["Data"];
        GridView1.DataBind();
    }

3 comments:

  1. Very useful.. I was searching for this kind of small but effective tips for last few days..

    ReplyDelete
  2. Writing and submitting articles as well as posting these phones a number of article directory sites is actually an additional efficient solution to construct back-links aimed at your website. High Authority SEO

    ReplyDelete