92
Web Forms and Server Controls ASP.NET

Web Forms and Server Controls

Embed Size (px)

DESCRIPTION

Web Forms and Server Controls. ASP.NET. Using HTML Server Controls. All HTML tags can be changed into server-side tags using the attribute and value runat="server" Limited functionality compared to Web controls Provide output similar to their HTML counterparts To set the runat attribute: - PowerPoint PPT Presentation

Citation preview

Page 1: Web Forms and Server Controls

Web Forms and Server Controls

ASP.NET

Page 2: Web Forms and Server Controls

Using HTML Server ControlsUsing HTML Server Controls

• All HTML tags can be changed into server-side tags using the attribute and value runat="server"– Limited functionality compared to Web controls

– Provide output similar to their HTML counterparts

• To set the runat attribute:– Right-click on the HTML control and select the

command Run As Server Control or

– Type the attribute and value into the tag in HTML view, i.e.<input type="text" runat="server">

Page 3: Web Forms and Server Controls

HTML Server ControlsHTML Server Controls

• Similar to HTML Controls but run on the server• Divided into separate classes:– HTMLInputControl

– HTMLContainerControl

Page 4: Web Forms and Server Controls

HTML Server ControlsHTML Server Controls

Page 5: Web Forms and Server Controls

HTML Control Client-Side vs. Server-Side Event HandlersHTML Control Client-Side vs. Server-Side Event Handlers

• In HTML documents, client-side controls (i.e. scripts or procedures executing in JavaScript or VbScript) have events such as onClick and onChange– Associated with HTML client controls

• When an HTML Server control value has changed, the OnServerChange or OnServerClick event occurs

Page 6: Web Forms and Server Controls

The Line Continuation CharacterThe Line Continuation Character

Line continuation charactersLine continuation characters

• When writing code, never press <Enter> key in the middle of a statement within code behind the page

• Underscore (_) key preceded by a blank space allows the statement to be continued on next line

• Example:lblMaturity.InnerHtml = sngInvestment _

* (1 + sngRate / 36000) _ ^ (360 * intYears)

– (Single-line statement)

Page 7: Web Forms and Server Controls

ConcatenationConcatenation

• Joining of two or more strings into a single string using either of the operators "&" or "+"

• Formats:String1 & String2 -or- String3 + String4

• Examples:strString = "Welcome to " & "ASP.NET"

– Stores "Welcome to Visual Basic" into strStringlblArithmetic.InnerHtml = "11 + 7 = " _

& 11 + 7

– Stores "11 + 7 = 18" into lblArithmetic.InnerHtml

Page 8: Web Forms and Server Controls

HTML Server Control Event HandlersHTML Server Control Event Handlers

• Controls that support the OnServerChange event:

– HTMLInputCheckBox

– HTMLInputRadioButton

– HTMLInputHidden

– HTMLInputText

– HTMLTextArea

– HTMLSelect

• Controls that support the OnServerClick event:

– HTMLInputImage

– HTMLAnchor

– HTMLButton

– HTMLForm

Page 9: Web Forms and Server Controls

Starting a New Web FormStarting a New Web Form

1. Select Project from the menu bar

2. Select Add Web Form… from the Project menu– The "Web Form" icon will already be selected in the

Templates: frame of the "New Item" dialog window

3. Type the Name: for the new file – The extension ".aspx" will be added automatically

when the file is created

4. Click the <Open> button

Page 10: Web Forms and Server Controls

HTMLButton.aspxHTMLButton.aspx

Page 11: Web Forms and Server Controls

• Properties of the individual controls can be changed through "Properties" window

• The Style property (attribute) is modified using Style Builder dialog window (same as for style sheets)

• Additionally many properties can be changed by adding statements to the code behind the page– When page loads, or when an event occurs, such as a

button click

• Properties frequently are not the same for HTML server controls and ASP.NET server controls

PropertiesProperties

Page 12: Web Forms and Server Controls

"Font" Properties in Style Builder"Font" Properties in Style Builder

Page 13: Web Forms and Server Controls

"Position" Properties in Style Builder"Position" Properties in Style Builder

Page 14: Web Forms and Server Controls

HTMLButton.aspx (Page 1)HTMLButton.aspx (Page 1)

• Add the image header.jpg– Style property—Position tab

• Top=0; Left=0

• Add the image menu.gif– Style property—Position tab

• Top = 85; Left = 17

• Add the image waterfordgifts.jpg– Style property—Position tab

• Top = 38; Left = 134

Page 15: Web Forms and Server Controls

The ID and Name PropertiesThe ID and Name Properties

• The ID property is used to identify the control to the server for server-side processing

• The Name property identifies the control to scripts running on the client side

Page 16: Web Forms and Server Controls

HTMLButton.aspx (Page 2)HTMLButton.aspx (Page 2)

• Add a Label from the "HTML" tab in the Toolbox– Set attribute "runat = server" (right-click and select

command Run as Server Control)

– ID—lblTitle

– Name—(we will not be setting this property)

– Style• Font (Family=Trebuchet MS; Size=15)

• Position (Top=243; Left=139; Height=26; Width=365)

– Modify text by typing—"Select the gender of the gift recipient"

Page 17: Web Forms and Server Controls

HTMLButton.aspx (Page 3)HTMLButton.aspx (Page 3)

• Add a Button from the "HTML" tab in the Toolbox– Set attribute "runat=server"

– ID—btnMale

– Style (Top=278; Left=138; Height=27; Width=89)

– Value—"Male"

• Add a Button from the "HTML" tab in the Toolbox– Set attribute "runat=server"

– ID—btnFemale

– Style (Top=310; Left=138; Height=27; Width=89)

– Value—"Female"

Page 18: Web Forms and Server Controls

HTMLButton.aspx (Page 4)HTMLButton.aspx (Page 4)

• Add a Label from the "HTML" tab in the Toolbox– Set attribute "runat = server"

– ID—lblGiftIdeasWomen

– Style• Font (Family=Trebuchet MS; Size=12)

• Position (Top=275; Left=235; Height=210; Width=250)

Page 19: Web Forms and Server Controls

HTMLButton.aspx (Page 5)HTMLButton.aspx (Page 5)

• Label—lblGiftIdeasWomen – Create a bulleted list—

• Make-Up Brush

• Tyrone Bell

• Butterfly

• Balmoral Vase

• Abbey Clock

• Heart-Shaped Ring Holder

• Wellsley Picture

Page 20: Web Forms and Server Controls

HTMLButton.aspx (Page 6)HTMLButton.aspx (Page 6)

• Add a Label from the "HTML" tab in the Toolbox– Set attribute "runat = server"

– ID—lblGiftIdeasMen

– Style• Font (Family=Trebuchet MS; Size=12)

• Position (Top=275; Left=235; Height=210; Width=250)(Wait to set the Left position until all text is entered)

Page 21: Web Forms and Server Controls

HTMLButton.aspx (Page 6)HTMLButton.aspx (Page 6)

• Label—lblGiftIdeasMen – Create a bulleted list—

• Golf Ball

• Golf Club

• Male Golfer

• Letter Opener

• Business Card Holder

• Shamrock Paperweight

Page 22: Web Forms and Server Controls

ProceduresProcedures

• A procedure (Sub or Function)is a named grouping of one or more programming statements

• Create an event Sub procedure by double-clicking on the object in Design mode

• The Page_Load event occurs when the web page loads into the browser

• Example:Private Sub Page_Load( … ) Handles MyBase.Load

lblGiftIdeasMen.Visible = False

lblGiftIdeasWomen.Visible = False

End Sub

Page 23: Web Forms and Server Controls

The ServerClick EventThe ServerClick Event

• Occurs when an HTML Server Button (HTML Button with runat=server attibute set) is clicked

• Equivalent of Click event in VB .NET, but for an ASP.NET Web Server control

• Example:Private Sub btnMale_ServerClick( … ) Handles btnMale.ServerClick

End Sub

Page 24: Web Forms and Server Controls

The InnerHtml PropertyThe InnerHtml Property

• Modifies the contents of an HTML Label (or other) control

• May include HTML tags for formatting of the text• The Label is converted to a <div> tag with inserted

text in the rendering of an HTML document• Example:

lblTitle.InnerHtml = "<b>We have lots of gift ideas for men.</b>"

• The InnerText property (similar to InnerHtml) may only contain text elements, not formatting tags

Page 25: Web Forms and Server Controls

HTMLButton.aspx—Page_LoadHTMLButton.aspx—Page_Load

Private Sub Page_Load( … ) Handles MyBase.Load

lblGiftIdeasMen.Visible = FalselblGiftIdeasWomen.Visible = False

End Sub

Page 26: Web Forms and Server Controls

HTMLButton.aspx—btnMale_ServerClickHTMLButton.aspx—btnMale_ServerClick

Private Sub btnMale_ServerClick( … ) Handles btnMale.ServerClick

lblTitle.InnerHtml = "<b>We have lots of gift ideas for men.</b>"

lblGiftIdeasMen.Visible = TruelblGiftIdeasWomen.Visible = False

End Sub

Page 27: Web Forms and Server Controls

HTMLButton.aspx—btnFemale_ServerClickHTMLButton.aspx—btnFemale_ServerClick

Private Sub btnFemale_ServerClick( … ) Handles btnFemale.ServerClick

lblTitle.InnerHtml = "<b>We have lots of gift ideas for women.</b>"

lblGiftIdeasWomen.Visible = TruelblGiftIdeasMen.Visible = False

End Sub

Page 28: Web Forms and Server Controls

• An image is displayed on the Button instead of text– By default the image docks to the all sides on the

button, so it stretches if the button is resized

• There actually is no Image Button in the HTML tab of the Toolbox– Drop and drag an HTML Button from the Toolbox

– Then key the type attribute in the input tag, i.e.<input type="image">

HTML Image Button (Page 1)HTML Image Button (Page 1)

Page 29: Web Forms and Server Controls

• The src attribute names the path and filename of the image file displayed on the Button, i.e.<input type="image" src="male.gif">

• No value attribute is required since image replaces the text on the button

• All other functioning is the same as the HTML Button control

HTML Image Button (Page 2)HTML Image Button (Page 2)

Page 30: Web Forms and Server Controls

HTMLImageButton.aspxHTMLImageButton.aspx

Page 31: Web Forms and Server Controls

HTMLImageButton.aspxHTMLImageButton.aspx

• btnMale<input type="image" src="images/male.gif">

• btnFemale<input type="image" src="images/female.gif">

Page 32: Web Forms and Server Controls

The Value Property for a Text FieldThe Value Property for a Text Field

• Retrieves or modifies the values from HTML text field (text box) controls– The value attribute can be used to set the default

value for input controls such as a one-line text field or password box

• Used for HTML form controls rather than the Text property of ASP.NET server controls

• Examples:– txtUserName.Value– txtPassword.Value

Page 33: Web Forms and Server Controls

HTML Button ControlsHTML Button Controls

• Buttons usually call procedures when clicked

• Available are Submit, Reset, and the general Button

• Member of the HTMLInputControl Class, i.e.– <input type = "Submit">

– <input type = "Reset"> • Resets Form to default so runat="server" not applicable

– <input type = "Button">

• Default procedure for HTML Buttons is ServerClick event, i.e Private Sub btnSubmit_ServerClick( … ) Handles btnSubmit.ServerClick

Page 34: Web Forms and Server Controls

HTMLInputButton.aspxHTMLInputButton.aspx

Page 35: Web Forms and Server Controls

HTMLInputButton.aspx (Page 1)HTMLInputButton.aspx (Page 1)

• Add Text Field from "HTML" tab in Toolbox– Set attribute "runat = server"

– ID—txtUsername

– Style (Top=280; Left=145)

• Add Password Field from "HTML" tab in Toolbox– Set attribute "runat = server"

– ID—txtPassword

– Style (Top=310; Left=145)

Page 36: Web Forms and Server Controls

HTMLInputButton.aspx (Page 2)HTMLInputButton.aspx (Page 2)

• Add Submit Button from "HTML" tab in Toolbox– Set attribute "runat = server"

– ID—btnSubmit

– Style (Top=345; Left=150)

– Value—"Sign In"

• Add Reset Button from "HTML" tab in Toolbox– ID—btnReset

– Style (Top=345; Left=230)

Page 37: Web Forms and Server Controls

HTMLInputButton.aspx (Page 3)HTMLInputButton.aspx (Page 3)

• Add a Button from "HTML" tab in Toolbox– Set attribute "runat = server"

– ID—btnHelp

– Style (Top=345; Left=450)

– Value—"Help"

Page 38: Web Forms and Server Controls

HTMLInputButton.aspx—Page_LoadHTMLInputButton.aspx—Page_Load

Private Sub Page_Load( … ) Handles MyBase.Load

lblTitle.InnerText = "Please log into our Customer Support Area"

lblHelp.Visible = FalsebtnHelp.Visible = True

End Sub

Page 39: Web Forms and Server Controls

HTMLInputButton.aspx—Page_Load (Page 1)

HTMLInputButton.aspx—Page_Load (Page 1)

Private Sub btnSubmit_ServerClick( … ) Handles btnSubmit.ServerClick

lblHelp.Visible = False

If txtUsername.Text = "Course" And txtPassword.Text = "Technology" Then

lblTitle.InnerText = "You are authenticated"

Page 40: Web Forms and Server Controls

HTMLInputButton.aspx—Page_Load (Page 2)

HTMLInputButton.aspx—Page_Load (Page 2)

ElselblTitle.InnerText = "Please click on the Help button for help!"txtUsername.Text = ""txtPassword.Text = ""btnHelp.Visible = True

End If

End Sub

Page 41: Web Forms and Server Controls

HTMLInputButton.aspx—btnHelp_ServerClickHTMLInputButton.aspx—btnHelp_ServerClick

Private Sub btnHelp_Server_Click( … ) Handles btnHelp.ServerClick

lblTitle.InnerText = "Please log into our Customer Support Area"

lblHelp.Visible = TruebtnHelp.Visible = False

End Sub

Page 42: Web Forms and Server Controls

HTML Radio Button, Dropdown List, and Hyperlink Server ControlsHTML Radio Button, Dropdown List, and Hyperlink Server Controls

• CheckBoxes, RadioButtons and DropDown lists – Form fields that allow users to select from lists of

options

– Can retrieve their values using properties of the HTML form control

• Hyperlinks – Allow you to create links to other pages or to internal

targets within the same page

Page 43: Web Forms and Server Controls

The Checked Property of RadioButtonsThe Checked Property of RadioButtons

• Determines which RadioButton is Checked:If rdBridal.Checked = True Then

lblTitle.InnerHtml = "Celebrate your Wedding!"

imgTop.Src = "images/28.jpg"

End If

• Or:If rdBridal.Checked Then

lblTitle.InnerHtml = "Celebrate your Wedding!"

imgTop.Src = "images/28.jpg"

End If

Page 44: Web Forms and Server Controls

The RadioButton HTML Server ControlThe RadioButton HTML Server Control

Page 45: Web Forms and Server Controls

Dropdown HTML Server ControlDropdown HTML Server Control

• Created with the HTML <select> tag– <option> tags create each individual item

– A value attribute can be associated with each item in the list

• SelectedIndex property of the drop-down list box– A zero-based index indicating which item is selected

– When nothing has been selected the SelectedIndex property returns the value -1

• The Add method add items to the list dynamically in code when the page loads, or when an event occurs

Page 46: Web Forms and Server Controls

The IsPostback Page PropertyThe IsPostback Page Property

• Determines if the user has visited page before during the current session

• Important to know so that statements that initialize the page do not run again if page is revisited

• The _doPostBack function is generated automatically by ASP.NET– Passes to the Web server information concerning the

object that called an event and parameters passed to it

– The Boolean IsPostBack property recognizes if the page was visited previously from this information

Page 47: Web Forms and Server Controls

The IsPostback Page Property and the Add Method of the Select ControlThe IsPostback Page Property and the Add Method of the Select Control

• Example:If Not Me.IsPostBack Then

lblTitle.InnerHtml() = _

"Select gender of gift recipient."

imgProduct.Visible = False

ProductList.Visible = False

CatList.Items.Add("Gifts for Men")

CatList.Items.Add("Gifts for Women")

End If

Page 48: Web Forms and Server Controls

Dropdown HTML Server ControlDropdown HTML Server Control

Page 49: Web Forms and Server Controls

Anchors (Hyperlinks)Anchors (Hyperlinks)

• Creates a hyperlink to another Web document• Example:

<a href="http://www.tarastore.com" id="AMale" name="AMale" runat="server">Men</a>

• The HRef property can change the URL for an <a> tag in the code behind the page, i.e.AMale.HRef = "GiftsForMen.aspx"

AFemale.HRef = "GiftsForWomen.aspx"

AHome.HRef = "http://www.tarastore.com"

Page 50: Web Forms and Server Controls

The Hyperlink ControlThe Hyperlink Control

Page 51: Web Forms and Server Controls

Using ASP.NET Web Form ControlsUsing ASP.NET Web Form Controls

• Also known as Web Controls– Located on the Web Forms tab in the Toolbox

– Inherit from the Web Control class

• ASP.NET controls can be logically grouped into:– Web Form controls

– Rich controls

– Data controls

– Validation Controls

– Mobile Controls

Page 52: Web Forms and Server Controls

Syntax Differences for Assigning Text to a Label in Web Form ControlsSyntax Differences for Assigning Text to a Label in Web Form Controls

• Text is assigned to a Label (and other controls) using the Text property, not InnerHtml or InnerText

• Example:Label1.Text = "Welcome to ASP.NET"

– Web Form controls in ASP.NET follow a syntax that closely approximates that of Visual Basic .NET

Page 53: Web Forms and Server Controls

Syntax Differences for Assigning Color Values in Web Form ControlsSyntax Differences for Assigning Color Values in Web Form Controls

• Color is a class in .NET Framework derived from the System.Drawing.Color namespace– Assign the value using known colors referred to by

name, i.e.MyControl.BorderColor = System.Drawing.Color.Green

MyControl.BorderColor = Color.Green

Page 54: Web Forms and Server Controls

The Color.FromName() MethodThe Color.FromName() Method

• Returns a color value from the Color class• Values may be specific system-define color name or an

RGB hexadecimal color value as a string • Format:

ControlName.ColorProperty = Color.FromName("SystemDefinedColor")

• Examples:MyControl.BackColor = Color.FromName("Red")

MyControl.BackColor = Color.FromName("MenuText")

Page 55: Web Forms and Server Controls

Syntax Differences for Assigning Image Properties in Web Form ControlsSyntax Differences for Assigning Image Properties in Web Form Controls

• Image control class produces an <img> tag• Properties of the Image control are different from

HTML server controls as follows:– ImageURL—path to the image and filename; creates

the src property

– AlternateText—displays text when the image is not available; creates the alt property

– ImageAlign—provides the image alignment; creates the align property

Page 56: Web Forms and Server Controls

The Add Method for the DropDownList Web Form ControlThe Add Method for the DropDownList Web Form Control• Adds options (<option> blocks) to the DropDownList• Member of the Items collection of the• Example:

If Not IsPostBack Then dlCategory.Items.Add("Gifts") dlCategory.Items.Add("Jewelry") dlCategory.Items.Add("China and Crystal") dlCategory.Items.Add("Pottery") dlCategory.Items.Add("Clothing") dlCategory.Items.Add("Food") dlCategory.Items.Add("Books, Music, Video") dlCategory.Items.Add("Bridal")End If

Page 57: Web Forms and Server Controls

The SelectedIndex Property of the DropDownList Web Form ControlThe SelectedIndex Property of the DropDownList Web Form Control

• The SelectedIndex property is a zero-based index indicating which item in the DropDownList is selected

• When no item has been selected from DropDownList, the SelectedIndex property returns the value -1

• Example:Select Case dlCategory.SelectedIndex

Case 0

lblTitle.Text = _

"Let us help you find best gift!"

imgTop.ImageUrl = "images/21.jpg"

Page 58: Web Forms and Server Controls

ASPSelect.aspxASPSelect.aspx

Page 59: Web Forms and Server Controls

ASPSelect.aspxASPSelect.aspx

• In Design view, drag DropDownList control from "Web Forms" tab of Toolbox onto Form

• Set properties:– ID dlCategory

– Height 25

– Width 155

Page 60: Web Forms and Server Controls

ASPSelect.aspx—Page_LoadASPSelect.aspx—Page_Load

Private Sub Page_Load( … ) Handles MyBase.Load

If Not IsPostBack Then dlCategory.Items.Add("Gifts") dlCategory.Items.Add("Jewelry") dlCategory.Items.Add("China and Crystal") dlCategory.Items.Add("Pottery") dlCategory.Items.Add("Clothing") dlCategory.Items.Add("Food") dlCategory.Items.Add("Books, Music, Video") dlCategory.Items.Add("Bridal")End If

End Sub

Page 61: Web Forms and Server Controls

ASPSelect.aspx—Page_ClickASPSelect.aspx—Page_Click

• Enter the following code after the procedure header:Select Case dlCategory.SelectedIndex

Case 0

lblTitle.Text = "Let us help you find the best gift!"

imgTop.ImageUrl = "images/21.jpg"

Page 62: Web Forms and Server Controls

Panel Web Form ControlsPanel Web Form Controls

• The Panel control contains other controls and in the browser HTML creates a <div> block

• Another method for setting properties, i.e.wrapping, absolute positioning, font type, and scrollbars

• A Label control inserted into the Panel, creates a <span> tag in the rendered HTML code– Use the Text property to display the text

• Only allows for flow layout of elements– Use a Table or an HTML gridlayout

Page 63: Web Forms and Server Controls

ASPPanel.aspxASPPanel.aspx

The PanelThe Panel

Page 64: Web Forms and Server Controls

Literal Web Form ControlsLiteral Web Form Controls

• Used to write content directly to the page, i.e.– Client-side HTML or text without an ID property

• The runat = "server" attribute may not be applied

Page 65: Web Forms and Server Controls

Placeholder Web Form ControlPlaceholder Web Form Control

• A container to store dynamically added server controls

• Does not produce any visible output without addition of other controls

• The inserted controls are instantiated using classes and constructors, and are added to the Controls collection of the Placeholder, i.e.Dim MyLink As New Hyperlink

placeholder.Controls.Add(MyLink)

Page 66: Web Forms and Server Controls

The "Target" Property of a Hyperlink ControlThe "Target" Property of a Hyperlink Control

• Target—window or frame in which the Web page will load (open)– The reserved name windows are:

• _blank—renders in a new window without frames (_new will also render in a new window)

• _parent—renders in the immediate frameset or window parent one level above

• _self—renders in frame with the current focus

• _top—renders in a full window without frames

– Target also may be a named frame or window

Page 67: Web Forms and Server Controls

ASPPlaceHolder.aspxASPPlaceHolder.aspx

Page 68: Web Forms and Server Controls

ASPPlaceHolder.aspxASPPlaceHolder.aspx

• In Design view, the Placeholder control already is inserted onto Form

• Set properties:– ID placeholder

Page 69: Web Forms and Server Controls

ASPPlaceHolder.aspx—Page_LoadASPPlaceHolder.aspx—Page_Load

• After comment "Create a hyperlink", insert:Dim MyLink As New Hyperlinkplaceholder.Controls.Add(MyLink)With MyLink .Text = "Click here to see larger image" .ForeColor = Color.FromName("#004040") .Font.Name = "Trebuchet MS" .Font.Size = MyLabel.Font.Size.Smaller .ID = "HLHome" .NavigateURL = "images/LgButterfly.jpg" .Target = "_blank"End With

Page 70: Web Forms and Server Controls

CheckBox Web Form ControlCheckBox Web Form Control

• Unlike a RadioButton, more than one CheckBox can be Checked

• Code can look at the value of each CheckBox, i.e. Dim MyMessage As String

MyMessage = "<b>You selected:</b><br />"

If CB1.Checked Then

MyMessage &= CB1.Text & "<br />"

End If

Page 71: Web Forms and Server Controls

ASPCheckBox.aspxASPCheckBox.aspx

Page 72: Web Forms and Server Controls

ASPCheckBox.aspxASPCheckBox.aspx

• In Design view, drag CheckBox control from "Web Forms" tab of Toolbox below last CheckBox on Form

• Set properties:– ID CB8

– Font—Name Trebuchet MS

– Font—Size X-Small

– ForeColor #004040

– Style—Position Top=??; Left=??

– Text Sports in Ireland

Page 73: Web Forms and Server Controls

ASPCheckBox.aspx—btnSubmit_ClickASPCheckBox.aspx—btnSubmit_Click

• Enter the following code after the procedure header:Dim MyMessage As String

MyMessage = "<b>You selected:</b><br /> <br />"

If CB1.Checked Then

MyMessage &= CB1.Text & "<br />"

End If

Page 74: Web Forms and Server Controls

Using Validation Controls (Page 1)Using Validation Controls (Page 1)

• Compare controls, or part of the controls such as the data, to a rule– Rule may require that the control contain any value, or

require a specific form of data such as alphabetical or numeric.

– The rule may specify what the data must be contained within a range of two values.

– The rule may be very specific and require formatting such as uppercase letters and periods.

Page 75: Web Forms and Server Controls

Using Validation Controls (Page 2)Using Validation Controls (Page 2)

• The five validation controls are:– RequiredFieldValidator—Makes sure a form field is not

left blank

– RangeValidator—Makes sure a field’s value falls between a given range

– CompareValidator—Compares field with other values or values of other controls using relational operators

– RegularExpressionValidator—Evaluates the data against a regular expression

– CustomValidator—Evaluates data against custom criteria as defined in a programmer-define Function

Page 76: Web Forms and Server Controls

Using Validation Controls (Page 3)Using Validation Controls (Page 3)

• Inherits from the BaseValidator class which inherits from the Label class– Therefore custom error messages are displayed using

Label controls

• Validation controls that perform comparisons inherit directly from BaseCompareValidator base class

Page 77: Web Forms and Server Controls

Using Validation Controls (Page 4)Using Validation Controls (Page 4)

• Common properties– Display property—shows the message

• Dynamic—space for the validation message is dynamically added to the page only if validation fails

• Static—space for the validation message is allocated in the page layout whether there is an error, or not

• None—validation message is never displayed in the browser

– ErrorMessage—displayed if the value of the control is in error (extends from Text property of a Label)

– ForeColor property is the color of the error message (default color is red)

Page 78: Web Forms and Server Controls

Using Validation Controls (Page 5)Using Validation Controls (Page 5)

• Validate method performs validation on associated input control and updates the IsValid property– Page.IsValid (Boolean) indicates if the controls on the

page are valid after the Page.Validate method executes

• The following checks if the entire form is valid Page.Validate()

If Page.IsValid Then

Message.Text = "Result: Valid!"

Else

Message.Text = "Result: Not valid!"

End If

Page 79: Web Forms and Server Controls

Using Validation Controls (Page 6)Using Validation Controls (Page 6)

• ControlToValidate property specifies the control to validate

• For the RegularExpressionValidator control, theValidationExpression property compares control to the regular expression– Regular Expression is a rule that describes the

value using a language that describes one or more groups of characters

Page 80: Web Forms and Server Controls

Using Validation Controls (Page 7)Using Validation Controls (Page 7)

• The ValidationExpression property– Built-in regular expressions – Regular Expression Editor – Library of sample codes

Internet E-Mail Address \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*Internet URL http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?US Phone Number \d{3}-\d{3}-\d{4}US Zip Code \d{5}(-\d{4})?

Page 81: Web Forms and Server Controls

ASPValidateForm.aspxASPValidateForm.aspx

Page 82: Web Forms and Server Controls

Using Validation Controls (Page 8)Using Validation Controls (Page 8)

• The ValidationSummary control– Summarizes in one location the error messages from

all validators on a Web page

– Properties:• DisplayMode—error messages displays as a list

(List), a bulleted list (BulletList), or a single paragraph (SingleParagraph)

• ShowSummary—shows the entire list

• ShowMessageBox—displays errors in an alert box

• HeaderText—a heading message displayed prior to the error listing

Page 83: Web Forms and Server Controls

ASPValidationSummary.aspxASPValidationSummary.aspx

Page 84: Web Forms and Server Controls

Binding Web Form Controls to Simple DataBinding Web Form Controls to Simple Data

• Bind data to controls

– Assign a DataSource

– Call the DataBind method

• Group together controls

– RadioButtonList controls—group RadioButtons

– CheckboxList controls—group CheckBox controls

• Set group properties

– RepeatDirection property—displayed horizontally or vertically

– RepeatLayout property—use table or paragraph tags

Page 85: Web Forms and Server Controls

Binding RadioButtonLists to ArrayLists (Page 1)

Binding RadioButtonLists to ArrayLists (Page 1)

• An ArrayList is a type of array – Size dynamically increases as required– Declared using Dim, the array name, and keyword

New, and ArrayList at the type• Properties and Methods– Capacity—the number of items the list can hold

• zero-based - counting of items starts at 0 and not 1; default capacity of 16

– Count—determines the number of items in the list– Add method—used to add items to the list– SelectedItem—determines which element is selected

Page 86: Web Forms and Server Controls

Binding RadioButtonLists to ArrayLists (Page 2)

Binding RadioButtonLists to ArrayLists (Page 2)

• Add items to array list and populate RadioButtonList …

AR1.Add("Sports in Ireland")

RBL.DataSource = AR1

RBL.DataBind()

• Retrieve values using SelectedItem propertyDim strResult As String

strResult = "<b>You selected: </b><br/><br/>"

If RBL.SelectedIndex > -1 Then

strResult += RBL.SelectedItem.Text

End If

lblTopics.Text = strResult

Page 87: Web Forms and Server Controls

Binding CheckBoxLists to HashTables (Page 1)

Binding CheckBoxLists to HashTables (Page 1)

• Items are added using a key and value pair• Declare using keyword Dim, HashTable name,

keyword New, and Hash(n) as type (n is table size)– Add method adds items to the HashTable.

– Use the key to retrieve the value for a particular item

• You must specify the key and value:– DataValueField is used to create the value

– DataTextField is used to create the text displayed

Page 88: Web Forms and Server Controls

Binding CheckBoxLists to HashTables (Page 2)

Binding CheckBoxLists to HashTables (Page 2)

• Add a value to a HashTable (key, value)• Populate the CheckBoxList and bind data to control– Notice that the key or value may be displayed; in this example,

the value isdisplayed: If Not Page.IsPostBack Then

Dim HS1 As New HashTable(5)…HS1.Add(5, "Sports in Ireland")CBL.DataSource = HS1CBL.DataTextField = "Value"CBL.DataValueField = "Key"CBL.DataBind()

End If

Page 89: Web Forms and Server Controls

Binding CheckBoxLists to HashTables (Page 3)

Binding CheckBoxLists to HashTables (Page 3)

• Loop through each control in the list and read values using the Boolean Selected property: If CBL.SelectedIndex > -1 Then strResult = _ "You selected the following categories:<br />" Dim i As Integer For i = 0 To CBL.Items.Count - 1 If CBL.Items(i).Selected Then strResult += CBL.Items(i).Text + "<br />" End If NextElse strResult = "You did not select a category."End IflblTopics.Text = strResult

Page 90: Web Forms and Server Controls

ASPRadioButtonList.aspxASPRadioButtonList.aspx

Page 91: Web Forms and Server Controls

ASPDBCheckboxList.aspxASPDBCheckboxList.aspx

Page 92: Web Forms and Server Controls