AspNetPager使用初步
AspNetPager是一款优秀的分页控件,使用该控件进行数据源分页,关键是设置该控件的RecordCount、StartRecordIndex和EndRecordIndex属性和处理PageChanged事件。
主要代码如下:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
AspNetPager1.RecordCount = GetRecordCount();//总记录数
Bind();
}
}
void Bind()
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(@"server=.\sqlexpress;database=北风贸易;uid=sa;pwd=sa"))
{
SqlCommand cmd = new SqlCommand("GetPageData", conn);
cmd.Parameters.AddWithValue("@startIndex", AspNetPager1.StartRecordIndex);
cmd.Parameters.AddWithValue("@endIndex", AspNetPager1.EndRecordIndex);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(dr);
dr.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
int GetRecordCount()
{
string sql="select count(*) from 产品资料";
int n=0;
using(SqlConnection conn=new SqlConnection(@"server=.\sqlexpress;database=北风贸易;uid=sa;pwd=sa"))
{
SqlCommand cmd=new SqlCommand(sql,conn);
conn.Open();
n=(int)cmd.ExecuteScalar();
}
return n;
}
protected void AspNetPager1_PageChanged(object sender, EventArgs e)
{
Bind();
}
对应的存储过程如下:
create procedure GetPageData
(@startIndex int,
@endIndex int
)
as
begin
with temptbl as (
SELECT ROW_NUMBER() OVER (ORDER BY 单价 desc)AS Row, * from 产品资料 )
SELECT * FROM temptbl where Row between @startIndex and @endIndex
end
该存储过程可以使用AspNetPager自动产生,只需填入信息即可:
有关AspNetPager的更多介绍,请参考http://www.webdiyer.com/