前台代码:
<webdiyer:AspNetPager ID="AspNetPager1" runat="server" FirstPageText="首页" LastPageText="尾页"
NextPageText="下一页" PrevPageText="上一页" HorizontalAlign="Center" OnPageChanged="AspNetPager1_PageChanged"
PageIndexBoxType="DropDownList" ShowPageIndexBox="Always" UrlPaging="True"
ShowNavigationToolTip="True" PageSize="1">
</webdiyer:AspNetPager>
后台代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
public void BindGridView()
{
string sql = "select ID,SmallClassID,NewsTitle,Checked,Commend,AddTime from NewsAdd";//自定义的SQL语句
int recordcount;
DataSet ds = GetPage(sql, this.AspNetPager1.CurrentPageIndex, this.AspNetPager1.PageSize, out recordcount);
this.AspNetPager1.RecordCount = recordcount;
this.Repeater1.DataSource = ds;
this.Repeater1.DataBind();
}
public DataSet GetPage(string sql, int currentPage, int pagesize, out int recordcount)
{
SqlDataAdapter ada = new SqlDataAdapter(sql, GetConnection());
DataSet ds = new DataSet();
int startRow = (currentPage - 1) * pagesize;
ada.Fill(ds, startRow, pagesize, "table");
recordcount = GetPageRecord(sql);
return ds;
}
public int GetPageRecord(string sql)
{
sql = System.Text.RegularExpressions.Regex.Replace(sql, "order by.*", "");
sql = "select count(*) from (" + sql + ") as temp";
SqlCommand cmd = new SqlCommand(sql, GetConnection());
cmd.Connection.Open();
int recordcount = (int)cmd.ExecuteScalar();
return recordcount;
}
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
BindGridView();
}
public SqlConnection GetConnection() //获得SqlConnection对象
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString());
}