添加分页到gridview asp.net

时间:2016-06-01 06:09:48

标签: c# asp.net gridview pagination page-index-changed

我想要发生的是拥有一个分页来清楚地看待数据。 这是我对gridview的html代码:

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

和代码背后:

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();
    }
不知怎的,我的代码无效。它有页面,但是当我点击第2页时,没有显示数据。我认为它有关如何从sql获取数据的事情。对此有什么诡计吗?

2 个答案:

答案 0 :(得分:2)

我添加了

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();
    }

答案 1 :(得分:0)

而不是这个

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

使用以下内容..在页面加载中将数据源存储到您用于gridview的会话,并执行以下操作,

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

和页面索引更改功能..

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