DataGrid分页(1)
分页的一种方法:
aspx页面:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server"> <title>分页事例</title> </head> <body> <form id="form1" runat="server"> <div> <asp:DataGrid ID="DataGrid1" runat="server" AllowCustomPaging="True" AllowPaging="True" AutoGenerateColumns="False" Height="204px" OnPageIndexChanged="DataGrid1_PageIndexChanged" PageSize="5" Width="424px"> <PagerStyle Mode="NumericPages" /> <Columns> <asp:BoundColumn DataField="ProductID" HeaderText="ID"></asp:BoundColumn> <asp:BoundColumn DataField="Name"></asp:BoundColumn> <asp:BoundColumn DataField="Content"></asp:BoundColumn> </Columns> </asp:DataGrid></div> </form> </body> </html> 后台aspx.cs代码:
public partial class page : System.Web.UI.Page
{ int startIndex = 0; void Bind()//绑定数据方法 { //定义数据库连接对象 SqlConnection cn = new SqlConnection("Data Source=Net33;Initial Catalog=QMSoftware;Integrated Security=True"); //创建数据适配对象 SqlDataAdapter da=new SqlDataAdapter("select ProductID ,Name ,Content from Product",cn); //创建DataSet对象 DataSet ds=new DataSet(); try { //从指定的索引开始取PageSize条记录. da.Fill(ds,startIndex,DataGrid1.PageSize,"CurDataTable"); da.Fill(ds,"AllDataTable");//填充数据集合 //设置DataGrid控件实际要显示的项数 DataGrid1.VirtualItemCount=ds.Tables["AllDataTable"].Rows.Count; //进行数据绑定 DataGrid1.DataSource=ds.Tables["CurDataTable"]; DataGrid1.DataBind(); } catch { Page.RegisterClientScriptBlock("","<script>alert('数据显示错误');</script>"); } } protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Bind(); } } protected void DataGrid1_PageIndexChanged(object source, DataGridPageChangedEventArgs e) { DataGrid1.CurrentPageIndex=e.NewPageIndex; //取得当前页为止总共有多少条记录,以便在下一页就从该记录开始读取 startIndex=DataGrid1.PageSize*DataGrid1.CurrentPageIndex; //取得绑定数据 Bind(); } 本文出自 51CTO.COM技术博客} |


zxb1029
博客统计信息
热门文章
最新评论
友情链接