ASP.NET Ajax 实现无刷新分页
使用Ajax的UpdatePanel控件和DataList控件 实现的无刷新分页。
详细过程:
1.1. 启动sqlserver,创建数据库ajax数据库中创建sale表,点击新建查询,写入代码:
create table sale
(
sid char(5) primary key, --销售编号
pid char(5), --商品编号
pname varchar(50), --商品名称
unit varchar(4), --单位
number int, --销售数量
price decimal, --单价
sdate datetime, --销售日期
people varchar(20) --经手人
)
go
2.1 点击文件-新建-网站,命名WebAjax,点击确定按钮。
2.2.在默认项目中 添加个web窗体,命名为Default
2.3.在Default页面中,拖入一个ScriptManager控件,再拖入一个UpdatePanel控件
2.4.在UpdatePanel中拖入一个DataList控件,用来显示和分页 数据库中的商品数据;
2.5.写好DataList中数据模版和 模版样式
2.6.拖入三个个Lable控件,Lable1用来显示当前页,Lable2用来显示总页数,Lable3存储当前页码
。
2.7.拖入四个Button控件,Button1用来控制 显示首页数据,Button2用来控制 显示上一页数据,
Button3用来控制 显示下一页数据,Button4用来控制 显示尾页数据,
2.8,写后台cs代码,调试并成功。
1.前台:
2.后台using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; public partial class _Default : System.Web.UI.Page { SqlConnection sqlcon = new SqlConnection(@"server=.sqlexpress;database=ajax;integrated security=SSPI"); public string strsql = "SELECT * FROM sale"; PagedDataSource page = new PagedDataSource(); protected void Page_Load(object sender, EventArgs e) { BindList(1); } private void BindList(int index) { SqlDataAdapter adp = new SqlDataAdapter(strsql, sqlcon); sqlcon.Open(); DataSet dst = new DataSet(); adp.Fill(dst, "table"); DataTable tab = new DataTable(); tab = dst.Tables["table"]; page.DataSource = tab.DefaultView; //分页实现 page.PageSize = 3; page.AllowPaging = true; page.CurrentPageIndex = index - 1; this.Label1.Text = index.ToString(); this.Label2.Text = page.PageCount.ToString(); DataList1.DataSource = page; DataList1.DataBind(); sqlcon.Close(); } protected void Button1_Click(object sender, EventArgs e) { BindList(1); Label3.Text = "1"; } protected void Button2_Click(object sender, EventArgs e)//上一页 { if (Convert.ToInt32(Label3.Text) == 1) { BindList(1); Label3.Text = "1"; } else { BindList(Convert.ToInt32(Label3.Text)-1); Label3.Text = (Convert.ToInt32(Label3.Text)-1).ToString(); } } protected void Button3_Click(object sender, EventArgs e)//下一页 { if (Convert.ToInt32(Label3.Text) == (page.PageCount - 1)) { BindList(page.PageCount); Label3.Text = page.PageCount.ToString(); } else { BindList(Convert.ToInt32(Label3.Text) + 1); Label3.Text = (Convert.ToInt32(Label3.Text) + 1).ToString(); } } protected void Button4_Click(object sender, EventArgs e) { BindList(page.PageCount); Label3.Text = page.PageCount.ToString(); } }