asp.net常用代码.pdf

所需积分/C币:1 2012-10-04 10:39:07 317KB PDF
13
收藏 收藏
举报

asp.net常用代码.pdf
并执行数据绑定 MyDataGrid. Data Source=ds. Tables("student").DefaultView MyData Grid Data Bind( End Sub </script> command方式 cscript language="VBrunat=server"> Dim conn as new sqlconnection( Configuration Settings. appSettings("sql constr " ) "以下为页面载入事件,每当页面打开时执行下面代码 Sub Page_ Load(Sender As object, E As Eventargs) Dim My Command As Sqlcommand'定义用于对数据库执行的对象 Conn. Open 创建 command对象,该对象在创建时需要两个参数第一个是对数据库操作的语句,每二个是使用的连接 My Command= New Sqlcommand("select* from t student Conn 设置 Data grid对象的 Data Source属性为Ds屮的 student表 并执行数据绑定 My Data Grid Data Source=My Command. executereadero Data Grid Data Bindo MyConnection Close() End sub </script> 7、写入数据库 Dim conn as new sqlconnection( Configuration Settings App Settings ("sql constr ) Sub butinsert click(Src As Object, E As EventArgs) Dim MyCommand As Salcommand'定义用于对数据库执行的对象 Dim StrSql As String'定义一个用于保存SQL语句的字符串 连接并打开数据库 ConnOpen( 构造一个冋数据库中插入数据的SQL语句 Strsql="insert into t student(s number, s name department sex, birth day, polity )values Strsql & txtNumbertext Strsql & txtName text StrSQL &=ddlDepartment. selecteditem. text StrSql&=ddlSex selecteditem text strsql &=txt Birthday. text strsql &=ddl Polity. selecteditem text &" 创建 command对象,该对象在创建时需娈两个参数第一个是对数据库操作的语句,每二个是使用的连接 MyCommand = New Sqlcommand(strsql, Conn) 调用 My Command对象的 Execute NonQuery()方法向SQL数据为中写入数据 MyCommand. ExecuteNonQueryo) 关闭 My Connection连接 Conn Close( 调用子过程 Data Bind(方法重新绑定数据 Data bind () End sub 8、更新数据库记录 Dim conn as new sqlconnection( Configuration Settings App Settings" sql constr ) Sub butupdate click(Src As object, E As EventArgs) Dim My Command As Sqlcommand"定义用于对数据库执行的对象 Dim Strsql as string'定义一个用于保存SQL语句的字符串 连接并打开数据库 Conn Open() 杓造一个向数据库中插入数据的SQL语句 Strsql =update t student set StrSql&=s name=& txtName text StrSQL &="department=&ddI Department. selecteditem text Strsql&=sex=& ddlSex selecteditem text strsql &="birthday=& txt Birthday. text strsq &="polity=& ddlPolity selecteditem text strsql&="where s number=& txt Number. text 创建 command对象,该对象在创建时需要两个参数第一个是对数据库操作的语句,每二个是使用的连接 My Command=New SqlCommand (StrSql, Conn) 调用 MyCommand对象的 ExecuteNon Query)方法向SoL数据为中写入数据 MyCommand ExecuteNonQuery( Message InnerHtml ="<b>Record updated</b: Catch EXc As SQLException Message InnerHtml="ERROR: Could not update record Message Style color")=red End Try 关闭Conn连接 Conn. Close 调用子过程 Data bind()方法重新绑定数据 Data Bindo End sub 9、删除数据库记录 Dim cann as new sqlconnection( Configuration Settings App Settings(sql_constr ) Sub but Delete click(Src As Object, E As EventArgs) Dim MyCommand As sqlcommand'定义用于对数据库执行的对象 Dim StrSql As String"定义一个用于保存SQL语句的字符串 连接并打开数据库 Conn. Open 构造一个向数据库中插入数据的SQL语句 Strsql=Delete From t student Where s number=& txtNumber text "创建 command对象,该对象在创建时需要两个参数第一个是对数据库操作的语句,每二个是使用的连接 MyCommand =New Sqlcommand(strsql conn) 调用 My Command对象的 ExecuteNon Query()方法向SQL数据为中写入数据 MyCommand. ExecuteNonQueryo Message InnerHtml ="<h>Record Deleted</b> Catch EXc As SQLException Message InnerHtml ="ERROR: Could not delete record Message Style (" color )=red End Try 关闭Conn连接 Conn. Close 调用子过程 Data bind()方法重新绑定数据 Data Bindo End sub 10、给 Dropdownlist控件添加 On SelectedIndexChanged事作驱动 casp: Dropdownlist runat="server"id="City" Autopostback="trueO tedIndex changed="city selected"> 11、利用 Data grid控件的 Oneditcommand对象、 Editcommand colum对象、 Button Column对象、 Boundcolumn对象制作 ASP: Data Grid id="My Data Grid DataKey Field="link id Width=100% HeaderStyle-BackColor="#aaaadd OnEditcommand="MyData Grid edit OnCancel Command="MyData Grid_ Cancel OnUpdate Command="MyData Grid_ Update On Delete Command="My Data Grid Delete Auto Generate Columns="False"runat="server> <Columns> <asp: Editcommand column edittexte"编辑" Cancel Text="取消" Update Text="更新" ItemStyle-Wrap="fale"/ <asp: Button Column Text="I FA "CommandName"Delete"Item Style-Wrap="false"/> <asp: Boundcolumn headertext="网站编号" Data Field=" link id" ReadOnly="True"/> < asp: Bound Column Header Text="例站名称" DataField=" sitename"/ <asp: Boundcolumn header Text="网站地址" Data Fied="URL" asp: Boundcolumn headertexta"网站简介" Data Field-"ntro" <asp: Boundco| umn header text="网站评分" DataField=" grade <asp: Boundcolumn headertext="提交时间" Data Field=" 'submit date" Readonly="Tue"/> /Columns> </ASP: Data grid> 12、利用 Data list控件的 Alternatingltem Template对象、 Header Template对象、 Item Template对象、 Separator Template对象分栏 <asp: DataList id=MyData List"width=100% RepeatDirection=Horizontal"RepeatColumns="3 Alternatingltem Style-Back Color=#D1D1d1 runat="server> <HeaderTemplate> <h4a!n=" center">网络导航</h4><hr> </Header Template> <Item Template> <b><%# Container. Dataltem( sitename)%></b> cbrskx jihi adhe : <asp: Hyperlink Text='<%#t Conta iner Dataltem("url )%>navigateurl='<%"httP: //"& container. Dataltem("url")%> Target=blank "runat="server"/> br>网站评分:<%井 Container. dataltem(" grade")% <p>< asp: HyperLink Text="【详细】" NavigateUr='<‰#"cg03.asp? link id="& Container. Dataltem("nki")%' larget=" blank" runat="server> </Item Template> <Alternatingltem Template> <i><%# Container. Dataltem("sitename)%></i> <br>网站网址<asp:HyperLinkText=<%#Container.Dataltem(URL‰Navigateuri='<%#thttp://&container.Dataltemurl")‰ Target="blank"runat="server"/> <br>网站评分:<% Container: DataItem(" grade") <p><asp: HyperLink Text="( i !H ]" NavigateUrl='%#"7-5.aspx?link_id="& Conta iner. Dataltem("link id")%>'Target="blank unat=server/> </Alternatingltem Template> <Separator Template> <img src="redbar. jpg> </SeparatorTemplate> <footerTemplate> <hr>< p align=" center">如有优秀站点,欢迎向我推荐。</p> </footer Template> </asp: DataList> 13、新闻展示页面 Datalist控件的插入 <asp: DataList runat=server" ID=dINews1> <itemtemplate> <table width=95% border=o"align="center"cellpadding=0"cellspacing="0> <tr> <td width=160> <a href=<%## Data Binder Eval( Container. Dataltem, " id", "showjieshizixun aspx?id=0] %>target="blank"> <% Data Binder Eval( Container. Dataltem, title)%> <td width=30><div align=right"><img src=images/new. gif width=28 height=11 ></div></td> /tr> </table> <itemtemplate> </asp: Datalist> 14、弹出对话框 Response. Write("< script language= Javascript> alert'出现早常错误)</s"+" cript〉") 15、投票查看结果面页 <% import namespace="system. data% <% import namespace="system. data sqlclient%> % Page Language=VB ContentType=text/html%> <> <head> metahttp-equiv="content-type"content=Text/html;charset=gb2312> <tte>无标题文档</ title> <link href= Style. css rel="stylesheet type=text/css> <head> <body> <l-#include virtual="header. inc-> <table width=776 border=0"align="center" cellpadding=o"cellspacing=0"> <tr> <td> <Form runat="server> 得祟情况 <BLOCKQUOTE> <asp: datagrid runat="server"ID="My Grid Header - Back color="#336699 AlternatingltemStyle-Back Color="#E4E8EF Bordercolor ="black CellPadding=2 CellSpacing="0 Auto GenerateColumns="false"> <columns> <asp: boundcolumn data Field="景点" Header Text="景点" Header Style -Fore Color="旰FFF <asp: bounds| umn data field="票数" Header Text="票数" Headerstyle- Forecolor="#FFFF tem Style -HorizontalAlign="right"/> <asp: boundcolumn data field="得票率" Header Text="得票率" HeaderStyle-Fore Color="#FFF"/> </columns> </asp: datagrid></ BLOCKQUOTE </Form> </td> </tr> </table> #include virtual="footer inc-> </body> </html> <script runat="server> Sub Page Load( Src As Object, E As EventArgs) Dim conn as new sqlconnection( Configuration Settings App Settings("sql constr ))'E Connection Xf 3t If Not is post Back then Dim Adpt as sqldataAdapter Dim Ds as dataset Dim SQL As string 打开数据库连接 Conn. Open 读取数据并填充到DS中表名为Vote SQL =Select From Vote Adpt New sqlDataAdapter( SQL, Conn Ds= New Dataset Adpt. Fill(Ds, Vote") 产生「得票率」栏位 Dim Table l As data Table=Ds Tables" vote") Table1 Columns add( New data column("得票率", GetType( String)) gettype(:获得数据类型 Dim I As Integer, Total As Long 计算总票数 For i=o to table1. Rows. Count-1 Tota|+= Table1Rows().tem("票数") +=:表示连加,如:A+=1表示A=A+1 =:表示连减 Next If Total=o then total= 1 计算得票率,并且产生比例横条图 For 1=0 To table1. Rows. count-1 Dim rate= Table1.Rows(0).tem("票数")/Tota Dim RatehTML As string Dim Rate value As String RateHTML =<IMG SRC=100. gif Height=16 Width=& Rate*400 &"Align=TextTop> Rate Value ="(" FormatNumberRate* 100, 2)& % formatnum ber(数值,小数位数):四舍五入 Table1RoWs()tem("得票率")= RateHTML& RateValue Next MyGrid Data Source = Ds. Tables( Vote ).Defaultview MyGrid Data Bind( Conn. Close End if End sub 16、将读取的旅游景点项目自动绑定到 Radiobutt! enlist控件上 Sub Page Load(sender As object, e As EventArgs If Not ls PostBack then Dim Rd as sqlData Reader SQL As String Conn Open() SQL = Select * From Vote dim cmd as sqlcommar Cmd= New sqlCommand( SQL, Conn Rd= Cmd. ExecuteReadero While rd Reado Candidate Items. ado( Rd item("世界奇景")) End while Conn Close( End If End sub 17、图形访客计数器 <% Import Namespace="System. I0"%> <HTML> <BODY BGCOLOR=WHITE> < CENTER><H2> Png Count2aspx-图形访客计数器第二版<HRx/H2> 您是本站第< mg sro="№ um ToPng.spX? counter=<%= counter%"Agn= TextTop>位贵宾! /BODY> </HTML> <script Language="VB runat="server"> Dim counter as long=1宣告一个计数器变数 Sub Page Load(sender As object, e As EventArgs) 进行锁定,防止非同步更新 Application Lock Dim Path Name As string= Server MapPath ("counter.txt") If file exists( Pathname)Then'判断 counter. txt是存在 读取 counter. txt档案中的计数器,然後指定给 counter变数 Dim s Reader as streamReader sReader New StreamReader( PathName, Encoding. Default Dim s as stril S=rEader. ReadLineo Not s is Nothing Then ounter=CLng(S)+1′先加一,再指定给 counter变数 End If rEader. Close End仟 将计数器的值写回 counter. txt档案 Dim writer As stream writer wRiter New StreamWriter( PathName, False, Encoding. Default Writer. Write( CStr(counter)) wRiter. Flush( wRiter. Closel ′解除锁定 Application. Un Lock End sub </script> 18、购物页 cart. aspx页的设计 1.安插 Data Grid控件,详细代码如下 <asp: Datagrid ID=dg Car runat="server" Auto Generate Columns=false Border color="#bcc9e1 Border Width= 1 CellPadding=3 ItemStyle-Fore Color=#999999 Datakey Field=pno> <columns> <asp: boundcolumn header Text="商品名称" Data Field="书名" Item Style-Width="240"></asp: boundcolumn> asp: boundcolumn Header Text="市场价" Data field="定价" Data FormatString="{0}元"></asp: oundcolumn> <asp: boundcolumn header Text="优惠价" Data Field="售价" Data Formatstring="{o}元"</asp: boundcolumn> <asp: templatecolumn Header Text=数量"> <itemtemplate> <asp: textbox size=1 id="Qty"runat="server text=<%# Databinder eval(container data item "qty)%>7> </itemtemplate> </asp: templatecolumn> < asp: boundcolumn Header Text="市场价小计" Data field=" saletotal" Data Formatstring="{0:c}"></asp: boundcolumn> <asp: oundcolumn headertext="优惠价小计" Data Field=" realtotal" Data Formatstring="o:c}"></asp: boundcolumn> < asp: templatecolumn Header Text="删除"> <itemtemplate> <asp: checkbox runat="server"ID="del 7> </itemtemplate> /asp: templatecol umn> </columns> c/asp: Datagrid> 插相应Labe标签、按钮,并给出按钮的单击事件驱动过程 <asp: abel runat=" server"|D=" blsaletotal"/‘接收市场价汇总 < asp: label runat" server"|D=" blrealtotal"/‘接收优惠价汇总 < asp: label ID=bljs" runat=" 'server"x</asp:abel>‘接收共节省 < casp: imagebutton ID=" mgbutReCar" Imageurl= mages/ reAr. gif" runat=" server" Onclick=" imgbutRe Car click"/>‘重新计算 <asp: imagebutton ID="imgbut GoBank"ImageUrl=images/ GoBank git runat="server"/> 去牧银台 <asp: imagebutton ID=" imgbut clear cart" ImageUrl==" images/ Clearcar:gif" runat=" server'" On Click=" imgbutclear Cart click"/>‘清空购物车 3.参考代码 script runat="server"> Sub Page Load(Src As Object, E As EventArgs) If not is postback then 取得用户要加入购物书的商品的ID Dim product as string = request QueryString("pno") 判断如果是用户所购买的第一件崗品的话则那立一个 hashTable 否则从 session中将已经存在的 hashTable取回 Dim hash as hash table IF Session ("car")is nothing then hash New hash Table Hash Session ("car") End if 判断用户所选购的商品是否已经存在于购物车中 如果不存在则将其加入购物车,如果存在则在原有数据上加1 if Not Hash ContainsKey(product)then Hash. Add(product, 1) else hash item(product)+=1 end if session "car =hash end if End Sub Sub bind dgproduct( Dim i as integer dim x as string 取得 session中的 hashTable dim hash as hashtable Hash Session (car) 将所有选购的商品构造成为一个字符串 dim Products As string products="( For Each X in hash keys

...展开详情
试读 12P asp.net常用代码.pdf
立即下载 身份认证后 购VIP低至7折
一个资源只可评论一次,评论内容不能少于5个字
您会向同学/朋友/同事推荐我们的CSDN下载吗?
谢谢参与!您的真实评价是我们改进的动力~
  • 分享宗师

关注 私信
上传资源赚钱or赚积分
最新推荐
asp.net常用代码.pdf 1积分/C币 立即下载
1/12
asp.net常用代码.pdf第1页
asp.net常用代码.pdf第2页
asp.net常用代码.pdf第3页

试读结束, 可继续读1页

1积分/C币 立即下载