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

问题描述 投票:0回答:1

我正在尝试对 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();

}
c# asp.net gridview pagination webforms
1个回答
1
投票

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

gwActivity.DataSource = cmd.ExecuteReader();

AFAIK,

SqlDataReader
方法使用的
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();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.