绑定到Datatable-Paging的GridView无法正常工作

时间:2016-05-23 06:27:24

标签: c# asp.net gridview datatable

我设置了一个带有按钮单击的webform,它解析.txt文件并将其放入数据表中。解析结束时,数据表绑定到gridview。我试图添加分页,因为我得到了大量的行,但似乎没有正常工作。每当我点击下一页时,网格就会消失,并且要再次出现在正确的页面上,我需要再次单击该按钮。

我尝试将以下代码添加到源代码中:

// string only contain the a to z , A to Z, 0 to 9,  -_

这一点:

<asp:GridView ID="GridView1" Runat="server" 
     AutoGenerateColumns="true"
     AllowPaging="True" OnPageIndexChanging="OnPageIndexChanging" >

但它似乎没有改变任何东西。对我做错了什么的想法?

2 个答案:

答案 0 :(得分:0)

尝试在GridView中添加OnPageIndexChanging事件

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
OnPageIndexChanging="OnPageIndexChanging" PageSize="5">

和你的aspx.cs代码。尝试在Page_Load事件上绑定Gridview。

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

 protected void Page_Load(object sender, EventArgs e)
  { this.BindGrid();}

 private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * From [dbo].[your table] "))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();
                    }
                }
            }
        }
    }

答案 1 :(得分:0)

protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        //here yo have to assign datasource 
       //Some thing like this
       ///GridView1.DataSource=DataTable;
        GridView1.DataBind();
    }