我有一个执行自定义查询的页面,该查询保存在数据库的某个位置。我需要能够在 gridview 上启用分页。
例如,保存在数据库中的查询如下所示:
select * from requestbases
这将返回 10,000 行。
使用下面的方法,我让它返回 10 行。
public DataTable GetGenericResults(string strsql, int pageIndex)
{
StringBuilder sb = new StringBuilder();
sb.Append("WITH MyPagedData as ( ");
int indexFrom = strsql.IndexOf("from");
sb.Append(strsql.Substring(0, indexFrom));
sb.Append(", ");
sb.Append("ROW_NUMBER() OVER(ORDER BY RequestBaseId DESC) as RowNum ");
sb.Append(strsql.Substring(indexFrom));
sb.Append(") ");
sb.Append("SELECT * from MyPagedData where RowNum between @StartIndex and @StartIndex + 10");
using(var connection = (SqlConnection)_context.Database.Connection)
{
var adapter = new SqlDataAdapter(sb.ToString(), connection);
adapter.SelectCommand.Parameters.Add("@StartIndex", SqlDbType.Int).Value = pageIndex;
var results = new DataSet();
adapter.Fill(results, "Results");
return results.Tables["Results"];
}
}
这是绑定网格的代码
var datatable = RequestBaseBL.GetGenericResults(query.QuerySql, 0);
if (datatable.Rows.Count > 0)
{
LblCount.Text = datatable.Rows.Count + " records";
PanelResults.Visible = true;
GrvCustomResults.Visible = true;
GrvCustomResults.DataSource = datatable;
GrvCustomResults.DataBind();
}
问题是查询本身返回 10 行,因此 gridview 永远不会显示寻呼机。
<asp:GridView ID="GrvCustomResults" runat="server" Visible="false" AutoGenerateColumns="true">
<PagerSettings
Visible="true"
Position="TopAndBottom"
PreviousPageText="Previous"
NextPageText="Next"
Mode="NumericFirstLast" />
<HeaderStyle CssClass="gridheader" />