ASP.NET 揭秘 第二章用Web Server Controls建立Forms

    技术2022-05-11  148

    Chapter 2. Building Forms with Web Server Controls 一、Building Smart Forms  Using Label Controls(标签)   The Label control has one important property: Text,支持AutoPostBack属性   The contents of a Label control are rendered within a <span> tag (you can see this if you click View Source on your browser).   Note: The LiteralControl is very similar to the Label control except for the fact that it does not render <span> tags. You can use the LiteralControl within the <title> tag of a page.  Using the TextBox Control(文本)   The TextBox control can render any one of three different HTML tags,支持AutoPostBack属性   文本内容检验类:CrossSiteScriptingValidation,   要取消校验,在页头上添加指示<%@ ValidateRequest="False" %>,或在Concfig文件中加入<pages validateRequest="false" />  Using Button Controls(按钮)   Button— Displays a standard HTML form button   默认按钮<input type="Submit">, 有一个灰边框.   事件Click,Command,当Button按下后,同时发生Click和Command事件,两个事件的区别是Command事件有参数 CommandName and CommandArgs    <asp:Button Text="Add 5"      CommandName="Add"      CommandArgument="5"      OnCommand="Button_Command"      Runat="Server"/>   ImageButton— Displays an image form button   同Button比,多了ImageAlign,ImageURL属性,及AlternativeText决定图片无法显示时的提示信息.   事件参数ImageClickEventArgs,有x,y当前的坐标位置.    Sub ImageButton_Click( s As Object, e As ImageClickEventArgs )      Select Case e.X        Case Is < 95          lblMessage.Text = txtSomeText.Text.ToUpper()        Case Is < 185          lblMessage.Text = txtSomeText.Text.ToLower()        Case Is < 289          lblMessage.Text = ""      End Select    End Sub   LinkButton— Displays a hypertext link.   The LinkButton control does not work on browsers that do not support JavaScript (or browsers that have JavaScript disabled).   Sub LinkButton_Click( s As Object, e As EventArgs )     Dim RanNum As New Random     Select Case RanNum.Next( 4 )       Case 0         lblFortune.Text = txtUsername.Text & ", good things are coming!"       Case 1         lblFortune.Text = txtUsername.Text & ", you are doomed!"       Case 2         lblFortune.Text = txtUsername.Text & ", invest in Microsoft!"       Case 3         lblFortune.Text = txtUsername.Text & ", this book will change your life!"     End Select   End Sub  Using the RadioButton and RadioButtonList Controls(单选)   The RadioButton Control   你可以向页面上任意添加个别的RadioButton,它们通过GroupName进行分组,每一个分组在同一时间只能有一个被选中. 通过Checked属性,设置或检查是否选中.   *每一组中的多个RadioButton仅对应一个CheckedChanged事件,并且,该事件在某一RadioButton选中时发生.页面初始化时Checked=Ture,不会触发该事件.   *RadioButton支持AutoPostBack属性,另外AutoPostBack属性需要客户端脚本的支持,如果Browser不支持JavaScrpit,那么AutoPostBack就不能正常工作.   The RadioButtonList Control   RadioButtonList是包含许多个独立的RadioButton.通过SelectedIndex, SelectedItem, SelectedValue进行识别选中项,通过SelectedIndex, SelectedValue设置默认选中项.RadioButtonList支持AutoPostBack属性.   建立RadioButtonList的三种方法:    1>.页面中直接定义;2>.在代码中向ListItemCollection集合中添加成员;3>.使用数据绑定DataSouce,DataBind;   通过RepeatLayout, RepeatDirection,RepeatColumns对RadioButtonList的外观进行控制.   *对于采用数据绑方式的RadioButtonList,可以使用DataTextFormatString对其进行格式化,用DataTextField ,DataValueField对Text和Value进行区分.   数据格式化    <asp:RadioButtonList      ID="radlFavoriteColor"      DataTextFormatString="The color is {0}"      Runat="Server">    </asp:RadioButtonList>   数据绑定    Dim dtblStates As New DataTable    Dim drowNewState As DataRow    dtblStates.Columns.Add(New DataColumn( "StateName", GetType( String ) ) )    dtblStates.Columns.Add(New DataColumn( "StateAbbr", GetType( String ) ) )    drowNewState = dtblStates.NewRow()    drowNewState( "StateName" ) = "California"    drowNewState( "StateAbbr" ) = "CA"    dtblStates.Rows.Add( drowNewState )    drowNewState = dtblStates.NewRow()    drowNewState( "StateName" ) = "Massachusetts"    drowNewState( "StateAbbr" ) = "MA"    dtblStates.Rows.Add( drowNewState )    drowNewState = dtblStates.NewRow()    drowNewState( "StateName" ) = "Ohio"    drowNewState( "StateAbbr" ) = "OH"    dtblStates.Rows.Add( drowNewState )    radlStateOfResidence.DataSource = dtblStates    radlStateOfResidence.DataTextField = "StateName"    radlStateOfResidence.DataValueField = "StateAbbr"    radlStateOfResidence.DataBind   控制列表样式    <Script Runat="Server">    Sub Page_Load       Dim intCounter As Integer       Dim strSomeListItem As String       If Not IsPostBack Then         For intCounter = 1 To 50           strSomeListItem = "Radio Button " & intCounter           radlRadioButtons.Items.Add( strSomeListItem )         Next       End If    End Sub    </Script>    <asp:RadioButtonList      ID="radlRadioButtons"      RepeatColumns="3"      RepeatDirection="Vertical"      Runat="Server"/>  Using the CheckBox and CheckBoxList Controls(复选)   The CheckBox Control(同Radio)   The CheckBoxList Controls (同Radio)  Using the DropDownList Control(下拉框)  类似于RadioButtonList,由好多可选的元素构成,且同一时刻只能有一个被选中,与RadioButtonList不同的是它显示为单行的弹出式列表,包含ListItemCollection集合.  更多可参考ListItemCollection.  Using the ListBox Control(列表框)  支持单选和复选SelectionMode属性,Rows属性指定列表行数,默认为4.  包含一个Items的集合 二、Controlling Page Navigation  Submitting a Form to a Different Page   If you use the server-side version of the <form> tag, you cannot post a form to a different page (the server-side form tag does not have an Action property).   You can, if you have a pressing need, post a form to a new page by using the standard HTML form tags instead of ASP.NET controls   You also can use the Form collection of the HTTPRequest class to grab form data. The difference between the Params and Form collections is that the Params collection also represents QueryStrings, ServerVariables, and Cookies.   Form.aspx   <form Method="Post" Action="Results.aspx">   Results.aspx   <Script Runat="Server">    Sub Page_Load      lblUsername.Text = Request.Params( "Username" )      lblComments.Text = Request.Params( "Comments" )   End Sub   </Script>  Using the Redirect() Method   So, the question remains, how do you transfer a user to a new page after the user has successfully completed a form?   The best way to transfer the user is to use the Response.Redirect() method.   Redirect.aspx   <Script Runat="Server">    Sub Button_Click( s As Object, e As EventArgs )       ' Save Form Data to Database Table       Response.Redirect( "ThankYou.aspx" )    End Sub   </Script>  Working with the HyperLink Control   You can link one ASP.NET page to another by adding a HyperLink control to a page.   属性:ImageUrl,NavigateUrl,Target(The target window or frame for the link. Possible values are _top, _self, _parent, _search, or _blank.),Text    HyperLink.aspx   <Script Runat="Server">    Sub Page_Load      If TimeOfDay > #5:00pm# Then          lnkHelpLink.NavigateUrl = "AfterHoursHelp.aspx"          lnkHelpLink.Text = "After Hours Help"       Else          lnkHelpLink.NavigateURL = "Normalhelp.aspx"          lnkHelpLink.Text = "Help"       End If    End Sub   </Script> 三、Applying Formatting to Controls  Base Web Control Properties(基本属性) AccessKey/BackColor/BorderStyle/BorderWidth/Font-Bold/Font-Italic/Font-Name/Font-Names/Font-Overline/Font-Size/Font-Strikeout/Font-Underline/ForeColor/Height/TabIndex/ToolTip/Width  上面的部分属性可以通过CssClass属性来设置.  可以在运行时动态修改这些属性   <%@ Import Namespace="System.Drawing" %>   <Script Runat="Server">    Sub dropBackColor_SelectedIndexChanged( s As Object, e As EventArgs )     Dim strBackColor As Color      strBackColor = Color.FromName( dropBackColor.SelectedItem.Text )      txtTextBox.BackColor = strBackColor    End Sub    Sub dropFontSize_SelectedIndexChanged( s As Object, e As EventArgs )      txtTextBox.Font.Size = FontUnit.Parse( dropFontSize.SelectedItem.Text )    End Sub   </Script>  Applying Styles to Web Controls(应用样式)  CssClass属性,可以在运行时动态修改CSS属性.   Style.aspx   <html>   <head>    <Style>    .myClass    {      text-align: justify;      font: 14pt Script;    }    </Style>    <title>Style.aspx</title>   </head>   <body>    <form Runat="Server">    <asp:Label      ID="lblLabel"      Width="10"      cssClass="myClass"      Text="this is some text"      Runat="Server"/>    </form>    </body>    </html>  The Style Class(样式类)   通过ApplyStyle应用样式,MergeStyle应用合并样式.   StyleClass.aspx   <%@ Import Namespace="System.Drawing" %>   <Script Runat="Server">    Sub Page_Load( s As Object, e As EventArgs )      Dim myStyle As New Style      myStyle.BackColor = Color.Yellow      myStyle.ForeColor = Color.Green      myStyle.BorderStyle = BorderStyle.Dashed      myStyle.BorderWidth = New Unit(4)      txtTextBox1.ApplyStyle( myStyle )      txtTextBox2.ApplyStyle( myStyle )      txtTextBox3.MergeStyle( myStyle )    End Sub   </Script>   <html>    <head><title>StyleClass.aspx</title></head>   <body>    <form Runat="Server">    <asp:TextBox      id="txtTextBox1"      BackColor="red"      Text="Here is some text!"      Runat="Server"/>    <p>    <asp:TextBox      id="txtTextBox2"      BackColor="red"      Text="Here is some text!"      Runat="Server"/>    <p>    <asp:TextBox      id="txtTextBox3"      BackColor="red"      Text="Here is some text!"      Runat="Server"/>    </form>   </body>   </html> 总结:本章讨论了基本的Web Controls,学习了怎样向ASP.NET页面添加类似于TextBox,DropDownList的Web Controls等,同时要学习了,这些Web Controls的事件处理过程.接着学习了多个ASP.NET页面如何工作,通过Response.Redirect方法进行页面跳转,同时也学习了如何使用HyperLink Control进行多个页面的链接.最后学习了,运用这些基本Web Controls的格式化属性对它们进行格式化,同时也学习了通过Cascading Style Sheet classes 进行格式化.

    最新回复(0)