在ASP.Net内中,如何做到分页 我不只一次地被别人问起,如何在ASP.Net实现分页功能。我实在不愿意回答这个问题。因为在ASP.Net中实现分页,实在是太简单了,简单到你一看到程序就会去气得跳楼,呵呵要发表感叹,为什么这个东东不早出来。 在以住的WEB技术中,我们要做到分页,经常是一长串代码才能搞定它,而且每用一个页面,就要重写一次,烦的要命。但是在ASP.Net中借助DataGrid控件,我们分页程序可以轻松搞定,需要的只是对DataGrid控件做一些设定。我们还是借助一个程序来看:) <% @ Page Language="C#" %> <% @ Import Namespace="System.Data" %> <% @ Import Namespace="System.Data.ADO" %> <Script Language="C#" Runat="Server"> public void Page_Load(Object src,EventArgs e) { //联结语句 string MyConnString = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=c:/test/test.mdb;"; string strComm = "select * from UserList order by id"; //打开一个联结 ADOConnection MyConnection = new ADOConnection(MyConnString); //打开两个DataSetCommand ADODataSetCommand MyComm = new ADODataSetCommand(strComm,MyConnection); DataSet MyDataSet = new DataSet(); //把UserList,BookList表存入DataSet MyComm.FillDataSet(MyDataSet,"UserList"); DataGrid1.DataSource = MyDataSet.Tables["UserList"].DefaultView; DataGrid1.DataBind(); } </script> <html> <head> <title></title> </head> <body> <form runat="server"> <ASP:DataGrid id="DataGrid1" runat="server" BorderColor="black" BorderWidth="1" GridLines="Both" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#aaaadd" AlternatingItemStyle-BackColor="#eeeeee" /> </form> </body> </html> 它的显示结果为: 图11-1 大家可以看到在这个UserList表中的11条数据全都出来了,没有分页。 下面我们小改一下DataGrid控件的属性。加上 AllowPaging="True" PageSize="5" PagerStyle-HorizontalAlign="Right" 再看看: 图11-2 看看图片的最下面,是不是多了,是不是,这就表示分页啦,我们去按那个标签就可以看到下一页的情况:) 图11-4 这一切是不是太简单了。呵呵。他们的来源只是我加了那三个属性。其实只要一个AllowPaging就行了。 AllowPaging是指允许分页,这个是最主要的。有了它,我们才能分页。 PageSize是指定每页显示的记录数,如果不写,就会默认为10条。 PagerStyle-HorizontalAlign是指定分面显示的定位,默认是Left。 全部代码是: <ASP:DataGrid id="DataGrid1" runat="server" AllowPaging="True" PageSize="5" PagerStyle-HorizontalAlign="Right" BorderColor="black" BorderWidth="1" GridLines="Both" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#aaaadd" AlternatingItemStyle-BackColor="#eeeeee" /> 是不是很简单。呵呵。 注意写这个时不要忘记<form>了,不然你的页是能显示,但是不能翻,呵呵。因为这是需要提交的:) 下一节我们再讲解更详细的内容,呵呵,主要是考虑到图片太多了。浏览速度会变慢。
|