DataGrid的分页无法正常工作

时间:2018-05-17 07:37:24

标签: c# asp.net datagrid pagination

我试图将分页添加到我的数据网格但它没有显示,而数据网格只显示第1页,我无法点击页码

这是我的 aspx

<asp:DataGrid ID="grid1" runat="server" AutoGenerateColumns="False"
AllowPaging="True" PageSize="5" AllowCustomPaging="true" 
OnPageIndexChanged="grid1_PageIndexChanging">

<HeaderStyle HorizontalAlign="Center" Height="30px"></HeaderStyle>
     <Columns>
         <asp:TemplateColumn HeaderText="ID" >
            <HeaderStyle Font-Underline="false" Height="15px" Width="5%" HorizontalAlign="Center" BackColor="#ccffcc"></HeaderStyle>
                <ItemStyle HorizontalAlign="Center"></ItemStyle>
                    <ItemTemplate>
                        <asp:Label id="lblID" runat="server" text='<%#DataBinder.Eval(Container.DataItem, "ID_")%>'></asp:Label>
                    </ItemTemplate>
        </asp:TemplateColumn>
      </Columns>
      <PagerStyle Font-Bold="True" ForeColor="black" HorizontalAlign="left" Wrap="True" Mode="NumericPages" />
      <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
      </asp:DataGrid>

在我的 aspx.cs 上我添加了BindGrid()但是它没有工作

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

protected void grid1_PageIndexChanging(object source, DataGridPageChangedEventArgs e)
{
    grid1.CurrentPageIndex = e.NewPageIndex;
    grid1.VirtualItemCount = 1000;
    BindGrid();
}

private void BindGrid() 
{
    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    con.ConnectionString = gc.GetWebConfigConnectionStringAIS();
    con.Open();
    string query = "SELECT ID_ FROM dbo.Testing";
    cmd = new SqlCommand(query, con);
    cmd.CommandType = CommandType.Text;

    using (SqlDataReader dr = cmd.ExecuteReader())
    {
        grid1.DataSource = dr;
        grid1.DataBind();
    }

    con.Close();
    grid1.Visible = true;
}

2 个答案:

答案 0 :(得分:0)

确认您有足够的数据可以填充到更多的那一页

答案 1 :(得分:0)

使用数据集解决您的问题

private void BindGrid() 
{
    //declare DataSet attribute
    SqlDataAdapter da;  
    DataSet ds = new DataSet(); 

    SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    con.ConnectionString = gc.GetWebConfigConnectionStringAIS();
    con.Open();
    string query = "SELECT ID_ FROM dbo.Testing";
    cmd = new SqlCommand(query, con);
    cmd.CommandType = CommandType.Text;

    //here happens the magic
    cmd.Connection = con;  
    da = new SqlDataAdapter(cmd);  
    da.Fill(ds);  
    cmd.ExecuteNonQuery();

    //using dataset instead of reader will resolve your issue
    Grid.DataSource = ds;  
    Grid.DataBind();  

    using (SqlDataReader dr = cmd.ExecuteReader())
    {
        grid1.DataSource = dr;
        grid1.DataBind();
    }

    con.Close();
    grid1.Visible = true;
}

here 官方文档