基本函數如下:
複製代碼 代碼如下:/// <summary>
/// 需要分頁時使用,根據參數和ConditionExpress擷取DataTable
/// </summary>
/// <param name="_tableName">表名</param>
/// <param name="_fieldNames">欄位名集合,用逗號分開</param>
/// <param name="_OrderColumn">排序欄位,用於統計有多少條記錄</param>
/// <param name="IsDesc">是否倒序</param>
/// <param name="_indexColumn">自增欄位名</param>
/// <param name="_currentPage">當前頁</param>
/// <param name="pageSize">頁大小</param>
/// <param name="_rowsCount">總記錄數</param>
/// <returns>擷取到的DataTable</returns>
public static DataTable GetDataTable(string _tableName, string _fieldNames, string _OrderColumn, bool IsDesc, string _indexColumn, int _currentPage, int pageSize, string conditionExpress, ref int _rowsCount)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
string whereStr = " where 1=1 ";
string sort = IsDesc ? " desc" : " asc";
string sqlStr = " from " + _tableName;
//排序欄位
string orderStr = " order by " + _OrderColumn + sort;
if (_OrderColumn != _indexColumn)
orderStr += "," + _indexColumn + sort;
if (conditionExpress != string.Empty)
{
whereStr += conditionExpress;
}
sqlStr += whereStr;
//取得合格資料總數
SqlCommand cmd = new SqlCommand("select count(" + _OrderColumn + ") " + sqlStr, conn);
conn.Open();
try
{
_rowsCount = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
if (_currentPage > _rowsCount) _currentPage = _rowsCount;
if (_currentPage > 1)
{
if (IsDesc)
sqlStr += " and " + _OrderColumn + " < (select MIN(" + _OrderColumn + ") from ";
else
sqlStr += " and " + _OrderColumn + " > (select MAX(" + _OrderColumn + ") from ";
sqlStr += "(select top " + (pageSize * (_currentPage - 1)) + " " + _OrderColumn + " from " + _tableName + whereStr + orderStr + ") as t)";
}
sqlStr = "select top " + pageSize + " " + _fieldNames + sqlStr + orderStr;
try
{
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
da.Fill(ds);
return ds.Tables[0];
}
catch (Exception EX)
{
throw new Exception(EX.Message);
}
}
}
調用如下: 複製代碼 代碼如下:private void bind()
{
int rowCount = 1;
string wherestr = string.Empty;
//設定分頁
anPager.AlwaysShow = true;
anPager.PageSize = 10;
this.rptdictionary.DataSource = GetDataTable(
"dictionary_Toysgogo_",
"[id_dictionary_],[namecn_dictionary_],[nameen_dictionary_],[point_dictionary_]",
"[id_dictionary_]",
true,
"[id_dictionary_]",
this.anPager.CurrentPageIndex,
anPager.PageSize,
wherestr,
ref rowCount
);
this.anPager.RecordCount = rowCount;
this.rptdictionary.DataBind();
}
複製代碼 代碼如下://分頁切換
protected void anPager_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
{
this.anPager.CurrentPageIndex = e.NewPageIndex;
this.tbxType.Text = this.tbxType.Text;
bind();
}
之前一直在頁數方面直接用數字寫進去,沒有寫成anPager.PageSize=10;的形式,在老湯的提醒下,做了修改,也解決了一直困擾我的問題。