ASP建站十大常用程序代码完整篇

合集下载

常用ASP代码大全

常用ASP代码大全

常用ASP代码大全1.获得系统时间:<%=now()%>2. 取得来访用的IP:<%=request.serverVariables("remote_host")%>3.获得系统,浏览器版本:<script>window.document.write(" 版本:"+navigator.appName+navigator.appVersion+" browser.")</script>4.去除IE混动条:<body scroll="no"><body style="overflow-y:hidden">5.进入网站,跳出广告:<script language="javascript"><!--<!-- 注意更改文件所在路径-->window.open(''",'''',''height=200,width=300,top=0,left=30'');// --></script>6.随机数:<%randomize%><%=(int(rnd()*n)+1)%>N 为可改变数7.向上混动代码:<marquee direction="up" scrolldelay="200" style="font-size: 9pt; color: #FF0000;line-height: 150%; font-style:italic; font-weight:bold" scrollamount="2" width="206"height="207" bgcolor="#FFFF00">Unix中文站</marquee>8.自动关闭网页:<script LANGUAGE="javascript"><!--setTimeout(''window.close();'', 10000); //60秒后关闭// --> </script><p align="center">本页10秒后自动关闭,请注意刷新页面</p>9.随机背景音乐:<%randomize%><bgsoundsrc="/qz.q/mids/<%=(int(rnd()*60)+1)%>.mid"loop="-1"> 可以修改数字,限制调用个数,我这里是60个.10.自动刷新本页面:<script><!--var limit="0:10"if (document.images){var parselimit=limit.split(":")parselimit=parselimit[0]*60+parselimit[1]*1 }function beginrefresh(){if (!document.images)returnif (parselimit==1)window.location.reload()else{parselimit-=1curmin=Math.floor(parselimit/60)cursec=parselimit%60if (curmin!=0)curtime=curmin+"分"+cursec+"秒后重刷本页!"elsecurtime=cursec+" 秒后重刷本页!"window.status=curtimesetTimeout("beginrefresh()",1000) } }window.onload=beginrefreshfile://--></script>11.ACCESS数据库连接:<%option explicitdim startime,endtime,conn,connstr,dbstartime=timer()'更改数据库名字db="data/dvBBS5.mdb"Set conn = Server.CreateObject("ADODB.Connection")connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db)'如果你的服务器采用较老版本Access驱动,请用下面连接方法'connstr="driver={Microsoft Access Driver (*.mdb)};dbq=" & Server.MapPath(db)conn.Open connstrfunction CloseDatabaseConn.closeSet conn = NothingEnd Function %>12.SQL数据库连接:<%option explicitdim startime,endtime,conn,connstr,dbstartime=timer()connstr="driver={SQLServer};server=HUDENQ-N11T33NB;uid=sa;pwd=xsfeihu;database=dvbbs"Set conn = Server.CreateObject("ADODB.Connection")conn.Open connstrfunction CloseDatabaseConn.closeSet conn = NothingEnd Function%>13.用键盘打开网页代码:<script language="javascript">function ctlent(eventobject){ if((event.ctrlKey && window.event.keyCode==13)(event.altKey && window.event.keyCode==83)){ window.open('网址','','') } }</script>这里是Ctrl+Enter和Alt+S的代码自己查下键盘的ASCII码再换就行14.让层不被控件复盖代码:<div z-Index:2><object ***></object></div> #前面<div z-Index:1><object ***></object></div> #后面<div style="position:absolute; top:40;width:400px; height:95px;z-index:2"><table height=100% width=100% bgcolor="#ff0000"><tr><td height=100% width=100%></td></tr></table><iframe width=0 height=0></iframe></div><div style="position:absolute; top:50;width:200px; height:115px;z-index:1"><iframe height=100% width=100%></iframe></div>。

ASP.NET网站建设基本常用代码

ASP.NET网站建设基本常用代码

⽹站建设基本常⽤代码1.为按钮添加确认对话框Button.Attributes.Add("onclick","return confirm('确认?')");Button.Attributes.Add("onclick","if(confirm('确定?')){return true;}else{return false;}")2.表格超连接列传递参数<asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.aspx?id='<%# DataBinder.Eval(Container.DataItem, "数据字段1")%>'&name='<%# DataBinder.Eval(Container.DataItem, "数据字段2")%>'/>3.表格点击改变颜⾊if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem){e.Item.Attributes.Add("onclick","this.style.backgroundColor='#99cc00';this.style.color='buttontext';this.style.cursor='default';");}4.清空CookieCookie.Expires=[DateTime];Response.Cookies("UserName").Expires = 0;5.Panel 横向滚动,纵向⾃动扩展<asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>6.数字格式化<%#Container.DataItem("price")%> 结果:500.0000格式化:500.00<%#Container.DataItem("price","{0:¥#,##0.00}")%>int i=123456;string s=i.ToString("###,###.00");7.⽇期格式化<%# DataBinder.Eval(Container.DataItem,"Date")%> 结果:2004-8-11 19:44:28 格式化:2004-8-11<%# DataBinder.Eval(Container.DataItem,"Date","{0:yyyy-M-d}")%>8.时间格式化string aa=DateTime.Now.ToString("yyyy年MM⽉dd⽇");当前年⽉⽇时分秒 currentTime=System.DateTime.Now;当前年 int 年= DateTime.Now.Year;当前毫秒 int 毫秒= lisecond;9.⾃定义分页代码public static int pageCount; //总页⾯数public static int curPageIndex=1; //当前页⾯ if(ccDataGrid.CurrentPageIndex<(ccDataGrid.PageCount - 1)){//下⼀页 ccDataGrid.CurrentPageIndex += 1; curPageIndex+=1;}bind(); // ccDataGrid数据绑定函数if(ccDataGrid.CurrentPageIndex>0){ //上⼀页 ccDataGrid.CurrentPageIndex += 1; curPageIndex-=1;}bind(); // ccDataGrid数据绑定函数int a=int.Parse(JumpPage.Value.Trim());//JumpPage.Value.Trim()为跳转值if(a<DataGrid1.PageCount){ //直接页⾯跳转 DataGrid.CurrentPageIndex=a;}bind(); // ccDataGrid数据绑定函数10.变量.ToString()字符型转换转为字符串12345.ToString("n"); //⽣成 12,345.0012345.ToString("C"); //⽣成¥12,345.0012345.ToString("e"); //⽣成 1.234500e+00412345.ToString("f4"); //⽣成 12345.000012345.ToString("x"); //⽣成 3039 (16进制)12345.ToString("p"); //⽣成 1,234,500.00%11.客户端验证控件//验证空值<asp:requiredfieldvalidator id="valUsername" runat="server" controltovalidate="txtUsername" display="None" errormessage="请输⼊⽤户名 !!"></asp:requiredfieldvalidator>//验证⽹址<asp:regularexpressionvalidator id="rev" runat="server" ErrorMessage="公司⽹址不合法[要有http://] !" Display="None" ControlToValidate="txtCPWebsite" ValidationExpression="http://(["w-]+".)+["w-]+(/["w- ./?%&amp;=]*)?"></asp:regularexpressionvalidator>//验证邮箱<asp:RequiredFieldValidator id="rfv" runat="server" ControlToValidate="txtCPEmail" Display="None" ErrorMessage="请输⼊电⼦邮箱 !!"></asp:RequiredFieldValidator>//验证邮编<asp:regularexpressionvalidator id="rev5" runat="server" ErrorMessage="邮政编码不合法!" Display="None" ControlToValidate="txtCPPostCode" ValidationExpression=""d{6}"> </asp:regularexpressionvalidator>//显⽰错误信息<asp:validationsummary id="vs" runat="server" ShowSummary="False" ShowMessageBox="True"></asp:validationsummary>12.DataBinding绑定表达式1) 普通的绑定表达式<%# DataBinder.Eval(Container.DataItem, "ContactName") %>2) ⽂本+绑定表达式<asp:Label id=lblDate runat="server" Text='<%# "[" + DataBinder.Eval(Container, "DataItem.NewsCreatedate") + "]" %>' ForeColor="Red"></asp:Label>3) 同时带有显⽰格式的绑定表达式<%# DataBinder.Eval(Container,"ActiveDate","{0:yyyy-MM-dd}") %>4) 结合绑定表达式和模态框<A href='<%# ShowModalWin(Convert.ToString(DataBinder.Eval(Container.DataItem, "PictureImage")),Convert.ToString(DataBinder.Eval(Container.DataItem, "DetailID")),Convert.ToString(DataBinder.Eval(Container.DataItem, "PictureID")))%>'>其中:后台代码⽂件中ShowModalWin()⽅法的定义如下:protected string ShowModalWin(string PictureImage,string DetailID,string PictureID){return " window.showModalDialog(""Customers/ShowPictureInfo.aspx?pid="+PictureImage+"&did="+DetailID+"&id="+PictureID+""","""",""dialogHeight:320px;dialogWidth:480px;center:yes;help:no;status:no;scroll:no"");";}或者将参数提取出来单独定义成⼀变量:const string WINDOWPARAMSTRING="dialogWidth:540px;dialogHeight:420px;help:0;status:0;resizeable:1;scroll:no";Page.RegisterStartupScript("functionscript","<script language='javascript'>window.showModalDialog('EditUserService.aspx?URID="+iURID+"','','"+WINDOWPARAMSTRING+"') </script>");13.html字符转换的两个函数public string Encode(string str){str=str.Replace("&","&amp;");str=str.Replace("'","''");str=str.Replace("""","&quot;");str=str.Replace(" ","&nbsp;");str=str.Replace("<","&lt;");str=str.Replace(">","&gt;");str=str.Replace(""n","<br>");return str;}public string Decode(string str){str=str.Replace(""n","<br>");str=str.Replace("&gt;",">");str=str.Replace("&lt;","<");str=str.Replace("&nbsp;"," ");str=str.Replace("&quot;","""");return str;}14.产⽣62位内任意数字⼤⼩写字母的随机数private static char[] constant={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};public static string GenerateRandom(int Length){System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);Random rd= new Random();for(int i=0;i<Length;i++){newRandom.Append(constant[rd.Next(62)]);}return newRandom.ToString();}//调⽤string str=GenerateRandom(6);//参数表⽰需要产⽣随机数的数⽬15.图像加⼊版权信息using System.Drawing;using System.IO;using System.Drawing.Imaging;private void AddTextToImg(string fileName,string text){if(!File.Exists(MapPath(fileName))){throw new FileNotFoundException("The file don't exist!");}if( text == string.Empty ){return;}//还需要判断⽂件类型是否为图像类型System.Drawing.Image image = System.Drawing.Image.FromFile(MapPath(fileName));Bitmap bitmap = new Bitmap(image,image.Width,image.Height);Graphics g = Graphics.FromImage(bitmap);float fontSize = 12.0f; //字体⼤⼩float textWidth = text.Length*fontSize; //⽂本的长度//下⾯定义⼀个矩形区域,以后在这个矩形⾥画上⽩底⿊字float rectX = 0;float rectY = 0;float rectWidth = text.Length*(fontSize+8);float rectHeight = fontSize+8;//声明矩形域RectangleF textArea = new RectangleF(rectX,rectY,rectWidth,rectHeight);Font font = new Font("宋体",fontSize); //定义字体Brush whiteBrush = new SolidBrush(Color.White); //⽩笔刷,画⽂字⽤Brush blackBrush = new SolidBrush(Color.Black); //⿊笔刷,画背景⽤g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight);g.DrawString(text,font,whiteBrush,textArea);MemoryStream ms = new MemoryStream( );//保存为Jpg类型bitmap.Save(ms,ImageFormat.Jpeg);//输出处理后的图像,这⾥为了演⽰⽅便,我将图⽚显⽰在页⾯中了Response.Clear();Response.ContentType = "image/jpeg";Response.BinaryWrite( ms.ToArray() );g.Dispose();bitmap.Dispose();image.Dispose();}//调⽤AddTextToImg("me.jpg","Family.Man");16.常⽤正则表达式集锦"^""d+$" //⾮负整数(正整数 + 0)"^[0-9]*[1-9][0-9]*$" //正整数"^((-""d+)|(0+))$" //⾮正整数(负整数 + 0)"^-[0-9]*[1-9][0-9]*$" //负整数"^-?""d+$" //整数"^""d+("".""d+)?$" //⾮负浮点数(正浮点数 + 0)"^(([0-9]+"".[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*"".[0-9]+)|([0-9]*[1-9][0-9]*))$" //正浮点数"^((-""d+("".""d+)?)|(0+("".0+)?))$" //⾮正浮点数(负浮点数 + 0)"^(-(([0-9]+"".[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*"".[0-9]+)|([0-9]*[1-9][0-9]*)))$" //负浮点数"^(-?""d+)("".""d+)?$" //浮点数"^[A-Za-z]+$" //由26个英⽂字母组成的字符串"^[A-Z]+$" //由26个英⽂字母的⼤写组成的字符串"^[a-z]+$" //由26个英⽂字母的⼩写组成的字符串"^[A-Za-z0-9]+$" //由数字和26个英⽂字母组成的字符串"^""w+$" //由数字、26个英⽂字母或者下划线组成的字符串"^[""w-]+("".[""w-]+)*@[""w-]+("".[""w-]+)+$" //email地址"^[a-zA-z]+://(""w+(-""w+)*)("".(""w+(-""w+)*))*(""?""S*)?$" //url17.绑定在DataList中的DropDownListprivate void dlistOrder_EditCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e){//绑定订单状态for(int i=0;i<((DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlFlag")).Items.Count;i++){if(((DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlFlag")).Items[i].Value == dv.Table.Rows[0]["OrStatus"].ToString()) {((DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlFlag")).Items[i].Selected = true;}}}//另⼀种绑定⽅式,绑定送货⽅式DataView shipType = OrderSO.GetShipTypeList();DropDownList ddlShipType = (DropDownList)dlistOrder.Items[e.Item.ItemIndex].FindControl("ddlShipType");ddlShipType.DataSource = shipType;ddlShipType.DataTextField = "StName";ddlShipType.DataValueField = "StId";ddlShipType.DataBind();ddlShipType.SelectedIndex = ddlShipType.Items.IndexOf(ddlShipType.Items.FindByValue(dv.Table.Rows[0]["OrShipType"].ToString()));18.验证⽤户名必须以字母打头且不能含有中⽂String sUsername = txtUsername.Text.Trim();if(!Regex.IsMatch(sUsername, "^[A-Za-z].*")){Utility.MessageBox(this,"nameFormatError","⽤户名要以字母开头, 且不要⽤中⽂名称 !!");return;}。

asp 代码 大全

asp 代码 大全

asp代码大全[ 2006-5-5 22:37:49 ]以下代码由stone编写,如果转载请注明出处和作者,谢谢合作!(/)代码还有不足之处,请各位指出共同研究!所有代码的原文件下载:/uploadfile/2006-5/55682958.rar--------------------------------------------1,连接数据库代码文件名称conn.asp 所有访问数据库的文件都调用此文件<!--#i nclude file="Conn.as p"-->---------------------------------------------- 2。

增加纪录--------------------------------------3.显示记录page=1end ifn=rs.pagecountif page>n thenpage=clng(n)end ifif rs.eof thenresponse.write"<font color=#FF0000>暂没有信息!</font>"'response.endelsers.absolutepage=pageend ifi=0do while not rs.eof and i<rs.pagesize'do while not rs.eof%>--------如果是每行显示n个纪录开始----------------------------<%do while not rs.eof and i<rs.pagesize'do while not rs.eofif i mod 5=0 then '--------设置每行显示的个数response.write "<tr>"end if%>--------如果是每行显示n个纪录结束-----------------------------<%=rs("id")%><% rs.movenexti=i+1loop%><%response.write("共"&rs.recordcount&"条信息&nbsp;&nbsp;&nbsp;")if page<>1 thenresponse.write("<a href="/stblog/?page=1" title='首页'>首页</a>&nbsp;")elseresponse.write("首页&nbsp;")end ifif page>1 thenresponse.write("<a href="/stblog/?page=""&page-1&" title='上一页'>上一页</a>&nbsp;")----------------------------------------------4。

asp常用代码集锦

asp常用代码集锦

ASP中常用代码Cookie的用法://Cookie的用法HttpCookie cookie = new HttpCookie("first"); //第一个Cookie cookie.Expires = DateTime.Now.AddDays(30); //设置Cookie的消失时间,时间为30天cookie.Values["name"] = "lsc"; //设置Cookie的值//name <-->lsc为键值对cookie.Values["password"] = "12345";Response.Cookies.Add(cookie); //将指定的Cookie保存到本机//获取Cookie的值HttpCookie c = (HttpCookie)Request.Cookies["first"];Response.Write(c.Values["name"] + "<br/>");Response.Write(c.Values["password"]);Application 的用法:写在Gloal.asaxvoidApplication_Start(object sender, EventArgs e){// Code that runs on application startup//服务器启动时运行的代码//关于计数器的使用//在此初始化计数器Application["count"] = 0; //当服务器启动时调用,该网站访问数为0开始}写在页面端protected void Page_Load(object sender, EventArgs e) {try{//取出application中的值|Application.Lock();int count = (int)Application["count"];count++;Application["count"] = count; //将此返回服务?器Response.Write("你是第+Application["count"] + "位访客¨a");Application.UnLock();}catch (Exception ex){Response.Write(“<script>alert(“+ex.Message+”)</script>”); }}如果写在页面端,则用户刷新一次,访问人数就增加voidSession_Start(object sender, EventArgs e){// Code that runs when a new session is started//在新会话启动时运行的代码//取出application中的值Application.Lock();int count = (int)Application["count"];count++;Application["count"] = count; //将此返回服务器Response.Write("你是第" + Application["count"] + "位访客");Application.UnLock();}将此写在Global.asax中使得页面只有通过重新访问,访问数才能增加,否则不能增加Lock()和UnLock()的意义是必须是一个加完后,另外一个在加Response的用法:Response用于向页面输出内容和实现页面的重定向Response.Write();Resposne.Redirect("网址")Response.Cookies.Add(); 用于添加CookieRequest的用法:Request用于获取表单的值String name=request.queryString["name"];String name=request.from["name"];String name=request.params["name"]; --最常用的一种方法String name=request["name"];Session的用法:(Session中可以传递各种数据类型的数据也可以传递类)Session用于在各个页面之间传递数据首先是将值存放在Session中:Session["name"] = name;Session["password"] = password;然后获取值:string name = (string)Session["name"];string password = (string)Session["password"];###在实际工作中,Session传递的值一般是一个封装类JavaScript中页面自动跳转的方法:将其添加在中即可实现中的自动跳转<SCRIPT LANGUAGE="JavaScript"><!--function redirect() { //跳转页window.location = "Default.aspx";}timer = setTimeout('redirect()', 5 * 1000); //跳转//--></SCRIPT>在中设置密码框即在TextBox中添加TextMode="password" ---利用中自身的TextBox设置密码框添加TextMode属性关于DropDownList的数据绑定:首先在DropDownList中的事件SelectedIndexChanged中添加:this.Image1.ImageUrl = "img/" + this.DropDownList1.SelectedValue.ToString();1、利用图形界面进行数据绑定,详见数据绑定视频2、利用ArrayList容器进行数据绑定,但是只能是5条一下的数据if (!IsPostBack){ArrayList list = new ArrayList();list.Add("1.jpg");list.Add("2.jpg");list.Add("3.jpg");this.DropDownList1.DataSource = list; //指定数据源this.DropDownList1.DataBind();}3、利用数据库操作进行动态的数据绑定(较为正规的用法)//利用数据库操作进行动态数据绑定if (!IsPostBack){stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=mldn;Uid=china;Pwd=1 2345678";SqlConnectionsqlConn = new SqlConnection(strConn);sqlConn.Open();SqlCommandcmd = new SqlCommand();mandText = "select * from Images";cmd.Connection =sqlConn;SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);this.DropDownList1.DataSource = dt;this.DropDownList1.DataTextField = "imgs"; //添加显示给用户的数据this.DropDownList1.DataValueField = "imgs"; //添加传递给服务器的数据this.DropDownList1.DataBind();}在中利用onClientClick()事件调用JavaScript代码而不用onClick()事件在代码后面添加return false 阻止后面的代码执行在判断姓名文本框、密码框等不能为空的判断时,避免没有添加页面仍然跳转则在每一个判断后面添加一上return false,同时在onClientClick()中添加return javaScript方法CheckBoxList的用法:int count = this.CheckBoxList1.Items.Count;for (int index = 0; index <= count; index++){if (this.CheckBoxList1.Items[index].Selected){Response.Write(this.CheckBoxList1.Items[index].Text);}}RadioButtonList的用法:for (int index = 0; index < this.RadioButtonList1.Items.Count; index++){if (this.RadioButtonList1.Items[index].Selected){Response.Write(this.RadioButtonList1.Items[index].Text);}}Data中的Repeater的用法:主要用于分页首先拖动一个Reoeater控件,然后配置数据源在切换到代码视图,添加相应的模板,其中()模板如下:<HeaderTemplate></HeaderTemplate><ItemTemplate></ItemTemplate> --必写<FooterTemplate></FooterTemplate><AlternatingTemplate></AlternatingTeplate> --隔行显示模板,实现隔行的显示方式对应实例:<form id="form1" runat="server"><div><asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"><HeaderTemplate><table border="1"><tr><td width="100">图片</td><td width="100">值</td></tr></table></HeaderTemplate><ItemTemplate><table border="1"><tr style=" color:Green"><td width="100"><%# Eval("imgs") %></td><td width="100"><%# Eval("imgsValue")%></td></tr></table></ItemTemplate><AlternatingItemTemplate><table border="1"><tr style=" color:Red"><td width="100"><%# Eval("imgs") %></td><td width="100"><%# Eval("imgsValue") %></td></tr></table></AlternatingItemTemplate><FooterTemplate><table border="1"><tr><td colspan="2">这是一个测试程序!!</td></tr></table></FooterTemplate></asp:Repeater><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:mldnConnectionString %>" SelectCommand="SELECT * FROM [Images]"></asp:SqlDataSource><br /><br /><br /><br /></div></form>ASP中的分页:真分页和假分页假分页:using System;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Data;usingSystem.Data.SqlClient;public partial class page : System.Web.UI.Page{privateintpageNumber = 0;privateintlineCount;public void pages(){stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select * from fangyuan";SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);PagedDataSourcepds = new PagedDataSource();pds.DataSource = dt.DefaultView;pds.AllowPaging = true; //是否允许分页pds.PageSize = 2; //指定每页显示多少条数据pds.CurrentPageIndex = pageNumber; //指定显示的页码,用该变量控制翻页this.Repeater1.DataSource = pds;this.Repeater1.DataBind();conn.Close();}protected void Page_Load(object sender, EventArgs e){this.pages();stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select count(*) from fangyuan";object o = cmd.ExecuteScalar();lineCount = Convert.ToInt32(o);}protected void LinkButton1_Click(object sender, EventArgs e){try{pageNumber = 0;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton2_Click(object sender, EventArgs e){try{if (pageNumber< 0){Response.Write("不能再向上翻页了!");}else{pageNumber -= 1;this.pages();}}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton3_Click(object sender, EventArgs e) {try{pageNumber = 0;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton4_Click(object sender, EventArgs e) {try{pageNumber = 1;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton5_Click(object sender, EventArgs e) {try{pageNumber = 2;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton7_Click(object sender, EventArgs e) {try{if (pageNumber == (lineCount - 1)){Response.Write("不能再向下翻页了!");}else{pageNumber += 1;this.pages();}}catch (Exception ex){Response.Write(ex.Message);}}protected void LinkButton8_Click(object sender, EventArgs e) {try{pageNumber = lineCount - 1;this.pages();}catch (Exception ex){Response.Write(ex.Message);}}}DataList的用法:(绑定数据的方式与Repeater相同)与Repeater相比较,DataList的功能更强大,可以实现删除,具体用法如下:DataList绑定数据的两种方式:1、利用图形化界面对数据进行绑定2、动态的对数据进行绑定stringstrConn = "server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "select * from fangyuan";SqlDataAdaptersda = new SqlDataAdapter(cmd);DataTabledt = new DataTable();sda.Fill(dt);this.DataList1.DataSource = dt;this.DataList1.DataKeyField = "bianhao"; //指定以何种字段为标准 ---关键this.DataList1.DataBind();conn.Close();删除方法:string bianhao = this.DataList1.DataKeys[e.Item.ItemIndex].ToString(); //用于获取对应的编号 ----关键stringstrConn ="server=LSC-BD9E16FDC63\\SQLEXPRESS;database=build;Pwd=12345678;Uid=china";SqlConnection conn = new SqlConnection(strConn);conn.Open();SqlCommandcmd = new SqlCommand();cmd.Connection = conn;mandText = "delete from fangyuan where bianhao='" + bianhao + "'";cmd.ExecuteNonQuery();conn.Close();每删除一次后对数据进行重新绑定,实现更新DXControls外部控件的使用:在使用DXControls时注册代码(放在<% @page 的下面)<%@ Register Assembly="DXControls" Namespace="DXControls" TagPrefix="cc1" %>在复制<cc1:dxtb id="concentdx" runat="server" height="100px" width="450px"></cc1:dxtb>该段代码到.aspx文件中在使用该控件时,必须在工程中导入Bin文件夹,同时该文件夹中必须存在DXControls.dll文件,还应导入dxtb文件夹,里面包含有相应的文件中验证控件的使用1、RequiredFieldValidator必填项验证,如网络上的*为必填项的实现必须对两个属性进行更改:ControlToValidate指定对哪个控件进行验证ErrorMessage当输入错误时显示的错误信息2、RegularExpressionValidator正则表达式验证,如对密码、邮箱等的验证必须对三个属性进行更改:ControlToValidate指定对哪个控件进行验证ErrorMessage当输入错误时显示的错误信息ValidationExpression写出对应的正则表达式3、RangeValidator数字界限验证,如3-100常见的正则表达式的匹配字符串:\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 为匹配邮箱地址防止用户未登录就访问页面的代码:<%If(Session(“name”) == null){Response.Redirect(“Login.aspx”);}%>通过Seesion在用户登录时存值,再每一个页面都判断是否存在Session传递的值,已判断用户是否登录,通常传递类Linq的使用:查询操作://读取配置文件tStudentDataClassesDataContext context =new StudentDataClassesDataContext();//取出数据表中的所有内容System.Data.Linq.Table<student> list = context.GetTable<student>();//按照需求查询var query = from student in list select student;//或者语句的使用var query = from Person in context.Persons where Person.id == 1 || =="lsc" select Person;foreach(var student in query){Response.Write(+"<br />");}删除操作:(先查找再删除)PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();var delete = from Person in context.Persons where Person.id==1 select Person; foreach (var Person in delete){//删除操作context.Persons.DeleteOnSubmit(Person);}context.SubmitChanges(); //提交操作Response.Write("删除成功");添加数据操作:PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();Person p = new Person();p.id = 1; = "flq";p.password = "flq";context.Persons.InsertOnSubmit(p);//添加数据context.SubmitChanges(); //提交操作修改数据操作:PersonDataClassesDataContext context =new PersonDataClassesDataContext();System.Data.Linq.Table<Person> list = context.GetTable<Person>();var update = from Person in context.Persons where Person.id==4 select Person; foreach (var P in update){ = "wms";P.password = "wms";}context.SubmitChanges();利用Linq遍历数组:利用Linq对容器进行操作:如何利用Linq进行降序排列:以“c”结尾长度不大于5的人名。

ASP的三十二条精华代码

ASP的三十二条精华代码

ASP的三十二条精华代码1.onconte某tmenu="window.event.returnvalue=fale"将彻底屏蔽鼠标右键<tableborderonconte某tmenu=return(fale)><td>no</table>可用于Table2.<bodyonelecttart="returnfale">取消选取、防止复制3.onpate="returnfale"不准粘贴4.oncopy="returnfale;"oncut="returnfale;"防止复制5.<linkrel="ShortcutIcon"href="favicon.ico">IE地址栏前换成自己的图标不但大的ISP,ICP这么做,一些个人主页也推出这一"服务"以招揽网友,具体是如何实现这个功能的呢?我来帮你剖析一下:别怕,我们来打开lpace.reg看看(用最普通的notepad记事本就可以打开),发现内容如下:REGEDIT4[HKEY_CURRENT_USER\Software\Microoft\InternetE某plorer\Main] "StartPage"="/";;[HKEY_CURRENT_USER\Software\Netcape\NetcapeNavigator\Main]"H omePage"="/";;原来就两条,第一条设置IE的tarpage;第二条设置NC的homepage(没什么花头噢:)。

后面跟的URL就是你主页的网址!7.<inputtyle="ime-modeiabled">关闭输入法8.永远都会带着框架<criptlanguage="某某某某"><!--if(window==top)top.location.href="frame.htm";//frame.htm为框架网页//--></cript>9.防止被人frame<criptLANGUAGE=某某某某><!--if(top.location!=elf.location)top.location=elf.location;//--></cript>10.<nocript><iframerc=某.html></iframe></nocript>网页将不能被另存为11.<inputtype=buttonvalue=查看网页源代码onclick="window.location=''view-ource:''+''/&#39;'">12.怎样通过ap的手段来检查来访者是否用了代理<%ifRequet.ServerVariable("HTTP_某_FORWARDED_FOR")<>""then repone.write"<fontcolor=#FF0000>您通过了代理服务器,"&_"真实的IP为"&Requet.ServerVariable("HTTP_某_FORWARDED_FOR") endif%>13.取得控件的绝对位置//某某某某<criptlanguage="某某某某">functiongetIE(e){vart=e.offetTop;varl=e.offetLeft;while(e=e.offetParent){t+=e.offetTop;l+=e.offetLeft;}alert("top="+t+"\nleft="+l);}</cript>//VBcript<criptlanguage="VBcript"><!--functiongetIE()dimt,l,a,beta=document.all.img1t=document.all.img1.offetTopl=document.all.img1.offetLeftwhilea.tagName<>"BODY"eta=a.offetParentt=t+a.offetTopl=l+a.offetLeftwendmgbo某"top="&t&chr(13)&"left="&l,64,"得到控件的位置" endfunction--></cript>14.光标是停在文本框文字的最后<criptlanguage="某某某某">functioncc(){vare=event.rcElement;varr=e.createTe某tRange();r.moveStart(''character'',e.value.length);r.collape(true);r.elect();}</cript><inputtype=te某tname=te某t1value="123"onfocu="cc()"> ap:requet.ervervariable("HTTP_REFERER")某某某某:document.referrer16.最小化、最大化、关闭窗口<objectid=hh1claid="clid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"><objectid=hh2claid="clid:ADB880A6-D8FF-11CF-9377-00AA003B7A11"><OBJECTid=hh3claid="clid:adb880a6-d8ff-11cf-9377-00aa003b7a11"><inputtype=buttonvalue=最小化onclick=hh1.Click()><inputtype=buttonvalue=最大化onclick=hh2.Click()><inputtype=buttonvalue=关闭onclick=hh3.Click()>本例适用于IE17.<%''定义数据库连接的一些常量ContadOpenForwardOnly=0''游标只向前浏览记录,不支持分页、Recordet、BookMarkContadOpenKeyet=1''键集游标,其他用户对记录说做的修改将反映到记录集中,但其他用户增加或删除记录不会反映到记录集中。

ASP类代码参考

ASP类代码参考

ASP类代码参考关于ASP模板类代码参考Class TemplatePrivate m_FileName, m_Root, m_Unknowns, m_LastError, m_HaltOnErrPrivate m_ValueList, m_BlockListPrivate m_RegExpPrivate Sub Class_InitializeSet m_ValueList = CreateObject("Scripting.Dictionary")Set m_BlockList = CreateObject("Scripting.Dictionary")set m_RegExp = New RegExpm_RegExp.IgnoreCase = Truem_RegExp.Global = Truem_FileName = ""m_Root = "."m_Unknowns = "remove"m_LastError = ""m_HaltOnErr = trueEnd SubPrivate Sub Class_T erminateSet m_RegExp = NothingSet m_BlockMatches = NothingSet m_ValueMatches = nothingEnd SubPublic Property Get ClassName()ClassName = "Template"End PropertyPublic Property Get Version()Version = "1.0"End PropertyPrivate Function LoadFile(ByVal chartype)Dim Filename, fso, hndFileFilename = m_RootIf Right(Filename, 1)<>"/" And Right(Filename, 1)<>"" Then Filename = Filename & "/"Filename = Server.MapPath(Filename & m_FileName)Set StreamObject = Server.CreateObject("Adodb.Stream")StreamObject.Type = 1StreamObject.Mode = 3StreamObject.OpenStreamObject.Position = 0StreamObject.LoadFromFile FilenameStreamObject.Position = 0StreamObject.Type = 2StreamObject.CharSet = chartypeLoadFile = StreamObject.readtext()If LoadFile = "" Then ShowError("0x11Could Not Load The File " & m_FileName & "!")End FunctionPrivate Sub ShowError(ByVal msg)m_LastError = msgResponse.Write "Error ID : " & msg & ""If m_HaltOnErr Then Response.EndEnd SubPublic Sub set_root(ByVal Value)m_Root = ValueEnd SubPublic Function get_root()get_root = m_RootEnd FunctionPublic Property Let Root(ByVal Value)set_root(Value)End PropertyPublic Property Get Root()Root = m_RootEnd PropertyPublic Sub set_file(ByVal handle,ByVal filename,ByVal chartype)m_FileName = filenamem_BlockList.Add Handle, LoadFile(chartype)End SubPublic Function get_file()get_file = m_FileNameEnd FunctionPublic Sub set_unknowns(ByVal unknowns)m_Unknowns = unknownsEnd SubPublic Function get_unknowns()get_unknowns = m_UnknownsEnd FunctionPublic Property Let Unknowns(ByVal unknown)m_Unknowns = unknownEnd PropertyPublic Property Get Unknowns()Unknowns = m_UnknownsEnd PropertyPublic Sub set_block(ByVal Parent, ByVal BlockTag, ByVal Name)Dim Matchesm_RegExp.Pattern = "([sS.]*)"If Not m_BlockList.Exists(Parent) Then ShowError("0x12Undefined Block T ag " & Parent & "!")set Matches = m_RegExp.Execute(m_BlockList.Item(Parent)) For Each Match In Matchesm_BlockList.Add BlockTag, Match.SubMatches(0)m_BlockList.Item(Parent) = Replace(m_BlockList.Item(Parent), Match.Value, "{" & Name & "}")Nextset Matches = nothingEnd SubPublic Sub set_var(ByVal Name, ByVal Value, ByVal AppEnd) Dim ValIf IsNull(Value) Then Val = "" Else Val = ValueIf m_ValueList.Exists(Name) ThenIf AppEnd Then m_ValueList.Item(Name) = m_ValueList.Item(Name) & Val _Else m_ValueList.Item(Name) = ValElsem_ValueList.Add Name, ValueEnd IfEnd SubPublic Sub unset_var(ByVal Name)If m_ValueList.Exists(Name) Then m_ValueList.Remove(Name) End SubPrivate Function InstanceValue(ByVal BlockTag)Dim keys, iInstanceValue = m_BlockList.Item(BlockTag)keys = m_ValueList.KeysFor i=0 To m_ValueList.Count-1InstanceValue = Replace(InstanceValue, "{" & keys(i) & "}", m_ValueList.Item(keys(i)))NextEnd FunctionPublic Sub parse(ByVal Name, ByVal BlockTag, ByVal AppEnd) If Not m_BlockList.Exists(BlockTag) Then ShowError("0x12Undefined Block T ag " & Parent & "!")If m_ValueList.Exists(Name) ThenIf AppEnd Then m_ValueList.Item(Name) = m_ValueList.Item(Name) & InstanceValue(BlockTag) _ Else m_ValueList.Item(Name) = InstanceValue(BlockTag)Elsem_ValueList.Add Name, InstanceValue(BlockTag)End IfEnd SubPrivate Function finish(ByVal content)Select Case m_UnknownsCase "keep" finish = contentCase "remove"m_RegExp.Pattern = "{[^ trn}]+}"finish = m_RegExp.Replace(content, "")Case "comment"m_RegExp.Pattern = "{([^ trn}]+)}"finish = m_RegExp.Replace(content, "")Case Else finish = contentEnd SelectEnd FunctionPublic Sub output(ByVal Name)If Not m_ValueList.Exists(Name) Then ShowError("0x13Could Not Find Tag " & Name & "!")Response.Write(finish(m_ValueList.Item(Name))) End SubEnd Class。

ASP建站十大常用程序代码完整篇

ASP建站十大常用程序代码完整篇

这个教程我要分10篇给大家来做分析,这十大常用程序都包括什么呢?下面我给大家列出大纲工参考:第一节:注册系统注册几乎是每个网站都要使用的,去论坛要注册,聊天要注册,几乎无处不注册,所以注册是所有ASP应用程序中最常见的。

第二节:留言薄互联网最大的特点是互动性,让网友在留言薄上留下自己的意见能使网站的人气值上升不少。

第三节:调查系统利用网络进行一些调查是非常常见的,轻轻一点投下自己一票,因此有一个调查系统能为网站增色不少。

第四节:购物车购物车这个名字取自超级市场的购物推车,不过这个小小的推车却是每个购物网站必备的。

第五节:计数器在浏览网页的时侯,常常可以看见一些“当前网站上的人数是xxxx人”的在线人数统计。

第六节:论坛系统论坛可以说是网站中最受网友欢迎的地方,网友可以在这里自由的发表自己的意见,网站人气的高低很大程度上由论坛决定,因此为我们的网站增加一个论坛是必须的。

第七节:聊天室当你独自在Internet上浏览时,你并不是一个孤单的“旅人”,因为每时每刻总有成千上万的人同时在网上浏览,你可以同他们聊聊天,交谈几句,让自己体验一下“网”内存知己、天涯若比邻的感觉第八节:EMail当你独自在Internet上浏览时,你并不是一个孤单的“旅人”,因为每时每刻总有成千上万的人同时在网上浏览,你可以同他们聊聊天,交谈几句,让自己体验一下“网”内存知己、天涯若比邻的感觉。

第九节:搜索系统一个大型网站内容众多,来访者往往很难找到自己所需要的东西,这时候就需要一个站内搜索来帮助来访者更快的找到索要的资料,所以搜索系统是一个大型网站必备系统。

第十节:分页程序从程序上说分页只是一种小技巧,但确实却是一个非常重要的小技巧,好,少说废话,我们开始吧。

好了以上是我要给大家分别讲解的教程.欢迎大家及时收藏和支持这里先给大家讲解第一节:注册系统(一),设定注册页面的外观:在这个例子中涉及了五个页面,其中有三幅是一般的htm文件,另外的两幅是asp文件,在这里制作利用的工具是frontpage98,但是大部分的asp代码还是要自己输入的:1,设定原来已经注册的用户进入的外观:在这里设置了两个文本框,一个超级链接和两个按钮。

常用的ASP代码

常用的ASP代码

常用的ASP代码一、取得用户通过超连接发来的数据(http://localhost/lx1.asp?a=133)或用get方法发来的表单数据。

<%abc=request.queryString("a")%>二、取得以post方法发送来的表单数据<%abc=request.form("a")%>三、不管用什么方式发送来的数据,都可以用以下方法取得数据<%abc=request("a")%>四、创建并打开与数据库的连接<%set cn=server.createObject("adodb.connection") cn.connectionString="provider=microsoft.jet.oledb.4.0; data source=" &server.mappath("ddd\用户.mdb")cn.open%>五、对数据执行查询并返回一个记录集,假设数据库连接是cn<%'先创建一个取得数据的SQL查询abc=request.queryString("a") '取得查询的条件chaxunyuju="select * from 基本信息表 where 用户名='" & abc & "'" '加上条件构建了一个查询set jiluji=cn.execute(chaxunyuju) '执行查询并返回记录集%>六、判断一个记录集有没有记录,假充记录集对象是jiluji(看是不是jiluji.bof=true 且jiluji.eof=true)<%if jiluji.bof and jiluji.eof then'无记录情况的处理response.write "没有记录!"else'有记录情况的处理response.write jiluji("用户名")end if%>七、增:追加一条记录的方法,假设数据库连接是cn,且已进行了存在与否的查询<%if jiluji.bof and jiluji.eof then '判断存在与否'先创建一个追加数据的SQL查询abc=request.queryString("a") '取得要追加的数据cde=request.querystring("b") '取得要追加的数据chaxunyuju="insert into 基本信息表(用户名,密码) values('" & abc & "','" & cde& "')" '加上数据构建了一个追加查询cn.execute chaxunyuju '执行查询elseresponse.write "记录已存在!"end if%>八、显:显示记录的方法,假设数据库连接是cn,获得的记录集是jiluji<%do while not jiluji.eof%>'输出每一条记录<%=jiluji("用户名")%><%=jiluji("密码")%><%=jiluji("等级")%><%jiluji.moveNext%>'每输出一条记录,就下移一行<%loop%>九、改:更新记录的方法,假设数据库连接是cn<%if jiluji.bof and jiluji.eof then '判断存在与否response.write "记录不存在!"else'先创建一个更新数据的SQL查询abc=request.queryString("a") '取得要追加的数据cde=request.querystring("b") '取得要追加的数据chaxunyuju="update 基本信息表 set 用户名='" & abc & "',密码='" & cde & "'" '加上数据构建了一个追加查询cn.execute chaxunyuju '执行查询end if%>十、删:删除记录,假设数据库是cn<%abc=request.queryString("a") '先获得要删除的记录的关键词 chaxunyuju="delete from 基本信息表 where 用户名='" & abc & "'"cn.execute chaxunyuju%>十一、要及时关闭记录集和数据库(用完以后要关闭)<%jiluji.closeset jiluji=nothingcn.closeset cn=nothing%>。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

这个教程我要分10篇给大家来做分析,这十大常用程序都包括什么呢?下面我给大家列出大纲工参考:第一节:注册系统注册几乎是每个网站都要使用的,去论坛要注册,聊天要注册,几乎无处不注册,所以注册是所有ASP应用程序中最常见的。

第二节:留言薄互联网最大的特点是互动性,让网友在留言薄上留下自己的意见能使网站的人气值上升不少。

第三节:调查系统利用网络进行一些调查是非常常见的,轻轻一点投下自己一票,因此有一个调查系统能为网站增色不少。

第四节:购物车购物车这个名字取自超级市场的购物推车,不过这个小小的推车却是每个购物网站必备的。

第五节:计数器在浏览网页的时侯,常常可以看见一些“当前网站上的人数是xxxx人”的在线人数统计。

第六节:论坛系统论坛可以说是网站中最受网友欢迎的地方,网友可以在这里自由的发表自己的意见,网站人气的高低很大程度上由论坛决定,因此为我们的网站增加一个论坛是必须的。

第七节:聊天室当你独自在Internet上浏览时,你并不是一个孤单的“旅人”,因为每时每刻总有成千上万的人同时在网上浏览,你可以同他们聊聊天,交谈几句,让自己体验一下“网”内存知己、天涯若比邻的感觉第八节:EMail当你独自在Internet上浏览时,你并不是一个孤单的“旅人”,因为每时每刻总有成千上万的人同时在网上浏览,你可以同他们聊聊天,交谈几句,让自己体验一下“网”内存知己、天涯若比邻的感觉。

第九节:搜索系统一个大型网站内容众多,来访者往往很难找到自己所需要的东西,这时候就需要一个站内搜索来帮助来访者更快的找到索要的资料,所以搜索系统是一个大型网站必备系统。

第十节:分页程序从程序上说分页只是一种小技巧,但确实却是一个非常重要的小技巧,好,少说废话,我们开始吧。

好了以上是我要给大家分别讲解的教程.欢迎大家及时收藏和支持这里先给大家讲解第一节:注册系统(一),设定注册页面的外观:在这个例子中涉及了五个页面,其中有三幅是一般的htm文件,另外的两幅是asp文件,在这里制作利用的工具是frontpage98,但是大部分的asp代码还是要自己输入的:1,设定原来已经注册的用户进入的外观:在这里设置了两个文本框,一个超级链接和两个按钮。

两个文本框分别用来输入帐号(txtNum)和密码(txtPasswd),超级链接(New)链接到新用户进行注册的页面,两个按钮是用来提交和清除的,用来清除的按钮(cmdReset)直接选择为Reset类型,不过用来提交的按钮(cmdTijiao)并不要选择为Submit类型,而选择的是Normal类型,这是为了在这个按钮的onClick事件中添加代码,并且判断用户的输入是否合法!2,设定新用户登陆的页面外观:一般都是要新用户输入帐号,密码,姓名,及相关的一些信息,在这里我们有五个文本框,一个下拉式列表框和两个按钮,五个文本框就分别是让用户输入姓名,email,帐号,密码,确定密码。

但是其中只有用来输入帐号,密码和确定密码的文本框有名字,分别为txtNum,txtPasswd和txtConfirm。

提交按钮的名字为cmdTijiao3,这一步当然是设定注册成功后用户所进的页面了,这就由大家决定吧:)(二),添加程序代码:1,首先添加原来已经注册用户页面的代码,它主要是处理cmdTijiao_onClick事件,并且判断用户的输入是否合法,在这个例子中要求帐号必须是数字,密码不能为空,代码如下,其中frmRes是这个页面中窗口的名字,窗口的Action指向http://your/ResJudge.aspsub cmdTijiao_onClick()if frmRes.txtNum.value="" or frmRes.txtPasswd.value="" or (Not IsNumeric(frmRes.txtNum.value)) thenAlert"请在帐号和密码中输入相应的内容,帐号必须为数字!"else frmRes.submitend ifend sub2,添加新用户登陆的页面代码,这些代码是用来处理cmdTijiao_onClick事件的,要求用户输入的帐号必须是数字,密码和确定密码必须相同,这个页面的窗口的Action指向http://your/NewRes.asp,代码如下sub cmdTijiao_onClick()if Not Numeric(frmNew.txtNum.value) or frmNew.txtPasswd.value<>frmNew.txtConfirm.value thenAlert"输入不正确,请重新输入!"else frmNew.submitend ifend sub3,创建ResJudge.asp文件,这个asp文件的主要功能就是打开存储注册信息的数据库,查找是否有与前面页面提交的帐号和密码相匹配的纪录,如果有,就是注册成功,同时也可以在数据库中查找出这个用户的相关信息来,应允许这个用户进入他所希望进去的页面,如果没有则注册失败,整个代码如下<html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><meta name="GENERATOR" content="Microsoft Fronpage 3.0"><titile>注册判断</title></head><body><%Num=Request.form("txtNum") "把前面窗口传送来的内容赋给Num和Passwd两个字符串。

Passwd=Request.form("txtPasswd")dbname="Driver={Microsoft Access Driver(*.mdb)};DBQ="&Server.MapPath("\")"&"\ResDb\Res.mdb;" "dbname是打开数据库要用的set Cres=Server.CreateObject("ADODB.Connection") "以下是利用Connection对像和Recordset对象联结数据库并查找的代码。

set res=Server.CreateObject("ADODB.Recordset")Cres.open dbnameres.ActiveConnection=Cresres.source="Select*from res where 帐号="&Num&" and 密码="&Passwd&";"res.openif res.BOF then "如果查找结果为空,那么就说明注册不正确,所以在页面中显示下面的文本/%><p>注册不正确,请返回注册页面重新注册!</p><%else “否则就说明注册成功,可以进入浏览页面!%><!--#Include virtual="/success.htm"--> "这里采用了Server Side Include的方法,把允许浏览的页面包含在这个文件里面!<% res.Close “关闭刚才打开的数据库。

end if %></body></html>4,创建 NewRes.asp文件,这个文件的主要功能是把新用户的登陆信息存入数据库,代码如下<html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><meta name="GENERATOR" content="Microsoft frontpage 3.0"><title>输入数据库</title></head><body><!--#Include virtual="/adovbs.inc">“这个被包含进来的文件adovbs.inc是定义数据库对象ADO常量的文件。

<%Num=Request.form("txtNum") “把前面主页传送过来的内容赋给Num和Passwd两个变量。

Passwd=Request.form("txtPasswd")Set res=Server.CreateObject("ADODB.Recordset") “打开数据库。

dbname="Driver={Microsoft Access Driver(*.mdb)};DBQ="&ServerMapPath("\")&"\ResDb\Res.mdb;"sql="select*from res"res.open sql,dbName,adOpenKeyset,adLockOptimisticres.AddNew “添加新纪录res(1)=Num “res(1)代表数据库中的第二个字段,存储的是用户的帐号。

res(2)=Passwd “res(2)代表数据库中的第三个字段,存储的是用户的密码。

res.Update “更新数据库/res.Close %><p><b><font face=楷体_gb2312 size=5>您的帐号和密码已经注册成功,您现在可以<a href="http://your/index.htm">进入</a>了!</font></p></body></html>好了简单的代码就先讲解到这里,那里不对忘指教,下一节继续讲解用ASP设计一个留言薄,请各位及时收藏[ 本帖最后由 case 于 2006-7-1 17:14 编辑 ]-------------------------------------------------------------------------------- 作者: 天涯风云时间: 2006-7-1 09:58第二节:留言薄今天呢我们继续学习ASP建站十大常用程序第二节,这一节代码比较多请大家耐心的学习.本节我们要讲两个方面的知识: 前者是一个输入界面,后者是一个显示界面,用于显示留言信息.用ASP设计一个留言薄(上)首先,我们在做留言薄之前,先做出一个输入屏的界面效果,也就是生成留言部输入屏幕的htmL页,然后在这些htmL源代码中加入ASP脚本,我这里得到的htmL代码如下。

相关文档
最新文档