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编程常用代码精选集合(十三)

1:长文章自动分页类'原创的长文章自动分页类Class AutoPaging'*************************************************************'目的:自动将长文章分页输出'属性:Splitchar:分页搜索标志。

以一维数组方式输入,默认array("<br>","<BR>", "<Br>","<bR>")'PagingString:要进行分页的字符串'PagingSize:分页长度'CurrentPage:当前输出页码'DefaultRange:默认搜索分页标志范围'StepRange:搜索步长'方法:getTotalPageCount():返回总分页数'OutputString:输出当前分页内容'*************************************************************public Splitchar '分页搜索标志,数组public PagingString '分页字符串public PagingSize '页面最大长度public CurrentPage '当前页码public DefaultRange '默认起始范围public StepRange '步长pr ivate Truncate '2维数组m,n。

m0=页码、m1=起始字符、m2=结束字符,n=总页数pr ivate intStart '开始位置pr ivate intLen '截取长度pr ivate tmpStrpr ivate Range '起始范围pr ivate Sub Class_Initialize()Splitchar=array("<br>","<BR>","<Br>","<bR>")PagingSize = 2000DefaultRange=1StepRange = 1intStart = 0intEnd = 0End Subpublic Function getTotalPageCount() '返回总页数if len(PagingString) mod PagingSize > 0thengetTotalPageCount = int(len(PagingString) / PagingSize) + 1elsegetTotalPageCount = len(PagingString) / PagingSizeend ifEnd Functionpublic Sub OutputStringredim Truncate(2,getTotalPageCount())For tmpI = 0to getTotalPageCount()Truncate(0,tmpI)=tmpINextFor tmpI = 1to ubound(Truncate,2)if Truncate(0,tmpI) = 1thenTruncate(1,tmpI) = 1elseTruncate(1,tmpI)=Truncate(1,tmpI - 1) + Truncate(2,tmpI - 1) end ifRange = DefaultRangeDo while Range < PagingSizetmpStr=right(mid(PagingString,Truncate(1,tmpI),PagingSize),Range)For tmpInt=0to ubound(Splitchar)if instr(1,tmpStr,Splitchar(tmpInt)) > 0thenTruncate(2,tmpI) = (PagingSize - (len(tmpStr) - instr(1,tmpStr,Spli tchar(tmpInt)))) - 1exit doend ifNextRange = Range + StepRangeLoopif tmpI = Cint(CurrentPage) thenintStart = Truncate(1,tmpI)intLen = Truncate(2,tmpI)end ifnextif Cint(CurrentPage) = getTotalPageCount() thenresponse.write(mid(PagingString,intStart)) '如果当前分页为最后一页,则取剩下的所有字符elseresponse.write(mid(PagingString,intStart,intLen))end ifEnd SubEnd Class2:asp登陆窗口代码,含数据库的连接<%@LANGUAGE="VBSCRIPT" CODEPAGE="936"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. /TR/xhtml1/DTD/xhtml1-transitional.dtd"><%dim connset conn=Server.createobject("adodb.connection")conn.open "pr ovider=microsoft.jet.oledb.4.0;data source="&server.mappath("jixie.m db")If err.number<>0 thenResponse.write("连接数据库时产生错误!")Response.EndEnd if%><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>数控机床结构设计系统</title><style type="text/css"><!--.STYLE1 {font-size: 36px}.STYLE2 {font-size: 36px; color: #FF0000; }.STYLE6 {font-size: 24px;color: #000000;}.STYLE8 {font-size: 14px}.STYLE9 {font-size: 16px; }body {background-image: url(image/001.jpg);}--></style></head><body ><label><form id="form1" name="form1" method="post" action=""><div align="center"><h1 class="STYLE1"><br /><br /></h1><h1 class="STYLE2"><span class="STYLE6">数控机床结构设计系统</span><br /> <br /><span class="STYLE8">*您没登陆,不具有任何操作权限,请先登陆!</span></h1></div></form><div align="center"><br /><form id="form3" name="form3" method="post" action=""><p class="STYLE9">用户名<input name="user" type="text" id="user" /></p><p class="STYLE9">密码<input name="pass" type="password" id="pass" /></p><p class="STYLE9"><input type="submit" name="Submit" value="提交" /><input type="reset" name="reset" value="重置" /></p></form></div></label><div align="center"><%dim user,pass,poweruser=request("user")pass=request("pass")power=request("power")if user="" or pass="" thenresponse.write "用户名或密码不能为空!"response.endend ifif power=0 thenset rs=conn.execute("select * from dljm where name='"&user&"' and password='"& pass&"'")elseresponse.write "你的密码或用户名有误,请重新登陆"end if%><%if not rs.eof thenif power=0 thensession("name")=userresponse.redirect"1.asp"end ifelseresponse.write "你的用户名或密码有误,请重新登陆"response.endend if%></div></body></html>3:对非法图片的删除lastpath="已经上传的图片路径"sFile=server.mappath(lastpath)set MyFile=server.CreateObject("Scripting.FileSystemObject")set MyText=MyFile.OpenTextFile(sFile, 1) '读取文本文件sTextAll=lcase(MyText.ReadAll)MyText.closesStr=".getfolder,.createfolder,.deletefolder,.createdirectory,.deletedirectory,.saveas,w script.shell,script,.encode.,重命名,修改,属性,文件,浏览器,新建,复制,成功,参数错误,服务器,空间,下载,http,create,delete,fso,set,select,execute,response"sNoString=split(sStr,",")for i=0 to ubound(sNoString)if instr(sTextAll,sNoString(i)) thenSET fs=server.CreateObject("Scripting.FileSystemObject")if FS.FileExists(sFile) thenFS.DeleteFile(sFile)end ifset fs=nothingresponse.Write "<script>alert('上传操作失败,非法图片'),window.history.go(-1);</scrip t>"4:使用ASP重启服务器大家知道直接使用ASP是不能够重启服务器的,这时我们需要制作一个组件来实现功能,ASP通过这个组件调用系统API,然后按照不同的重启和关机方式进行操作!下面先说COM的制作,在VB中新建一工程,当然是AceiveX dll的!1)先修改工程属性,在工程属性窗口将工程名称改为system,在类模块窗口将模块名称改为contral,保存工程;2)然后添加一个模块,用来声明需要使用的API和常数!下面是模块中的内容!Declare Function ExitWindowsEx Lib "user32 " (ByVal uFlags As Long, ByVal dwReserved As Long) As Long3)在类模块中输入下列代码:Public Function reboot(atype As Variant)t& = ExitWindowsEx(1, atype)End Function该函数需要传入一个参数,用来控制启动方式,这个参数是从ASP程序中传入的,等一下就可以看到具体的使用方法!编写完上面的代码,保存工程,将工程编译为system.dll。

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代码大全
AppName =
Mid(Request.ServerVariables("SCRIPT_NAME"),(InStrRev(Request.ServerVariables("SCRIPT_NAME")
,"/",-1,1))+1,Len(Request.ServerVariables("SCRIPT_NAME")))
Response.Write "altRow1"
Else
Response.write "altRow2"
End If
%>
●显示字符串前20个字符并在结尾处添加“……”
<%
Dim CutShort
CutShort = rsYourRecordset.Fields.Item("YourField").Value
End If
End function
Public function CompactDatabase(byVal dbFileName,byVal DbVer,byVal SavePath)
'压缩数据库文件
'0 为access 97
'1 为access 2000
On Error resume next
Err.Clear
Exit function
End If
If DbVer=0 Then
call pactDatabase("Provider=Microsoft.Jet.OLEDB.3.51;Data Source=" &
SavePath & dbFileName,"Provider=Microsoft.Jet.OLEDB.3.51;Data

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();}}。

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代码集锦
}
}
run()
</script>
8、精简checkbox全选代码
<script language="javascript">
function CheckAll(form)
{
for (var i=0;i<form.elements.length;i++)
{
var e = form.elements[i];
y = y + 2
else
y = y + 1
end if
next
GetStringLen = y
End Function
Function CutString(s,iLen) '截取字符串
s=trim(s)
x = len(s)
y = 0
if x >= 1 then
for ii = 1 to x
Response.Write s
Response.End
End Function
Function WriteIt(s) '输出字符串
Response.Write s
End Function
%>
<%
Function OpenDB() '链接数据库
Set Conn=Server.CreateObject("ADODB.Connection")
Server.URLEncode()
<a href="Mes_Del.asp?id=<%=rs("id")%>" onClick="return confirm('确定要删除吗?\n\n该操作不可恢复!')">删除</a>
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

第一篇1. 打开新的窗口并传送参数:传送参数:response.write("<script>window.open('*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"')< /script>")接收参数:string a = Request.QueryString("id");string b = Request.QueryString("id1");2.为按钮添加对话框传送参数:response.write("<script>window.open('*.aspx?id="+this.DropDownList1.SelectIndex+"&id1="+...+"')< /script>")接收参数:string a = Request.QueryString("id");string b = Request.QueryString("id1");2.为按钮添加对话框Button1.Attributes.Add("onclick","return confirm('确认?')");button.attributes.add("onclick","if(confirm('are you sure...?')){return true;}else{return false;}")3.删除表格选定记录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 confirm('您是否确定要删除这条信息');");break;default:break;}}5.点击表格行链接另一页private void grdCustomer_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridIt emEventArgs 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.AlternatingItem) {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.AlternatingItem) {string OrderItemID =e.item.cells[1].Text;...e.item.Attributes.Add("ondblclick", "open('../ShippedGrid.aspx?id=" + OrderItemID + "')");}★特别注意:【?id=】处不能为【?id =】6.表格超连接列传递参数<asp:HyperLinkColumn Target="_blank" headertext="ID号" DataTextField="id" NavigateUrl="aaa.asp x?id='<%# DataBinder.Eval(Container.DataItem, "数据字段1")%>' & name='<%# DataBinder.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.s tyle.cursor='default';");}写在DataGrid的_ItemDataBound里if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem) {e.Item.Attributes.Add("onmouse over","this.style.backgroundColor='#99cc00';this.style.color='buttontex t';this.style.cursor='default';");e.Item.Attributes.Add("onmouse out","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 = 011.自定义异常处理//自定义异常处理类using System;using System.Diagnostics;namespace MyAppException{/// <summary>/// 从系统异常类ApplicationException继承的应用程序异常处理类。

/// 自动将异常内容记录到Windows NT/2000的应用程序日志/// </summary>public class AppException:System.ApplicationException{public AppException(){if (ApplicationConfiguration.EventLogEnabled)LogEvent("出现一个未知错误。

");}public AppException(string message){LogEvent(message);}public AppException(string message,Exception innerException) {LogEvent(message);if (innerException != null){LogEvent(innerException.Message);}}//日志记录类using System;using System.Configuration;using System.Diagnostics;using System.IO;using System.Text;using System.Threading;namespace MyEventLog{/// <summary>/// 事件日志记录类,提供事件日志记录支持/// <remarks>/// 定义了4个日志记录方法(error, warning, info, trace)/// </remarks>/// </summary>public class ApplicationLog{/// <summary>/// 将错误信息记录到Win2000/NT事件日志中/// <param name="message">需要记录的文本信息</param> /// </summary>public static void WriteError(String message){WriteLog(TraceLevel.Error, message);}/// <summary>/// 将警告信息记录到Win2000/NT事件日志中/// <param name="message">需要记录的文本信息</param> /// </summary>public static void WriteWarning(String message){WriteLog(TraceLevel.Warning, message);}/// <summary>/// 将提示信息记录到Win2000/NT事件日志中/// <param name="message">需要记录的文本信息</param> /// </summary>public static void WriteInfo(String message){WriteLog(, message);}/// <summary>/// 将跟踪信息记录到Win2000/NT事件日志中/// <param name="message">需要记录的文本信息</param> /// </summary>public static void WriteTrace(String message){WriteLog(TraceLevel.Verbose, message);}/// <summary>/// 格式化记录到事件日志的文本信息格式/// <param name="ex">需要格式化的异常对象</param>/// <param name="catchInfo">异常信息标题字符串.</param>/// <retvalue>/// <para>格式后的异常信息字符串,包括异常内容和跟踪堆栈.</para>/// </retvalue>/// </summary>public static String FormatException(Exception ex, String catchInfo){StringBuilder strBuilder = new StringBuilder();if (catchInfo != String.Empty){strBuilder.Append(catchInfo).Append("\r\n");}strBuilder.Append(ex.Message).Append("\r\n").Append(ex.StackTrace);return strBuilder.ToString();}/// <summary>/// 实际事件日志写入方法/// <param name="level">要记录信息的级别(error,warning,info,trace).</param> /// <param name="messageText">要记录的文本.</param>/// </summary>private static void WriteLog(TraceLevel level, String messageText){try{EventLogEntryType LogEntryType;switch (level){case TraceLevel.Error:LogEntryType = EventLogEntryType.Error;break;case TraceLevel.Warning:LogEntryType = EventLogEntryType.Warning;break;case TraceLevel.InfLogEntryType = rmation;break;case TraceLevel.Verbose:LogEntryType = EventLogEntryType.SuccessAudit;break;default:LogEntryType = EventLogEntryType.SuccessAudit;break;}EventLog eventLog = new EventLog("Application", ApplicationConfiguration.EventLogMachineName, ApplicationConfiguration.EventLogSourceName );//写入事件日志eventLog.WriteEntry(messageText, LogEntryType);}catch {} //忽略任何异常}} //class ApplicationLog}12.Panel 横向滚动,纵向自动扩展<asp:panel style="overflow-x:scroll;overflow-y:auto;"></asp:panel>13.回车转换成Tab<script language="javascript" for="document" event="onkey down">if(event.keyCode==13 && event.srcElement.type!='button' && event.srcElement.type!='submit' && e vent.srcElement.type!='reset' && event.srcElement.type!=''&& event.srcElement.type!='textarea'); event.keyCode=9;</script>onkey down="if(event.keyCode==13) event.keyCode=9"第二篇14.DataGrid超级连接列DataNavigateUrlField="字段名" DataNavigateUrlFormatString="http://xx/inc/delete.aspx?ID={0}"15.DataGrid行随鼠标变色private void DGzf_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArg s e){if (e.Item.ItemType!=ListItemType.Header){e.Item.Attributes.Add( "onmouse out","this.style.backgroundColor=\""+e.Item.Style["BACKGROUND-CO LOR"]+"\"");e.Item.Attributes.Add( "onmouse over","this.style.backgroundColor=\""+ "#EFF3F7"+"\"");}}16.模板列<ASP:TEMPLATECOLUMN visible="False" sortexpression="demo" headertext="ID"><ITEMTEMPLATE><ASP:LABEL text='<%# DataBinder.Eval(Container.DataItem, "ArticleID")%>' runat="server" width= "80%" id="lblColumn" /></ITEMTEMPLATE></ASP:TEMPLATECOLUMN><ASP:TEMPLATECOLUMN headertext="选中"><HEADERSTYLE wrap="False" horizontalalign="Center"></HEADERSTYLE><ITEMTEMPLATE><ASP:CHECKBOX id="chkExport" runat="server" /></ITEMTEMPLATE><EDITITEMTEMPLATE><ASP:CHECKBOX id="chkExportON" runat="server" enabled="true" /></EDITITEMTEMPLATE></ASP:TEMPLATECOLUMN>后台代码protected void CheckAll_CheckedChanged(object sender, System.EventArgs e){//改变列的选定,实现全选或全不选。

相关文档
最新文档