Search code examples
c#asp.netgridviewpaginationpage-index-changed

add pagination to gridview asp.net


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?


Solution

  • i added

    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);
    
            grid.DataSource = dt;
            grid.DataBind();
        }
        protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            CustomBindData();
            grid.PageIndex = e.NewPageIndex;
            grid.DataBind();
        }