Gridview中的分页——数据源不支持服务端数据分页

Paging in Gridview - The data source does not support server-side data 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();

}

异常最有可能来自这一行:

gwActivity.DataSource = cmd.ExecuteReader();

AFAIK,ExecuteReader() 方法使用的 SqlDataReader 不能用于绑定为 GridView 数据源,因为它是 forward-only reader 并且不' 支持分页功能。使用另一个支持 bi-directional 数据读取的数据源,例如 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();
        }
    }
}