从服务器端在数据源上分页gridview

时间:2019-02-08 07:58:37

标签: c# asp.net

我正在从服务器端向DataSource分配GridView并应用分页,但是它不起作用。我不知道自己在做什么错以下是我的代码。

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

下面是我的服务器端代码。

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

private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView1.PageIndex = e.NewPageIndex;
    this.BindGrid();
}

0 个答案:

没有答案