ASP建站十大常用程序代码公布(第一至十节)完整篇

合集下载

ASP编程常用代码精选集合(十二)

ASP编程常用代码精选集合(十二)

1:asp检查组件是否已经安装<% '函数名:IsObjInstalled'作用:检查组件是否已经安装'参数:strClassString ----组件名'返回值:True ----已经安装' False ----没有安装function IsObjInstalled(strClassString)on error resume nextIsObjInstalled = Falseerr = 0dim xTestObjset xTestObj = Server.createobject(strClassString)if0= err then IsObjInstalled = Trueset xTestObj = nothingerr = 0end function%>2:asp检查Email地址合法性'********************************************'函数名:BPCheckEMail'作用:检查Email地址合法性'参数:email ----要检查的Email地址'返回值:True ----Email地址合法False ----Email地址不合法'********************************************Function BPCheckEMail(email)Dim strArr,strRE1,strRE2,oRE1,oRE2,oMatches1,oMatches2strArr = Split(email,"@")If UBound(strArr) <> 1 ThenBPCheckEMail = False : Exit FunctionEnd IfstrRE1 = "^(?:[\w\.-]+@[A-Za-z1-9]{1}[A-Za-z0-9\.-]+\.[A-Za-z1-9]{2,3})" strRE2 = "[^\w\.@:-]+"Set oRE1 = New RegExp : Set oRE2 = New RegExpoRE1.Pattern = strRE1 : oRE2.Pattern = strRE2oRE1.IgnoreCase = False : oRE2.IgnoreCase = FalseoRE1.Global = True : oRE2.Global = TrueSet oMatches1 = oRE1.Execute(em ail) : Set oMatches2 = oRE2.Execute(em ail) If oMatches1.Count <> 0 And oMatches2.Count = 0 ThenBPCheckEMail = TrueElseBPCheckEMail = FalseEnd IfEnd Function3: asp生成指定类型的随机字符串'函数:RandomStr'作用:生成指定类型的随机字符串'参数:IsIgnoreCase(大小写字母状态)' IsStatus(数字、字母组合)' CodeLen(字符串长度)Function RandomStr(ByVal IsIgnoreCase,ByVal IsStatus,ByVal CodeLen) Dim NumStr,CharStr,StrDim RCodeItem,RCodeStart,RCodeStrNumStr="0123456789"CharStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ"Select Case UCase(IsIgnoreCase) '选择字符串类型Case"A":CharStr=CharStr&LCase(CharStr)Case"U":CharStr=CharStrCase"L":CharStr=LCase(CharStr)Case Else:CharStr=CharStr&LCase(CharStr)End SelectSelect Case UCase(IsStatus)'输出组合类型Case"A":Str=NumStr&CharStrCase"N":Str=NumStr'Only NumberCase"C":Str=CharStr'Only CharCase Else:Str=NumStr&CharStrEnd SelectRandomizeFor RCodeItem=0To CodeLen-1RCodeStart=Int(Rnd*Len(Str))RCodeStr=RCodeStr&Mid(Str,RCodeStart+1,1)NextRandomStr=RCodeStrEnd Function4:asp取得某个网页的内容'取得某个网页的内容function getHTTPPage(url)dim Httpset Http=server.createobject("MSXML2.XMLHTTP")Http.open "GET",url,falseHttp.sendif Http.readystate<>4thenexit functionend ifgetHTTPPage=bytesToBSTR(Http.responseBody,"GB2312")set http=nothingif err.number<>0thenerr.Clearend ifend functionFunction BytesToBstr(body,Cset)dim objstreamset objstream = Server.CreateObject("adodb.stream")objstream.Type = 1objstream.Mode =3objstream.Openobjstream.Write bodyobjstream.Position = 0objstream.Type = 2objstream.Charset = CsetBytesToBstr = objstream.ReadTextobjstream.Closeset objstream = nothingEnd Function5:asp的验证码'asp的验证码Sub Com_CreateValidCode(pSN)Response.Expires = -9999Response.AddHeader "Pr agma","no-cache"Response.AddHeader "cache-ctrol","no-cache"Response.ContentType = "Image/BMP"RandomizeDim i, ii, iiiConst cOdds = 8'杂点出现的机率Const cAmount = 10'文字数量Const cCode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"'颜色的数据(字符,背景)Dim vColorData(1)vColorData(0) = ChrB(0) & ChrB(0) & ChrB(255) ' 蓝0,绿0,红0(黑色)vColorData(1) = ChrB(235) & ChrB(235) & ChrB(235) ' 蓝250,绿236,红211(浅蓝色)'随机产生字符Dim vCode(4), vCodesFor i = 0To3vCode(i) = Int(Rnd* cAmount)vCodes = vCodes & Mid(cCode, vCode(i) + 1, 1)NextSession(pSN) = vCodes '记录入Session' 字符的数据Dim vNumberData(35)vNumberData(0) = "1110000111110111101111011110111101001011110100101 111010010111101001011110111101111011110111110000111"vNumberData(1) = "1111011111110001111111110111111111011111111101111 111110111111111011111111101111111110111111100000111"vNumberData(2) = "1110000111110111101111011110111111111011111111011 111111011111111011111111011111111011110111100000011"vNumberData(3) = "1110000111110111101111011110111111110111111100111 111111101111111111011110111101111011110111110000111"vNumberData(4) = "1111101111111110111111110011111110101111110110111 111011011111100000011111110111111111011111111000011"vNumberData(5) = "1100000011110111111111011111111101000111110011101 111111110111111111011110111101111011110111110000111"vNumberData(6) = "1111000111111011101111011111111101111111110100011 111001110111101111011110111101111011110111110000111"vNumberData(7) = "1100000011110111011111011101111111101111111110111 111110111111111011111111101111111110111111111011111"vNumberData(8) = "1110000111110111101111011110111101111011111000011 111101101111101111011110111101111011110111110000111"vNumberData(9) = "1110001111110111011111011110111101111011110111001 111100010111111111011111111101111011101111110001111"vNumberData(10) = "111101111111110111111110101111111010111111101011 1111101011111100000111110111011111011101111000100011"vNumberData(11) = "100000011111011110111101111011110111011111000011 1111011101111101111011110111101111011110111000000111"vNumberData(12) = "111000001111011110111011111011101111111110111111 1110111111111011111111101111101111011101111110001111"vNumberData(13) = "100000111111011101111101111011110111101111011110 1111011110111101111011110111101111011101111000001111"vNumberData(14) = "1000000111110111101111011011111101101111110000111111011011111101101111110111111111011110111000000111"vNumberData(15) = "100000011111011110111101101111110110111111000011 1111011011111101101111110111111111011111111000111111"vNumberData(16) = "111000011111011101111011110111101111111110111111 1110111111111011100011101111011111011101111110001111"vNumberData(17) = "100010001111011101111101110111110111011111000001 1111011101111101110111110111011111011101111000100011"vNumberData(18) = "110000011111110111111111011111111101111111110111 1111110111111111011111111101111111110111111100000111"vNumberData(19) = "111000001111111011111111101111111110111111111011 1111111011111111101111111110111110111011111000011111"vNumberData(20) = "100010001111011101111101101111110101111111000111 1111010111111101101111110110111111011101111000100011"vNumberData(21) = "100011111111011111111101111111110111111111011111 1111011111111101111111110111111111011110111000000011"vNumberData(22) = "100010001111001001111100100111110010011111010101 1111010101111101010111110101011111010101111001010011"vNumberData(23) = "100010001111001101111100110111110101011111010101 1111010101111101100111110110011111011001111000110111"vNumberData(24) = "111000111111011101111011111011101111101110111110 1110111110111011111011101111101111011101111110001111"vNumberData(25) = "100000011111011110111101111011110111101111000001 1111011111111101111111110111111111011111111000111111"vNumberData(26) = "111000111111011101111011111011101111101110111110 1110111110111011111011101001101111011001111110001011"vNumberData(27) = "100000111111011101111101110111110111011111000011 1111010111111101101111110110111111011101111000110011"vNumberData(28) = "111000001111011110111101111011110111111111100111 1111111001111111111011110111101111011110111100000111"vNumberData(29) = "100000001110110110111111011111111101111111110111 1111110111111111011111111101111111110111111110001111"vNumberData(30) = "100010001111011101111101110111110111011111011101 1111011101111101110111110111011111011101111110001111"vNumberData(31) = "100010001111011101111101110111110111011111101011 1111101011111110101111111010111111110111111111011111"vNumberData(32) = "100101001111010101111101010111110101011111010101 1111001001111110101111111010111111101011111110101111"vNumberData(33) = "100010001111011101111110101111111010111111110111 1111110111111110101111111010111111011101111000100011"vNumberData(34) = "100010001111011101111101110111111010111111101011 1111110111111111011111111101111111110111111110001111"vNumberData(35) = "110000001111011101111111110111111110111111111011 1111110111111111011111111011111111101110111100000011"' 输出图像文件头Response.BinaryWrite ChrB(66) & ChrB(77) & ChrB(230) & ChrB(4) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & _ChrB(0) & ChrB(0) & ChrB(54) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(40) & ChrB(0) & ChrB(0) & ChrB(0) & _ChrB(40) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(10) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(1) & ChrB(0)' 输出图像信息头Response.BinaryWrite ChrB(24) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & Ch rB(0) & ChrB(176) & ChrB(4) & _ChrB(0) & ChrB(0) & ChrB(18) & ChrB(11) & ChrB(0) & ChrB(0) & ChrB(18) & ChrB(11) & ChrB(0) & ChrB(0) & _ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & ChrB(0) & C hrB(0)For i = 9To0Step -1' 历经所有行For ii = 0To3' 历经所有字For iii = 1To10' 历经所有像素' 逐行、逐字、逐像素地输出图像数据If Rnd* 99+ 1< cOdds Then' 随机生成杂点Response.BinaryWrite vColorData(0)ElseResponse.BinaryWrite vColorData(Mid(vNumberData(vCode(ii)), i * 10 + iii, 1))End IfNextNextNextEnd Subdim sNamesName = request("s")if sName = ""thenCall Com_CreateValidCode("VERIFYNUM")elseCall Com_CreateValidCode(sName)end if。

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

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

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

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

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

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

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

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

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

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

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

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

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.NET程序中常用代码汇总-1

ASP.NET程序中常用代码汇总-1

window命令大全//传送参数:response.write("<script>window.open(’*.aspx?id="+this.DropDownList1.Select Index+"&id1="++"’)</script>")//接收参数:string a = Request.QueryString("id");string b = Request.QueryString("id1");Button1.Attributes.Add("onclick","return confirm(’确认?’)");bu tton.attributes.add("onclick","if(confirm(’are you sure?’)){return t rue;}else{return false;}")int intEmpID = (int)MyDataGrid.DataKeys[e.Item.ItemIndex];string deleteCmd = "DELETE from Employee where emp_id = " + intEmpID.ToString ()4.删除表格记录警告private void DataGrid_ItemCreated(Object sender,DataGridItemEventArgs e) {switch(e.Item.ItemType){case ListItemType.Item :case ListItemType.AlternatingItem :case ListItemType.EditItem:TableCell myTableCell;myTableCell = e.Item.Cells[14];LinkButton myDeleteButton ;myDeleteButton = (LinkButton)myTableCell.Controls[0];myDeleteButton.Attributes.Add("onclick","return c onfirm(’您是否确定要删除这条信息’);");break;default:break;}}5.点击表格行链接另一页private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebContro ls.DataGridItemEventArgs e){//点击表格打开if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType. AlternatingItem)e.Item.Attributes.Add("onclick","window.open(’Default.aspx?id=" + e.Item. Cells[0].Text + "’);");}//双击表格连接到另一页//在itemDataBind事件中if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.Al ternatingItem){string OrderItemID =e.item.cells[1].Text;e.item.Attributes.Add("ondblclick", "location.href=’../ShippedGrid.aspx?id =" + OrderItemID + "’");}//双击表格打开新一页if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.Al ternatingItem){string OrderItemID =e.item.cells[1].Text;e.item.Attributes.Add("ondblclick", "open(’../ShippedGrid.aspx?id=" + Orde rItemID + "’)");}★特别注意:【?id=】处不能为【?id =】6.表格超连接列传递参数<asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" Na vigateUrl="aaa.aspx?id=’<%# DataBinder.Eval(Container.DataItem, "数据字段1")%>’ & name=’<%# Da taBinder.Eval(Container.DataItem, "数据字段2")%>’ />7.表格点击改变颜色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’;");}写在DataGrid的_ItemDataBound里if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem){e.Item.Attributes.Add("onmouseover","this.style.backgroundColor=’#99cc00’;this.style.color=’buttontext’;this.style.cursor=’default’;");e.Item.Attributes.Add("onmouseout","this.style.backgroundColor=’’;this.style.color=’’;");}8.关于日期格式日期格式设定DataFormatString="{0:yyyy-MM-dd}"//我觉得应该在itembound事件中e.items.cell["你的列"].text=DateTime.Parse(e.items.cell["你的列"].text.ToString("yyyy-MM-dd "))9.获取错误信息并到指定页面//不要使用Response.Redirect,而应该使用Server.Transfere.g// in global.asaxprotected void Application_Error(Object sender, EventArgs e) {if (Server.GetLastError() is HttpUnhandledException)Server.Transfer("MyErrorPage.aspx");//其余的非HttpUnhandledException异常交给自己处理就okay了 :)}//Redirect会导致post-back的产生从而丢失了错误信息,所以页面导向应该直接在服务器端执行,这样就可以在错误处理页面得到出错信息并进行相应的处理10.清空CookieCookie.Expires=[DateTime];Response.Cookies("UserName").Expires = 0。

ASP常用代码段之一

ASP常用代码段之一
NongliData(17) = 465197
NongliData(18) = 3221
NongliData(19) = 3402
NongliData(20) = 400202
NongliData(21) = 2901
NongliData(22) = 1386
NongliData(23) = 267611
Dim curTime, curYear, curMonth, curDay, curWeekday
Dim GongliStr, WeekdayStr, NongliStr, NongliDayStr
Dim i, m, n, k, isEnd, bit, TheDate
'获取当前系统时间
curTime = Date
NongliData(45) = 204070
NongliData(46) = 3477
NongliData(47) = 461653
NongliData(48) = 1386
NongliData(49) = 2413
NongliData(50) = 330077
NongliData(51) = 1197
MonName(10) = "十"
MonName(11) = "十一"
MonName(12) = "腊"
'公历每月前面的天数
MonthAdd(0) = 0
MonthAdd(1) = 31
MonthAdd(2) = 59
MonthAdd(3) = 90
MonthAdd(4) = 120
MonthAdd(5) = 151
'地支名称

asp常用代码

asp常用代码

翻页:<%Set rs = server.CreateObject("Adodb.RecordSet")rs.open sql,c onn,1,1if not rs.eof thenif request("pagenum")="" thenpagenum=1elseif IsNumeric(request("pagenum")) thenpagenum=Cint(request("pagenum"))elsepagenum=1end ifend ifrs.pagesize=40if pagenum<=0 then pagenum=1if pagenum>rs.pagecount then pagenum=rs.pagecount'response.write "["&pagenum&"]"rs.absolutepage=pagenum '转到要查询的页。

for i=1 to rs.pagesize%>循环内容<%rs.movenextif rs.eof then exit fornextelse%>还没记录!<%end if%><%response.write("每页"&rs.pagesize&"项&nbsp;&nbsp;共"&rs.recordcount&"项&nbsp;&nbsp;"&pagenum&"/"&rs.pagecount&"&nbsp;&nbsp;")if 1 < pagenum then '向上翻页response.write("<a href='?pagenum=1'>首页</a>&nbsp;")response.write("<a href='?pagenum="&pagenum-1&"'>上一页</a>&nbsp;")elseresponse.write("<font disabled>首页上一页&nbsp;</font>")end ifif pagenum >= rs.pagecount then '向下翻页response.write("<font disabled>下一页尾页</font>&nbsp;")else'response.write("<br>rs.pagecount="&rs.pagecount&"<br>pagenum="&pagenum&"<br>")response.write("&nbsp;<a href='?pagenum="&pagenum+1&"'>下一页</a>&nbsp;")response.write("<a href='?pagenum="&rs.pagecount&"'>尾页</a>&nbsp;")end if%>VB回车换行符:vbCrLf是VB中用于表示“回车换行”的字符串常数(长度为2字节),相当于Chr(13)+Chr(10),或者汇编中的DB 0AH,0DH,$由于是常数,所以不会影响速度。

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代码

常用的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%>。

超精华的asp代码大全

超精华的asp代码大全

超精华的asp代码⼤全显⽰页⾯加载时间重复域中的斑马线显⽰字符串前20个字符并在结尾处添加“……”如果动态图⽚为空,使⽤默认图⽚代替如果数据为空,使⽤默认提⽰信息代替显⽰页⾯加载时间页⾯顶部添加下⾯的代码:<%Dim strStartTimeDim strEndTimestrStartTime = Timer '开始时间%>页⾯(同⼀页)的末尾添加:<%' 加载完毕的时间strEndTime = TimerResponse.Write ("页⾯加载时间: ")Response.Write FormatNumber(strEndTime - strStartTime, 4)Response.Write (" 秒.")%>重复域中的斑马线<%'此模块放置在重复域之外Dim RecordCounterRecordcounter = 0%><tr class =<%'将重复域中第⼀个 <tr>标签的CLASS属性代码⽤本模块替换'本模块基于CSS来改变单元格背景⾊,你也可以直接设置背景⾊来实现斑马线RecordCounter = Recordcounter + 1If RecordCounter Mod 2 = 1 ThenResponse.Write "altRow1"ElseResponse.write "altRow2"End If%>显⽰字符串前20个字符并在结尾处添加“……”<%Dim CutShortCutShort = rsYourRecordset.Fields.Item("YourField").ValueResponse.Write LEFT (CutShort, 20) & "........"%>如果动态图⽚为空,⽤默认图⽚代替<%Dim PicShowPicShow = rsShowHide.Fields.Item("shMainPix").ValueIF PicShow <>"" THEN %><img src="<%=rsShowHide.Fields.Item("shMainPix").Value%>"><% ELSE %><img src="StaticPic.gif"><% End If %>如果数据为空,⽤默认提⽰信息代替。

常用的代码

常用的代码

通知:观察者--- 注册刷新金钱体力的回调函数监听广播消息FBNotificationCenter:getInstance():addNotificationObserver(LUA_EVENT_REFRE SH_MONEY_AND_ENERGY,FBLuaEvent.new(self,self.updateMoneyAndDiamondAndE nergy));---- 消息的数量变化,会触发,即显示人物或者消息按钮上德红色点FBNotificationCenter:getInstance():addNotificationObserver(LUA_EVENT_REFRE SH_ALL_MESSAGE_SUCCESS,FBLuaEvent.new(self,self.showNewMsgIcon));FBNotificationCenter:getInstance():addNotificationObserver(LUA_EVENT_CONFI RM_ADD_FRIEND_SUCCESS,FBLuaEvent.new(self,self.showNewMsgIcon));FBNotificationCenter:getInstance():addNotificationObserver(LUA_EVENT_IGNOR E_MESSAGE_SUCCESS,FBLuaEvent.new(self,self.showNewMsgIcon));FBNotificationCenter:getInstance():addNotificationObserver(LUA_EVENT_CONFI RM_MESSAGE_SUCCESS,FBLuaEvent.new(self,self.showNewMsgIcon));---- 有新的成就任务完成FBNotificationCenter:getInstance():addNotificationObserver(LUA_EVENT_NEW_ ACHIEVEMENT_TASK_FINISHED,FBLuaEvent.new(self,self.showNewMsgIcon));发送一个通知FBNotificationCenter:getInstance():postNotification(LUA_EVENT_HIDE_WAITING_LAY ER,nil);获取lua的button 的名字local thebutton = tolua.cast(buttonNode,"FBButtonBase"); ----获取按钮local buttonName = thebutton:getButtonName(); ----获取按钮名称fb_log_warning("buttonName", buttonName);fb_log_debug("");if (buttonName == "btnBackToPreloading") then ----回到预加载界面Director:popScene(true);elseif (buttonName == "fastGame") then ----快速游戏if RpcUseNewWay == false then----老方法FBNotificationCenter:getInstance():addNotificationObserver(LUA_EVENT_LOGIN_PART_ALL_FINISHED,FBLuaEvent.new(self,self.goToAdventureScene));loginServer:startLogininWithUUID();CheckPointControllerLua:getInstance():doCheckPointByData(CheckPointEvent_St artGame);else----新方法if PreloadController:getInstance().m_is_localGame then----离线进入游戏self:goToAdventureScene();else----在线登陆服务器local Context = self;local function _callback()Context:goToAdventureScene();endLoginController:getInstance():Login_UUID(_callback);CheckPointControllerLua:getInstance():doCheckPointByData(CheckPointEvent_St artGame);endendelseif (buttonName == "resignByEmail") then ----邮箱登陆CheckPointControllerLua:getInstance():doCheckPointByData(CheckPointEvent_St artGame);loginServer:startLogininWithEmail();elseif (buttonName == "SNSID") then ----SNS 平台登陆CheckPointControllerLua:getInstance():doCheckPointByData(CheckPointEvent_St artGame);loginServer:startLogininWithSNS();elseif (buttonName == "channel") then ----渠道登陆CheckPointControllerLua:getInstance():doCheckPointByData(CheckPointEvent_St artGame);loginServer:startLogininWithChannel();endend对怪物的血条进行缩放local view = self.mygameboardviewif view thenlocal map = view.baseMapif map thenlocal itemView = map[1][1];if itemView thenlocal piece = itemView.itemSprite[ItemSpriteType.kBackground];local wpos = piece:convertToWorldSpace(ccp(0,0))local butSize = piece:getContentSize();barBossHeath:setScaleX(2 * butSize.width / barBossHeath:getContentSize().width);self:showMissionSuccessPopup(thedata);调用下面GamePlayFightController:showMissionSuccessPopup(thedata)-------1.弹出-----------黄黄self.pop = MissionSuccessPopup:createMissionSuccessPopup("MissionSuccessPopup", 100,"",thedata);调用弹出成功页面MissionSuccessPopup:createMissionSuccessPopup(LayoutName, level, sceneName, data)c++那边出现问题的时候可以调用lua那边的堆栈if (pNewFrame == NULL){const char* codes = "tb()";luaL_dostring(tolua_S,codes);lua_pop(tolua_S,1);}luaL_dostring(tolua_S,"tb()");lua_pop(tolua_S,1)sed 's/\r//' ./renamePNG.sh > _renamePNG.sh 执行脚本时替换文件的名字。

ASP经典实用代码

ASP经典实用代码
ASP经典实用代码
1、数据库连接。
ASP与Access数据库连接:
<%@ language=VBscript%>
<%
dim conn,mdbfile powered by
mdbfile=server.mappath("数据库名称.mdb")
set conn=server.createobject("adodb.connection")
con.open "PROVIDER=SQLOLEDB;DATA SOURCE=SQL服务器名称或IP地址;UID=sa;PWD=数据库密码;DATABASE=数据库名称
%>
DW中用字符串连接代码:
"Driver={Microsoft Access Driver (*.mdb)};DBQ=数据库的绝对路径"
sql="SELECT * FROM data" '更改您的数据库表名
rs.Open sql,conn,1,1
6、获得系统的时间。
<%=now()%>
7、取得来访问的IP。
<%=request.serverVariables("remote_host")%>
8、随机数。
< % next % >
< /form >
12、常用SQL语句整理。
(1) 数据记录筛选:
sql="select * from 数据表 where 字段名=字段值 order by 字段名 [desc]"
sql="select * from 数据表 where 字段名 like ''%字段值%'' order by 字段名 [desc]"

ASP代码大全

ASP代码大全
w3 Jmail4.3 组件重新设计了其内部结构——使用 Message 对象代替原来的单一对象 Jmail.smtpmail 发送邮件,有些方法需要身份验证的(如 163、yahoo 等),可以用下面的方法 解决: <% Set jmail = Server.CreateObject("JMAIL.Message") '建立发送邮件的对象 jmail.silent = true '屏蔽例外错误,返回 FALSE 跟 TRUE 两值 j mail.logging = true '启用邮件日志 jmail.Charset = "GB2312" '邮件的文字编码为国标 jmail.ContentType = "text/html" '邮件的格式为 HTML 格式
邮件方面: CDONTS: <% Set cdomail = Server.CreateObject("CDONTS.NewMail") '建立邮件对象 cdomail.Subject = "Mail Subject" '邮件标题 cdomail.From = "Sender's Mail" '发件人的地址 cdomail.To = "Email will from" '收件人的地址 cdomail.Body = "Mail Body" '邮件的内容 cdomail.Send '执行发送 %>
'jmail.AddRecipientCC Email '邮件抄送者的地址 jmail.Execute() '执行邮件发送 jmail.Close '关闭邮件对象 End Sub

asp代码大全:ASP必须知道的精华代码大全

asp代码大全:ASP必须知道的精华代码大全
定义数据库连接些常量constadopenforwardonly游标只向前浏览记录不支持分页recordbookmarkconstadopenkey键集游标其他用户对记录说做修改将反映到记录集中但其他用户增加或删除记录不会反映到记录集中支持分页recordbookmarkconstadopendynamic动态游标功能最强但耗资源也最多用户对记录说做修改增加或删除记录都将反映到记录集中支持全功能浏览access不支持constadopenstatic静态游标只是数据个快照用户对记录说做修改增加或删除记录都不会反映到记录集中支持向前或向后移动constadlockreadonly锁定类型默认只读不能作任何修改constadlockpessimistic当编辑时立即锁定记录最安全方式constadlockoptimistic只有在update思路方法时才锁定记录集而在此前其他操作仍可对当前记录进行更改插入和删除等constadlockbatchoptimistic当编辑时记录不会被锁定而更改插入和删除是在批处理方式下完成constadcmdtexth0001constadcmdtable18
asp代码大全:ASP必须知道的精华代码大全
疯狂代码 / ĵ:http://Asp/Article15994.html 1. _disibledevent=><table border _disibledevent=>2. <body _disibledevent=>3. _disibledevent=>4. _disibledevent=>5. <link rel=\"Shortcut Icon\" document.referrer 16. 最小化、最大化、关闭窗口 <object id=hh1 id=\"clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11\"> <param name=\"Command\" value=\"Minimize\"></object> <object id=hh2 id=\"clsid:ADB880A6-D8FF-11CF-9377-00AA003B7A11\"> <param name=\"Command\" value=\"Maximize\"></object>[Page] <OBJECT id=hh3 id=\"clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11\"> <PARAM NAME=\"Command\" value=\"Close\"></OBJECT> <input type=button value=最小化 _disibledevent=><input type=button value=最大化 _disibledevent=><input type=button value=关闭 _disibledevent=>本例适用于IE 17. <% 定义数据库连接些常量 Const adOpenForwardOnly = 0 游标只向前浏览记录不支持分页、Record、BookMark Const adOpenKey = 1 键集游标其他用户对记录说做修改将反映到记录集中但其他用户增加或删除记录不会 反映到记录集中支持分页、Record、BookMark Const adOpenDynamic = 2 动态游标功能最强但耗资源也最多用户对记录说做修改增加或删除记录都将反映 到记录集中支持全功能浏览(ACCESS不支持) Const adOpenStatic = 3 静态游标只是数据个快照用户对记录说做修改增加或删除记录都不会反映到记录集 中支持向前或向后移动 Const adLockReadOnly = 1 锁定类型默认只读不能作任何修改 Const adLockPessimistic = 2 当编辑时立即锁定记录最安全方式 Const adLockOptimistic = 3 只有在Update思路方法时才锁定记录集而在此前其他操作仍可对当前记录进行 更改、插入和删除等 Const adLockBatchOptimistic = 4 当编辑时记录不会被锁定而更改、插入和删除是在批处理方式下完成 Const adCmdText = &H <script language=\"javascript\"><!-function checkNum(str){ str.match(/\\D/)null} alert(checkNum(\"1232142141\")) alert(checkNum(\"123214214a1\"))

asp常用代码大全

asp常用代码大全

asp常用代码大全x1、ASP开始结束符语法:< % %> 文件后缀.asp2、判断语句:判断表单传来的用户名和密码是否正确,并提示If request("username")="admin" thenResponse.write"恭喜,你已经登录成功"ElseResponse.write"对不起,您输入的用户名错误,请返回重输入"End ifIf request("name")="admin" and request("pass")="admin"thenResponse.redirect"admin.asp"ElseResponse.redirect"login.asp"End if3、循环语句:循环显示6条数据库中的记录写法1:for n=1 to 6response.write rs("title")&"< br>"if not rs.eof thenexit forelsers.movenextend ifnext写法二:do while not rs.eofresponse.write rs("title")&"< br>"rs.movenextloop4、常用变量转换函数:Now() 函数返回系统时间Date() 函数返回当前系统日期.CStr(int) 函数转化一个表达式为字符串CInt(string) 将一个表达式转化为数字类型Trim(request("username")) 函数去掉字符串左右的空格Left(rs("title"),10) 函数返回字符串左边第length个字符以前的字符(含第length个字符),一般在限制新闻标题的显示长度的时候用Len(string) 函数返回字符串的长度.5、Access数据库连接代码方法一:db="mydata.mdb" ‘如果放在目录中,就要写明"database/mydata.mdb"Set conn = Server.CreateObject("ADODB.Connection")connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(db)conn.Open connstr方法二:'如果你的服务器采用较老版本Access驱动,请用下面连接方法db="mydata.mdb" ‘如果放在目录中,就要写明"database/mydata.mdb"Set conn = Server.CreateObject("ADODB.Connection")connstr="driver={Microsoft Access Driver (*.mdb)};dbq=" & Server.MapPath(db)conn.Open connstr6、Recordset对象操作数据库语法(1)打开sql语句指定的表中的数据,把这批数据放入rs对象中取出news表中所有的数据放到rs中Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news"Rs.Open SqlStr,conn,1,1取出news表中前6条数据放到rs中Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select top 6 * from news"Rs.Open SqlStr,conn,1,1(2)循环显示6条rs对象中存在的数据,列表显示不带连接的写法for n=1 to 6response.write rs("title")&"< br>"if not rs.eof thenexit forelsers.movenextend ifnext带连接的写法for n=1 to 6response.write "< a href=show.asp?id=rs("id")>"& left(rs("title"),20)&"< /a>< br>"if not rs.eof thenexit forelsers.movenextend ifnext(3)向数据库添加一条数据代码Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news"Rs.Open SqlStr,conn,1,3 ‘注意这里的1,3代表可以写入的打开数据表Rs.addnewRs("title")=trim(request("title"))Rs("neirong")=request("neirong")Rs("date")=now()rs.update ‘真正写入数据库(4)修改一条记录的代码,通过(2)中的连接传递过来了id数值Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘注意这里的1,3代表可以写入的打开数据表Rs("title")=trim(request("title"))Rs("neirong")=request("neirong")Rs("date")=now()rs.update ‘真正写入数据库(5)删除数据库中一条记录,通过连接传递过来了数据得id数值Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘注意这里的1,3代表可以写入的打开数据表rs.delete ‘删除该条数据7、标准Sql语句写法包括取全部记录Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news"Rs.Open SqlStr,conn,1,1 ‘运行sql语句,把数据提出到rs对象中选取几条数据Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select top 6 * from news"Rs.Open SqlStr,conn,1,1 ‘运行sql语句,把6条数据提出到rs 对象中选取一条指定表中id字段数值的数据Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select * from news where id="&request("id")Rs.Open SqlStr,conn,1,1 ‘运行sql语句,把6条数据提出到rs 对象中添加一条表单传过来的数据替换Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="insert into news(title,neirong) values(request("title"), request("neirong"))修改一条指定表中id字段数值的数据,用表单传过来的数据替换Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="update news set title=’"&request("title")&"’,neirong=’"&request("内容")&"’ where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘运行sql语句,把数据提出到rs对象中删除一条指定表中id字段数值的数据Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="delete from news where id="&request("id")Rs.Open SqlStr,conn,1,3 ‘运行sql语句,把数据提出到rs对象中8、当点击按钮时候表单带着的数据传送到哪个文件,在哪里指定?< form method="post" action="addsave.asp">< input type="text" name="title">< input type="text" name="neirong">< input type="submit" name="Submit" value="提交">< /form>9、表单提交来的数据接收并显示到屏幕上的代码response.write request("name")response.write now()response.write trim(request("name"))10、利用Application对象作计数器的语法在网页的头部加入Application.LockApplication("counter") = Application("counter") + 1Application.UnLock在需要显示计数内容的网页的地方,加入下面的语句response.write Application("counter")11、利用Session对象保护后台管理页面admin.asp,防止未登陆用户进入在网站后台网页admin.asp的头部加入下面的代码,if session(admin)< >"ok" thenresponse.redirect"login.asp"response.endend if在网站后台登陆页的密码验证部分标准写法AdmName=Request.Form("Name")AdmPass=Request.Form("Pass")Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="Select * from Admin where name='"&AdmName&"' and pass='"&AdmPass&"'"Rs.Open SqlStr,conn,1,3if Rs.EOF AND RS.BOF thenResponse.Redirect("login.asp")response.endelsesession("admin")="ok"Response.Redirect("admin.asp")response.endend if12、分页代码sql = "select……………………省略了sql语句Set rs=Server.Createobject("ADODB.RECORDSET")rs.Open sql, conn, 1, 1if not rs.eof thenpages = 30 '定义每页显示的记录数rs.pageSize = pages '定义每页显示的记录数allPages = rs.pageCount '计算一共能分多少页page = Request.QueryString("page")'通过浏览器传递的页数’if语句属于基本的排错处理if isEmpty(page) or Cint(page) < 1 thenpage = 1elseif Cint(page) > allPages thenpage = allPagesend ifrs.AbsolutePage = pageDo while not rs.eof and pages > 0'这里输出你要的内容………………pages = pages - 1rs.MoveNextLoopelseResponse.Write("数据库暂无内容!")End ifrs.CloseSet rs = Nothing分页页码连接和跳转页码程序< form Action="v3.asp" Method="GET">< %If Page < > 1 ThenResponse.Write "< A HREF=?Page=1>第一页< /A>"Response.Write "< A HREF=?Page=" & (Page-1) & ">上一页< /A>"End IfIf Page < > rs.PageCount ThenResponse.Write "< A HREF=?Page=" & (Page+1) & ">下一页< /A>"Response.Write "< A HREF=?Page=" & rs.PageCount & ">最后一页< /A>"End If%>< p>输入页数:< input TYPE="TEXT" Name="Page" SIZE="3"> 页数:< font COLOR="Red">< %=Page%>/< %=rs.PageCount%>< /font> < /p>< /form>13、分行列显示图片和产品名称的代码(4列x3行=12个)< %Set Rs=Server.CreateObject("ADODB.RecordSet")SqlStr="select top 12 * from myproduct"Rs.Open SqlStr,conn,1,1i=1%>< table width="90%" border="1" cellspacing="0" sellpadding="0">< tr>< %do while not rs.eof%>< td align="center">< img src="< %=rs("imgurl")%>" width="52" height="120">< br>< %=rs("productname")%>< /td>< % if i mod 4=0 then response.write"< /tr>< tr>"i=i+1rs.movenextlooprs.close%>< /tr>< /table>14、ASP数据库连接之ACCESS-SQLSERVER< %IsSqlData=0 定义数据库类别,0为Access数据库,1为SQL 数据库If IsSqlData=0 ThenAccess数据库datapath ="data/" 数据库目录的相对路径datafile ="data.mdb" 数据库的文件名connstr="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="&Server.MapPath(""&datapath&""&datafile&"") Connstr="DBQ="&server.mappath(""&datapath&""&datafil e&"")&";DRIVER={Microsoft Access Driver (*.mdb)};"ElseSQL数据库SqlLocalName ="(local)" 连接IP [ 本地用 (local) 外地用IP ] SqlUsername ="sa" 用户名SqlPassword ="1" 用户密码SqlDatabaseName="data" 数据库名ConnStr = "Provider=Sqloledb;User ID=" & SqlUsername & "; Password=" & SqlPassword & "; Initial Catalog = " & SqlDatabaseName & "; Data Source=" & SqlLocalName & ";"END IFOn Error Resume NextSet conn=Server.CreateObject("ADODB.Connection")conn.open ConnStrIf Err Thenerr.ClearSet Conn = NothingResponse.Write "数据库连接出错,请检查连接字串。

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 简单代码

一、学生注册:using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.OleDb;using mydb;public partial class manager_erroll_student : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (Session["Manager"] == null)Response.Write("<script>window.open('../student/not_login.aspx',target='w_right');</script>");}protected void Submit1_ServerClick(object sender, EventArgs e){String filepath = "~/Src/";String savepath = Server.MapPath("..") + @"\Src\";int filelength;String filetype;if (FileUpload1.HasFile){filepath += this.FileUpload1.FileName;String filename = FileUpload1.FileName;savepath += filename;FileUpload1.SaveAs(savepath);filelength = FileUpload1.PostedFile.ContentLength / 1024;filetype = FileUpload1.PostedFile.ContentType;Label2.Text = "<font style='font-size: 13px;font-weight: bold; '>成功上传:</font>" + filename + "<br>" + "<font style='font-size: 13px;font-weight: bold;'>文件大小:</font>" + filelength + "K<br>" + "<font style='font-size: 13px;font-weight: bold;'>文件类型:</font>" + filetype;}String userName = .Text;String userID = this.xh.Text;String userSex = "";if (this.RadioButton1.Checked)userSex += this.RadioButton1.Text;if (this.RadioButton2.Checked)userSex += this.RadioButton2.Text;String E_mail = this.yx.Value;String userPass = this.queding.Text;String BeiZhu = this.ps.Text;String Photo = filepath;String Sdept = this.zy.Text;String Grade = this.nj.Text;//-----------------------------------------------------------------//String sql = "insert into [users] values('" + userID + " ', '" +userPass + " ') ";Class1 cc2 = new Class1();cc2.dboperation(sql);cc2.close();String sql1 = "insert into userinf(userID,userName,userSex,BeiZhu,E_mail,Photo,Grade, Sdept) values('" + userID + " ', '" + userName + " ','" + userSex + " ','" + BeiZhu + " ','" + E_mail + "','" + filepath + "','" + Grade + " ','" + Sdept + " ') ";Class1 cc3 =new Class1();cc3.dboperation(sql1);cc3.close();String sql3 = "update [userinf] set Photo= '"+ filepath + "' where userID= '"+ userID + "'";Class1 cc1 = new Class1();cc1.dboperation(sql3);cc1.close();String sql2 = "select * from [users] where userID='" + userID + " '";Class1 cc4 = new Class1();if (cc4.select(sql2).HasRows){Label1.Text += "<font style='font-size: 14px;font-weight: bold;color:red '>已经注册成功:</font>" + "<br>" + "<hr align='left' width=250 color='blue'>";}else{Response.Write("<script>alert('注册失败请重新注册!!');</script>");}Label1.Text += "<font style='font-size: 13px;font-weight: bold; '>欢迎您:</font>" + name.Text + "<br/>";Label1.Text += "<font style='font-size: 13px;font-weight: bold;'>您的学号:</font>" + xh.Text + "<br/>";if (RadioButton1.Checked)Label1.Text += "<font style='font-size: 13px;font-weight: bold;'>性别:</font>"+ RadioButton1.Text + "<br/>";if (RadioButton2.Checked)Label1.Text += "<font style='font-size: 13px;font-weight: bold;'>性别:</font>"+ RadioButton2.Text + "<br/>";Label1.Text += "<font style='font-size: 13px;font-weight: bold;'>您的邮箱:</font>"+ yx.Value + "<br/>";Label1.Text += "<font style='font-size: 13px;font-weight: bold;'>您的个人说明:</font>" + ps.Text + "<br/>";Label1.Text += "<font style='font-size: 13px;font-weight: bold;'>您的专业:</font>"+ zy.Text + "<br/>";Label1.Text += "<font style='font-size: 13px;font-weight: bold;'>您的年级:</font>"+ nj.Text.Replace("\n", "<br>");cc4.close();}protected void xh_TextChanged(object sender, EventArgs e){}}二、class2using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.OleDb;namespace mydb2{///<summary>/// Class2 的摘要说明///</summary>public class Class2 : Page{protected OleDbConnection conn;protected OleDbCommand cmd;protected OleDbDataReader dr;protected string connString;public Class2(){connString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" +Server.MapPath("../App_Data\\mydb.mdb");}public void databind(GridView myGrid, string sql)//GridView的数据绑定{OleDbConnection con = new OleDbConnection(connString);//创建连接对象OleDbDataAdapter adp = new OleDbDataAdapter(sql, con);//DA从数据库con读取数据DataSet ds = new DataSet();//内存中数据库DSadp.Fill(ds);//DA将con读取的数据传到Ds中myGrid.DataSource = ds.Tables[0].DefaultView;//把ds.table【0】的数据都显示到GridView//GridView1.DataMember = "userinf";myGrid.DataBind();con.Close();}}}三、删除页面跳转using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.OleDb;using mydb;public partial class manager_deletejump : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (Session["Manager"] == null)Response.Redirect("managerlogin_now.aspx");else{string idd = Request.QueryString["idd"];Class1 a = new Class1();string sql = "delete from news where [ID]=" + idd;a.dboperation(sql);a.close();Response.Write("<script>alert('删除成功!')</script>");}}}四、密码修改using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.OleDb;using mydb;public partial class manager_change_passwordm : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if ( Session["Manager"] == null)Response.Write("<script>window.open('../student/not_login.aspx',target='w_right');</script>");}protected void Submit1_ServerClick(object sender, EventArgs e){// String userID= xh.Text;if (y.Text.Equals(Session["userpass"].ToString())){String userPass = qd.Text;String sql = "update Manage set [password]= '" + userPass + " ' where account='" + /*userID*/Session["Manager"].ToString() + " ' ";Class1 cc4 = new Class1();cc4.dboperation(sql);Label1.Text += "<font style='font-size: 13px;font-weight: bold; color:red '>修改密码成功</font>";cc4.close();}else{Label1.Text += "<font style='font-size: 13px;font-weight: bold; color:red '>密码修改失败,可能是原密码有误,请重试...</font>";}}}五,课程处理using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.OleDb;using mydb;using System.IO;using mydb2;public partial class Dealcourse : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (Session["Manager"] == null)Response.Write("<script>window.open('../student/not_login.aspx',target='w_right');</script>");if (!Page.IsPostBack)//如果页面不是第一次加载{//如果是多个关键值//GridView1.DataKeyNames = new string[] { "userID", "userCourse", "userTerm" };string idd = Request.QueryString["idd"].ToString();string sql = "SELECT CourseID AS 课程号,Coursename AS 课程名, CourseDate AS 开课学期,XS AS 学时, XF AS 学分, Kind AS 课程类型,CourseNo AS 课序号,CourseCol AS 学院,Teacher AS 授课教师 FROM Course where CourseID='" + idd + "'";Class2 cc = new Class2();cc.databind(GridView1, sql);}}protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) {string idd = Request.QueryString["idd"].ToString();string sql = "SELECT CourseID AS 课程号,Coursename AS 课程名, CourseDate AS 开课学期,XS AS 学时, XF AS 学分, Kind AS 课程类型,CourseNo AS 课序号,CourseCol AS 学院,Teacher AS 授课教师 FROM Course where CourseID='" + idd + "'";Class2 cc = new Class2();GridView1.EditIndex = -1;//将gridview从编辑模式切换成浏览模式cc.databind(GridView1, sql);}protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e){Response.Write("<script > confirm ('确认要删除吗?');</script>");string idd = Request.QueryString["idd"].ToString();//string userid = (string)GridView1.DataKeys[e.RowIndex].Value;string sql1 = "delete from Course where CourseID='" + idd + "'";Class1 a = new Class1();a.dboperation(sql1);a.close();string sql = "SELECT CourseID AS 课程号,Coursename AS 课程名, CourseDate AS 开课学期,XS AS 学时, XF AS 学分, Kind AS 课程类型,CourseNo AS 课序号,CourseCol AS 学院,Teacher AS 授课教师 FROM Course where CourseID='" + idd + "'";Class2 cc = new Class2();GridView1.EditIndex = -1;cc.databind(GridView1, sql);}protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e){string idd = Request.QueryString["idd"].ToString();string CourseID =((TextBox)(GridView1.Rows[e.RowIndex].Cells[2].Controls[0])).Text.ToString();string Coursename =((TextBox)(GridView1.Rows[e.RowIndex].Cells[3].Controls[0])).Text.ToString();string CourseDate =((TextBox)(GridView1.Rows[e.RowIndex].Cells[4].Controls[0])).Text.ToString();string XS =((TextBox)(GridView1.Rows[e.RowIndex].Cells[5].Controls[0])).Text.ToString();string XF =((TextBox)(GridView1.Rows[e.RowIndex].Cells[6].Controls[0])).Text.ToString();string Kind =((TextBox)(GridView1.Rows[e.RowIndex].Cells[7].Controls[0])).Text.ToString();string CourseNo =((TextBox)(GridView1.Rows[e.RowIndex].Cells[8].Controls[0])).Text.ToString();string CourseCol =((TextBox)(GridView1.Rows[e.RowIndex].Cells[9].Controls[0])).Text.ToString();string Teacher =((TextBox)(GridView1.Rows[e.RowIndex].Cells[10].Controls[0])).Text.ToString();string sql2 = "update Course set CourseID='" + CourseID + "',Coursename='" + Coursename + "', CourseDate='" + CourseDate + "',XS='" + XS + " ', XF='" + XF + "', Kind='" + Kind + "',CourseNo='" + CourseNo + "',CourseCol='" + CourseCol + "',Teacher='" + Teacher + "' where CourseID='" + idd + "'";Class1 a = new Class1();a.dboperation(sql2);a.close();GridView1.EditIndex = -1;string sql = "SELECT CourseID AS 课程号,Coursename AS 课程名, CourseDate AS 开课学期,XS AS 学时, XF AS 学分, Kind AS 课程类型,CourseNo AS 课序号,CourseCol AS 学院,Teacher AS 授课教师 FROM Course where CourseID='" + idd + "'";Class2 cc = new Class2();cc.databind(GridView1, sql);}protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e){GridView1.EditIndex = e.NewEditIndex;string idd = Request.QueryString["idd"].ToString();string sql = "SELECT CourseID AS 课程号,Coursename AS 课程名, CourseDate AS 开课学期,XS AS 学时, XF AS 学分, Kind AS 课程类型,CourseNo AS 课序号,CourseCol AS 学院,Teacher AS 授课教师 FROM Course where CourseID='" + idd + "'";Class2 cc = new Class2();cc.databind(GridView1, sql);}}6.登录代码using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.OleDb;//using System.Web.SessionState.HttpSessionState;using mydb;public partial class login_now : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){if (Page.IsPostBack){Session["ID"] = null;//Session["userPass"] = null;}}protected void Login1_Authenticate(object sender, AuthenticateEventArgs e){Session["ID"] += erName;Session["userPass"] += Login1.Password;//Session.Timeout(30);Class1 cc = new Class1();string sql = "select * from users where userID='" + erName + "' and userPass='" + Login1.Password + "'";if (cc.select(sql).HasRows)Response.Redirect("login_succeed.aspx");elseResponse.Write("<script>alert('用户名或密码错误!!');</script>");cc.close();}}。

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

第一节:注册系统(一),设定注册页面的外观:在这个例子中涉及了五个页面,其中有三幅是一般的htm文件,另外的两幅是asp文件,在这里制作利用的工具是frontpage98,但是大部分的asp代码还是要自己输入的:1,设定原来已经注册的用户进入的外观:在这里设置了两个文本框,一个超级链接和两个按钮。

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

但是其中只有用来输入帐号,密码和确定密码的文本框有名字,分别为txtNum,txtPa sswd和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.Cl ose “ 关闭刚才打开的数据库。

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设计一个留言薄,请各位及时收藏第二节:留言薄今天呢我们继续学习ASP建站十大常用程序第二节,这一节代码比较多请大家耐心的学习.本节我们要讲两个方面的知识: 前者是一个输入界面,后者是一个显示界面,用于显示留言信息.用ASP设计一个留言薄(上)首先,我们在做留言薄之前,先做出一个输入屏的界面效果,也就是生成留言部输入屏幕的htmL页,然后在这些htmL源代码中加入ASP脚本,我这里得到的htmL代码如下。

*文件名:book.htm<html><head><title>留言薄</title></head><body bgcolor="#BED9FC" background="images/bg.gif"><p align="center"><img src="images/gbook.gif" alt="GBook.gif (12142 bytes)" WIDTH="374"HEIGHT="83"></p><p align="center">[<a href="disp.asp">我要看留言板</a>] [<a href="../index.asp">返回首页</a>]</p><form method="POST" action="book.asp"><input type="hidden" name="task" value="insert"><div align="left"><table><tr><td align="right">姓名</td><td><img src="images/bottom-b.gif" alt="BUTTOM-B.GIF (179 bytes)" WIDTH="16" HEIGHT="16"></td><td><input name="name" size="46"></td></tr><tr><td align="right">性别</td><td><img src="images/bottom-g.gif" alt="BUTTOM-G.GIF (179 bytes)" WIDTH="16" HEIGHT="16"></td><td><input name="sex" size="46"></td></tr><tr><td align="right">来自</td><td><img src="images/bottom-b.gif" alt="BUTTOM-B.GIF (179 bytes)" WIDTH="16" HEIGHT="16"></td><td><input name="from" size="46"></td></tr><tr><td align="right">主页URL</td><td><img src="images/homepage.gif" alt="HomePage.gif (1232 bytes)" WIDTH="30" HEIGHT="30"></td><td><input name="url" size="46"></td></tr><tr><td align="right">E-mail</td><td><img src="images/email.gif" alt="Email.gif (1197 bytes)" WIDTH="30" HEIGHT="30"></td><td><input name="email" size="46"></td></tr><tr><td align="right">留言</td><td colspan="2"><textarea wrap="off" name="comments" cols="49" rows="9"></textarea></td></tr><tr><td></td><td colspan="2"><dl><dd align="center"><input type="submit" value="我写好了"><input type="reset" value="重新再写"></dd></dl></td></tr></table></div></form><p align="center"></p></body></html>您可以按这里看一下这个界面的效果(需要强调一点,这些htmL代码还是完全没有功能的)你可以把它保存为book.htm,然后用FRONTPAGE98来打开它,打开后,可以查看网页中的那个输入FORM的属性,在这个留言薄中。

相关文档
最新文档