在Gridview中分页 - 数据源不支持服务器端数据分页

时间:2018-04-03 08:08:48

标签: c# asp.net gridview webforms paging

我正在尝试使用我的GridView的分页,但是我收到一个错误:“ 数据源不支持服务器端数据分页 ”。

我不明白我做错了什么......

HTML(ASPX标记):

<asp:GridView ID="gwActivity" runat="server" AutoGenerateColumns="False" AllowPaging="True" OnRowCommand="gwActivity_RowCommand" CssClass="gwActivity" OnPageIndexChanging="gwActivity_PageIndexChanging">................[Plus more]

代码背后:

public void BindGridviewActivity()
{
    /*************Connectionstring is located in Web.config ******************/
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("SELECT T1.[ActivityID] FROM [BI_Planning].[dbo].[tlbActivity]", con);
        con.Open();
        gwActivity.DataSource = cmd.ExecuteReader();
        gwActivity.DataBind();
    }
}

代码隐藏(GridView):

protected void gwActivity_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gwActivity.PageIndex = e.NewPageIndex;
    BindGridviewActivity();

}

1 个答案:

答案 0 :(得分:1)

最常见的例外是这一行:

gwActivity.DataSource = cmd.ExecuteReader();

SqlDataReader方法使用的AFAIK ExecuteReader()不能用于绑定为GridView数据源,因为它只是前向读取器,不支持分页功能。使用其他数据源,如SqlDataAdapter,支持双向数据读取,如下所示:

public void BindGridviewActivity()
{
    /*************Connectionstring is located in Web.config ******************/
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("SELECT T1.[ActivityID] FROM [BI_Planning].[dbo].[tlbActivity]", con);
        con.Open();

        var da = new SqlDataAdapter(cmd);
        var ds = new DataSet();
        da.Fill(ds);

        if (ds.Tables.Count > 0)
        {
            gwActivity.DataSource = ds.Tables[0];
            gwActivity.DataBind();
        }
    }
}