add pagination to gridview asp.net

Paolo Duhaylungsod picture Paolo Duhaylungsod · Jun 1, 2016 · Viewed 12.6k times · Source

what i want to happen is to have a pagination to have a clean look at the data. here is my html code for gridview:

<asp:gridview ID = "grid" runat="server"  AllowPaging="true" OnPageIndexChanging="gdview_PageIndexChanging">

and code behind:

public static string cs = "Server=PAULO;Database=ShoppingCartDB;Integrated Security=true";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["New"] != null)
        {
            if (!IsPostBack)
            {
                SqlConnection con = new SqlConnection(cs);
                con.Open();

                string sql = "SELECT * FROM CustomerDetails Where CustomerName = '" + Session["New"] +"'";
                SqlDataAdapter da = new SqlDataAdapter(sql, con);
                DataTable dt = new DataTable();
                da.Fill(dt);




                Label2.Text += Session["New"].ToString();
                linkLogout.Visible = true;
                //linkOrderHistory.Visible = true;
                Label2.Visible = true;
                linkViewProfile.Visible = true;
                grid.DataSource = dt;
                grid.DataBind();
            }
        }

    }
    private void CustomBindData()
    {
        SqlConnection con = new SqlConnection(cs);
        con.Open();

        string sql = "SELECT * FROM CustomerDetails Where CustomerName = '" + Session["New"] + "'";
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        da.Fill(dt);
    }
    protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        CustomBindData();
        grid.PageIndex = e.NewPageIndex;
        grid.DataBind();
    }

somehow my code is not working. it has the pages but when i click on page 2, no data is shown. i think it has something to do on how i get the data from the sql. any tricks on this?

Answer

Harish Nayak picture Harish Nayak · Jun 1, 2016

Instead of this

protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grid.PageIndex = e.NewPageIndex;
    grid.DataBind();
}

use the following..In page load store the datasource to session which your were using for the gridview and do the following like,

Session[gridviewsouce] = dt; //dataTable which you were using in page_load

and in page indexchanging function..

protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grid.PageIndex = e.NewPageIndex;
    DataTabel dt = Session[gridviewsouce] as DataTable;
    grid.DataSource = dt;
    grid.DataBind();
}