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