此例子使用的是northwind数据库,里面用了分页存储过程,具体实现根据你设置的 datagrid的每页的大小,每次从数据库中取出相对的记录,具体效果如图。
下面还把常用的几种删除记录的方式也写了一下(1.根据选中的checkbox,一次删除多条记录,2.属性生成器里添加的删除按钮列删除,3.在模板列中放入button按钮,每次删除之前都会有提示框,代码如下)
说明:由于这个程序我用到了数据访问层,所以数据库访问层的代码没有放上来,自己可以写一下,用到地方下面的代码会有说明
关于删除的方法,由于northwind表是sqlserver自带的,所以用了一个方法代替一下,并没有真正的删除记录,代码我注释掉了,不过逻辑是一样的。
关于页面的跳转,我用了dropdownlist控件和textbox控件,用dropdownlist控件看的清楚,使用方便,但是一旦记录很多,页数增加,那就要每次都清除,每次加载一次,可能会影响效率,所以我用了两种方法,供其选择。
希望这个例子对大家有所帮助,也希望能够多提意见!
以下为存储过程,一个是分页存储过程,一个是得到总记录的存储过程
分页存储过程:
set quoted_identifier on
go
set ansi_nulls on
go
alter procedure test_getorders
(@pagesize int, –页面大小,如每页存储20条记录
@pageindex int –当前页码
)
as
set nocount on
begin
declare @indextable table(id int identity(1,1),nid int) –定义表变量
declare @pagelowerbound int –定义此页的底码
declare @pageupperbound int –定义此页的顶码
set @pagelowerbound=(@pageindex-1)*@pagesize
set @pageupperbound=@pagelowerbound+@pagesize
set rowcount @pageupperbound
insert into @indextable(nid) select orderid from orders order by orderid desc
select orderid,customerid,convert(char(10),orderdate,120) as orderdate,
shipcity,shipcountry,isnull(shipregion,无) as shipregion
from orders a
inner join @indextable t
on a.orderid=t.nid
where t.id>@pagelowerbound and t.id<=@pageupperbound
order by t.id
end
set nocount off
go
set quoted_identifier off
go
set ansi_nulls on
go
得到总记录的存储过程:
set quoted_identifier on
go
set ansi_nulls on
go
alter proc getordercount
as
–得到orders表的总记录数
select count(*) from orders
go
set quoted_identifier off
go
set ansi_nulls on
go
前台的代码:
<%@ page language=”c#” codebehind=”orderspage.aspx.cs” autoeventwireup=”false” inherits=”nettest.orderspage” %>
<!doctype html public “-//w3c//dtd html 4.0 transitional//en” >
<html>
<head>
<title>northwind数据库orders表的分页例子</title>
<meta name=”generator” content=”microsoft visual studio .net 7.1″>
<meta name=”code_language” content=”c#”>
<meta name=”vs_defaultclientscript” content=”javascript”>
<link href=”css/basiclayout.css” rel=”stylesheet” type=”text/css”>
<meta name=”vs_targetschema” content=”http://schemas.microsoft.com/intellisense/ie5″>
</head>
<body ms_positioning=”gridlayout”>
<script language=”javascript”>
function selectall()
{
var len=document.form1.elements.length;
var i;
for (i=0;i<len;i++)
{
if (document.form1.elements[i].type==”checkbox”)
{
document.form1.elements[i].checked=true;
}
}
}
function unselectall()
{
var len=document.form1.elements.length;
var i;
for (i=0;i<len;i++)
{
if (document.form1.elements[i].type==”checkbox”)
{
document.form1.elements[i].checked=false;
}
}
}
</script>
<form id=”form1″ method=”post” runat=”server”>
<table align=”center” border=”0″ width=”60%”>
<tr>
<td align=”right”>
<asp:regularexpressionvalidator id=”regularexpressionvalidator1″ runat=”server” errormessage=”页数只能为数字” display=”none”
controltovalidate=”txtpage” validationexpression=”\d{0,10}”></asp:regularexpressionvalidator>
<asp:validationsummary id=”validationsummary1″ runat=”server” showmessagebox=”true” showsummary=”false”></asp:validationsummary></td>
</tr>
<tr>
<td align=”center”><font style=”font-size: 10pt”>共</font>
<asp:label id=”lbtotalpage” runat=”server” cssclass=”pagelinks”></asp:label>
<font style=”font-size: 10pt”>页/共
<asp:label id=”lbtotalcount” runat=”server” cssclass=”pagelinks”></asp:label>
记录 当前</font>
<asp:label id=”lbcurrentpage” runat=”server” cssclass=”pagelinks”></asp:label>
<font style=”font-size: 10pt”>页</font>
<font style=”font-size: 10pt”>跳转到</font>
<asp:dropdownlist id=”ddlpage” runat=”server” autopostback=”true” width=”65px”></asp:dropdownlist>
<font style=”font-size: 10pt”>页</font>
<asp:textbox id=”txtpage” runat=”server” width=”43px”></asp:textbox>
<asp:button id=”btngo” runat=”server” cssclass=”redbuttoncss” width=”34px” text=”go”></asp:button><font size=”2″>
</font>
</td>
</tr>
<tr>
<td align=”right”><input type=”button” value=”全部选择” onclick=”selectall()”><font face=”宋体”>
</font><input type=”button” value=”全部取消” onclick=”unselectall()”><font face=”宋体”>
</font>
<asp:button id=”btndelete” runat=”server” text=”删除”></asp:button><font face=”宋体”>
</font>
</td>
</tr>
<tr>
<td>
<asp:datagrid id=”dborders” runat=”server” autogeneratecolumns=”false” width=”100%” borderstyle=”none”
bordercolor=”#93bee2″ pagesize=”20″ allowcustompaging=”true” allowpaging=”true” datakeyfield=”orderid”>
<itemstyle font-size=”x-small” horizontalalign=”center” height=”25px” backcolor=”#ccffff”></itemstyle>
<headerstyle font-size=”x-small” font-bold=”true” horizontalalign=”center” height=”25px” backcolor=”#6699ff”></headerstyle>
<columns>
<asp:templatecolumn>
<itemtemplate>
<font face=”宋体”>
<asp:checkbox id=”cbflag” runat=”server”></asp:checkbox></font>
</itemtemplate>
</asp:templatecolumn>
<asp:boundcolumn datafield=”orderid” headertext=”订单编号”></asp:boundcolumn>
<asp:boundcolumn datafield=”customerid” headertext=”客户编号”></asp:boundcolumn>
<asp:boundcolumn datafield=”orderdate” headertext=”订单日期”></asp:boundcolumn>
<asp:boundcolumn datafield=”shipcity” headertext=”运输城市”></asp:boundcolumn>
<asp:boundcolumn datafield=”shipcountry” headertext=”运输国家”></asp:boundcolumn>
<asp:boundcolumn datafield=”shipregion” headertext=”运输区域”></asp:boundcolumn>
<asp:buttoncolumn text=”删除” commandname=”delete”></asp:buttoncolumn>
<asp:templatecolumn>
<itemtemplate>
<font face=”宋体”>
<asp:button id=”btnadelete” runat=”server” cssclass=”redbuttoncss” commandname=”delete” text=”删除”></asp:button></font>
</itemtemplate>
</asp:templatecolumn>
</columns>
<pagerstyle visible=”false”></pagerstyle>
</asp:datagrid>
</td>
</tr>
<tr>
<td align=”center” height=”30″><b><asp:linkbutton id=”firstpage” runat=”server” cssclass=”pagelinks” text=”[first page]” commandname=”first”
oncommand=”navigationlink_click”>第一页</asp:linkbutton>
<asp:linkbutton id=”previouspage” runat=”server” cssclass=”pagelinks” text=”[previous page]” commandname=”prev”
oncommand=”navigationlink_click”>上一页</asp:linkbutton>
<asp:linkbutton id=”nextpage” runat=”server” cssclass=”pagelinks” text=”[next page]” commandname=”next”
oncommand=”navigationlink_click”>下一页</asp:linkbutton>
<asp:linkbutton id=”lastpage” runat=”server” cssclass=”pagelinks” text=”[last page]” commandname=”last”
oncommand=”navigationlink_click”>末一页</asp:linkbutton></b>
</td>
</tr>
</table>
</form>
</body>
</html>
后台代码:
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
using databaseclass;
using system.data.sqlclient;
namespace nettest
{
/// <summary>
/// orderspage 的摘要说明。
/// </summary>
public class orderspage : system.web.ui.page
{
protected system.web.ui.webcontrols.label lbtotalpage;
protected system.web.ui.webcontrols.label lbtotalcount;
protected system.web.ui.webcontrols.label lbcurrentpage;
protected system.web.ui.webcontrols.dropdownlist ddlpage;
protected system.web.ui.webcontrols.linkbutton firstpage;
protected system.web.ui.webcontrols.linkbutton previouspage;
protected system.web.ui.webcontrols.linkbutton nextpage;
protected system.web.ui.webcontrols.datagrid dborders;
protected system.web.ui.webcontrols.linkbutton lastpage;
private classdatagrid cdg=new classdatagrid();//数据访问层的类,定义的的一个实例
protected system.web.ui.webcontrols.button btngo;
protected system.web.ui.webcontrols.textbox txtpage;
protected system.web.ui.webcontrols.validationsummary validationsummary1;
protected system.web.ui.webcontrols.regularexpressionvalidator regularexpressionvalidator1;
protected system.web.ui.webcontrols.button btndelete;
protected int32 currentpagenumber = 1;//初始化,设置当前页为1,随时都要使用
private void page_load(object sender, system.eventargs e)
{
if(!ispostback)
{
binddata();
btndelete.attributes [“onclick”]=”javascript:return confirm(您确认要删除吗?);”;
}
}
#region web 窗体设计器生成的代码
override protected void oninit(eventargs e)
{
//
// codegen: 该调用是 asp.net web 窗体设计器所必需的。
//
initializecomponent();
base.oninit(e);
}
/// <summary>
/// 设计器支持所需的方法 – 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.ddlpage.selectedindexchanged += new system.eventhandler(this.ddlpage_selectedindexchanged);
this.btngo.click += new system.eventhandler(this.btngo_click);
this.dborders.itemcommand += new system.web.ui.webcontrols.datagridcommandeventhandler(this.dborders_itemcommand);
this.dborders.deletecommand += new system.web.ui.webcontrols.datagridcommandeventhandler(this.dborders_deletecommand);
this.dborders.itemdatabound += new system.web.ui.webcontrols.datagriditemeventhandler(this.dborders_itemdatabound);
this.btndelete.click += new system.eventhandler(this.btndelete_click);
this.load += new system.eventhandler(this.page_load);
}
#endregion
public int32 getcountorders()
{
int32 tcount=int32.parse(cdg.getordercount());//此处用到了数据访问层,得到总记录数,代码要自己写一下
return tcount;
}
protected void navigationlink_click ( object sender, commandeventargs e )//此事件为html代码里注册(事件为oncommand)
{
switch ( e.commandname )//根据设置的commandname属性判断
{
case “first”:
currentpagenumber = 1;
break;
case “last”:
currentpagenumber = int32.parse ( lbtotalpage.text );
break;
case “next”:
currentpagenumber = int32.parse ( lbcurrentpage.text ) + 1;
break;
case “prev”:
currentpagenumber = int32.parse ( lbcurrentpage.text ) – 1;
break;
}
binddata();
}
public void binddata()
{
lbcurrentpage.text = currentpagenumber.tostring();
int pagesize=int.parse(dborders.pagesize.tostring());
//绑定datagrid,此处用到数据访问层,只要可以绑定就可以了(dataset,datatable都可以),这里的代码要自己写一下
sqldatareader dr=cdg.getorders(pagesize,currentpagenumber);
dborders.datasource=tools.convertdatareadertodatatable(dr);
dborders.databind();
double totalpages = 1;//初始化,总页数为1
double modepages=0;//取模余数(判断总页数是否要加1)
int32 totalrecords = getcountorders();//调用上面的得到总记录数的方法
totalpages = totalrecords / pagesize;//得到总页数(总记录数除以每页的记录数)
modepages=totalrecords%pagesize;//得到取模的余数(总记录数取模每页的记录数)
if(modepages>0)//如果取模数不等于0,则把总页数加1
{
totalpages+=1;
}
if(modepages==0)//如果取模数等于0,不做任何事(也可以不用判断)
{
}
lbtotalpage.text = totalpages.tostring();//显示页面上的总页数
lbtotalcount.text=totalrecords.tostring();//显示页面上的总记录数
//以下为判断点击的按钮(第一页,上一页,下一页,末一页)是否可以用
if ( currentpagenumber == 1 )
{
previouspage.enabled = false;
firstpage.enabled=false;
if ( totalpages > 1 )
{
nextpage.enabled = true;
lastpage.enabled=true;
}
else
{
nextpage.enabled = false;
lastpage.enabled=false;
}
}
else
{
previouspage.enabled = true;
firstpage.enabled=true;
if ( currentpagenumber == totalpages )
{
nextpage.enabled = false;
lastpage.enabled=false;
}
else
{
nextpage.enabled = true;
lastpage.enabled=true;
}
}
ddlpage.items.clear();//清楚跳转的页数(如果不清除,里面的记录将会循环增加)
int pcount=int.parse(lbtotalpage.text);//得到总页数,为了循环
for(int i=1;i<=pcount;i++)
{
ddlpage.items.add(i.tostring());
}
ddlpage.items.findbytext(currentpagenumber.tostring()).selected=true;//把当前页显示在列表框的第一个
}
private void ddlpage_selectedindexchanged(object sender, system.eventargs e)
{
int pagesize=int.parse(ddlpage.selectedvalue.tostring());
int pagecount=int32.parse(lbtotalpage.text.trim().tostring());
if(pagesize<1)
{
currentpagenumber=1;
}
else if(pagesize>pagecount)
{
currentpagenumber=pagecount;
}
else
{
currentpagenumber=pagesize;
}
binddata();
}
private void btngo_click(object sender, system.eventargs e)
{
int pagesize=int.parse(txtpage.text.trim().tostring());
int pagecount=int32.parse(lbtotalpage.text.trim().tostring());
if(pagesize<1)
{
currentpagenumber=1;
}
else if(pagesize>pagecount)
{
currentpagenumber=pagecount;
}
else
{
currentpagenumber=pagesize;
}
binddata();
}
private void btndelete_click(object sender, system.eventargs e)
{
try
{
string selectedstring = “”;//定义一个变量
foreach(datagriditem data in dborders.items)
{
for(int i=0;i<data.cells[0].controls.count;i++)//循环datagrid的第一个单元格
{
if(data.cells[0].controls[i].gettype().tostring()==”system.web.ui.webcontrols.checkbox”)//判断类型是否为checkbox
{
if(((checkbox)data.cells[0].controls[i]).checked==true)//如果checkbox被选中
{
selectedstring += dborders.datakeys[data.itemindex].tostring() + “,”;
//因为设置了datagrid的datakeyfield属性(编号),所以可以根据datakeys得到选中checkbox的那行所对应的那条记录的编号
//以逗号分隔,加入同一个字符串中
}
}
}
}
if(selectedstring!=””)
{
bool result=true;
selectedstring = selectedstring.substring(0,selectedstring.length-1);//截取最后一个逗号
string[] arr = selectedstring.split(,);//分割字符串,放入数组中
for(int i=0;i<arr.length;i++)//循环数组
{
if(arr[i].trim()!=””)//如果值不为空
{
//result=cdg.deleteorder(int32.parse(arrselected[i]));//删除一条记录
//这里的deleteuser是我写的数据层的方法,返回的是bool,如果删除成功,返回true;
//此处的删除方法可以根据自己的需求写,所以这里就不写了
}
}
if(result)
{
response.write(“<script>alert(用户删除成功)</script>”);
}
}
binddata();
}
catch
{
response.write(“<script>alert(过程出现错误,删除失败,请查找原因)</script>”);
}
}
private void dborders_itemdatabound(object sender, system.web.ui.webcontrols.datagriditemeventargs e)
{
if(e.item.itemtype==listitemtype.item)//这是判断属性生成器里添加的删除,弹出一个删除对话框
{
if(e.item.itemtype==listitemtype.item)//这个删除的事件在deletecommand中执行
{
linkbutton btn=(linkbutton)e.item.cells[7].controls[0];
btn.attributes.add (“onclick”,
“return confirm (\”确定要删除此项记录吗?\”);”);
}
}
if(e.item.itemtype==listitemtype.item || e.item.itemtype==listitemtype.alternatingitem)//这是判断模板列中里添加的删除按钮(button,imagebutton也可以),弹出一个删除对话框
{
button button = (button) e.item.findcontrol(“btnadelete”);//这个事件在itemcommand事件中执行
//imagebutton button = (imagebutton) e.item.findcontrol(“imagebutton1”);
button.attributes.add (“onclick”,
“return confirm (\”确定要删除此项记录吗?\”);”);
}
}
private void dborders_deletecommand(object source, system.web.ui.webcontrols.datagridcommandeventargs e)
{
//写你的删除事件,下面是举例,具体根据自己的实际情况而定
int orderid=int.parse(dborders.datakeys[e.item.itemindex].tostring());//得到该行的对应的编号
// bool result=cdg.deleteorder(orderid);
// if(result)
// {
// response.write(“<script>alert(用户删除成功)</script>”);
// }
}
private void dborders_itemcommand(object source, system.web.ui.webcontrols.datagridcommandeventargs e)
{
int orderid=int.parse(dborders.datakeys[e.item.itemindex].tostring());//得到该行的对应的编号
if(e.commandname.equals(“delete”))//此属性为设置的控件的commandname,刚才设置的是delete,表示删除(其他也可以)
{
//写你的删除事件,下面是举例,具体根据自己的实际情况而定
//bool result=cdg.deleteorder(orderid);
// if(result)
// {
// response.write(“<script>alert(用户删除成功)</script>”);
// }
}
}
}
}