使用SqlDataAdapter寻呼SqlDataReader源

Kev*_*vin 5 c# gridview sqldatareader sqldataadapter page-index-changed

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

不幸的是,我的页面仍然没有被分页.这是我的代码在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();
Run Code Online (Sandbox Code Playgroud)

不幸的是,当我这样做时,我的分页没有显示出来.难道我做错了什么?

谢谢

Han*_*año 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();
}
Run Code Online (Sandbox Code Playgroud)

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

protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
        bindGridview();
}
Run Code Online (Sandbox Code Playgroud)