5

这个问题似乎很常见,我已经完成了这个答案

不幸的是,我的页面仍然没有被分页。这是我的代码在 C# 中的样子:

 SqlCommand command = new SqlCommand("(SELECT ......", Connection);
 SqlDataAdapter myAdapter = new SqlDataAdapter(command);
 DataTable dt = new DataTable();
 myAdapter.Fill(dt);

 command.Connection = connection;
 command.Connection.Open();

 GridView1.DataSource = dt;
 GridView1.DataBind();
 GridView1.AllowPaging = true;
 GridView1.PageSize = 15;

 command.Connection.Close();
 command.Connection.Dispose();

不幸的是,当我这样做时,我的分页没有出现。难道我做错了什么?

谢谢

4

2 回答 2

6

在调用方法之前设置所有与分页相关的属性。Databind()当您使用自定义分页时,您将不得不处理该GridView1_PageIndexChanging事件。您需要更改当前的 PageIndex,然后像这样重新绑定GridView

void bindGridview()
{
    SqlCommand command = new SqlCommand("(SELECT ......", Connection);
    SqlDataAdapter myAdapter = new SqlDataAdapter(command);
    DataTable dt = new DataTable();
    myAdapter.Fill(dt);

    command.Connection = connection;
    command.Connection.Open();
    GridView1.AllowPaging = true;
    GridView1.PageSize = 15;
    GridView1.DataSource = dt;
    GridView1.DataBind();


    command.Connection.Close();
    command.Connection.Dispose();
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    bindGridview();
}

如果您还绑定了 GridView Page_Load,请执行以下操作:

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        bindGridview();
}
于 2013-04-12T21:46:44.717 回答
3

您需要添加PageIndexChanging事件GridView以启用paging

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    bindGridview(); 
}
于 2013-04-12T21:48:47.887 回答