祝贺一下~好不容易把分页做出来了。之前都是用GridView自带的分页,版式难看不说,还极不优化,一次取出所有记录,然后进行假分页。
现在用aspNetPager控件做出的真分页,就好多了,不过还有改进的地方,SQL语句如果换成存储过程效率会更高。
首先在SqlHelper.cs(DAL层中的数据库助手类,用于写可以复用的基本增删查改方法)中加上以下代码:
Code
/**//// <summary>
/// 获取分页数据
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="currentPage">当前页</param>
/// <param name="pagesize">每页显示数</param>
/// <param name="recordcount"></param>
/// <returns></returns>
public static DataSet GetPage(string sql, int currentPage, int pagesize, out int recordcount)
{
openCon();
sqlDs.Clear();
sqlDa = new SqlDataAdapter(sql, sqlConn);
int startRow = (currentPage - 1) * pagesize;
sqlDa.Fill(sqlDs, startRow, pagesize, "table");
recordcount = GetPageRecord(sql);
closeCon();
return sqlDs;
}
//返回总的记录数
public static int GetPageRecord(string sql)
{
openCon();
sql = Regex.Replace(sql, "order by.*", "");
sql = "select count(*) from (" + sql + ") as temp";
sqlCmd = new SqlCommand(sql, sqlConn);
int recordcount = int.Parse(sqlCmd.ExecuteScalar().ToString());
closeCon();
return recordcount;
}
然后在BLL层新建一个PageManager.cs的分页操作类,封装一下DAL层方法:
Code
/**//// <summary>
/// 获取分页数据
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="currentPage">当前页</param>
/// <param name="pagesize">每页显示数</param>
/// <param name="recordcount"></param>
/// <returns></returns>
public static DataSet GetPage(string sql, int currentPage, int pagesize, out int recordcount)
{
return SQLHelper.GetPage(sql, currentPage, pagesize, out recordcount);
}
asp.net需分页的数据绑定处是这样的:
Code
<asp:Repeater ID="repNewsList" runat="server">
<ItemTemplate>
<tr>
<td align="center"><a href="list.aspx?caid=<%# Eval("caId") %>"><%# Eval("name") %></a></td>
<td align="center"><%# Eval("createTime") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>