Title: Using Server Controls
1Using Server Controls
- Introduction to ASP.NET
- By Kathleen Kalata
2Objectives
- In this chapter, you will
- Create Web pages using HTML server controls and
ASP.NET controls - Examine the difference between HTML server
controls and ASP.NET controls - Create and process a form using HTML server
controls and ASP.NET server controls - Populate controls dynamically using ArrayLists
and HashTables - Validate a form using validation controls
3Using HTML Server Controls
- Object-oriented programming allows you to use
objects, which can be accessed by other programs - An object is a set of related methods and
properties that are compartmentalized - Properties are used to set the value of a
variable defined within an object - All of the HTML tags can be immediately changed
into server-side tags using runatserver - Attributes also are called properties
- Visible property is a Boolean value that
indicates whether a Server control is rendered as
an HTML control on the page
4HTML Control Server Event Handlers
- Client-side controls have events such as onClick
and onChange are associated with HTML client
controls - To be able to detect these events on the server,
Visual Studio .NET will create a generic
JavaScript event handler called _doPostBack - The event sends the name of the control
(eventTarget) and any arguments (eventArgument)
back to the server when the event is intercepted - This handler only is required once per page, and
is written by the server, not the programmer - OnServerChange event occurs when an HTML server
control value has changed
5OnServerChange Event
- The HTML controls that support the OnServerChange
event - HTMLInputCheckBox
- HTMLInputRadio
- HTMLInputHidden
- HTMLInputText
- HTMLTextArea
- HTMLSelect
- The HTML controls that support the OnServerClick
event - HTMLInputImage
- HTMLAnchor
- HTMLButton
- HTMLForm
6Sample Web Form
- ltinput name"WebAddress" type"text"
id"WebAddress" - onchange"__doPostBack('WebAddress','')"
- language"javascript" /gt
- ltinput type"submit" name"GoBtn" value"Go"
id"GoBtn" /gt - ltinput type"hidden" name"__EVENTTARGET"
value"" /gt - ltinput type"hidden" name"__EVENTARGUMENT"
value"" /gt
7Sample _doPostback Event Handler
- ltscript language"javascript"gt
- lt!--
- function __doPostBack(eventTarget, eventArgument)
- var theform document.ctrl0
- theform.__EVENTTARGET.value eventTarget
- theform.__EVENTARGUMENT.value eventArgument
- theform.submit()
-
- // --gt
- lt/scriptgt
8Using HTML Server Controls
- A function is a named grouping of one or more
programming statements - This exercise demonstrates how to use HTML server
controls to dynamically change the contents of
the page - Create a new project named Chapter3, create an
images folder, import the images - Create a WebForm from scratch named
HTMLButton.aspx
9Using HTML Server Controls
- This code changes the visible property for the
two label controls to false - lblGiftIdeasMen.Visible False
- lblGiftIdeasWomen.Visible False
- The code f or the male button
- lblTitle.InnerHtml "ltbgtWe have lots of gift
ideas for men.lt/bgt" - lblGiftIdeasWomen.Visible False
- lblGiftIdeasMen.Visible True
- The code for the female button
- lblTitle.InnerHtml "ltbgtWe have lots of gift
ideas for women.lt/bgt" - lblGiftIdeasWomen.Visible True
- lblGiftIdeasMen.Visible False
10HTMLButton.aspx
11HTML Server Button Controls
- The properties of individual controls can be
changed through the Properties window - You can also change the properties of individual
controls by adding your code to the code behind
the page - You can change the property when the page loads,
or when an event occurs, such as a button click - The properties are not always the same for HTML
server controls and ASP.NET server controls
12Using HTMLImageButton Server Controls
- In the exercise, you import the HTML template
named HTMLImageButton.aspx - The btnMale_ServerClick event handler
- Private Sub (ByVal sender As System.Object, ByVal
e As System.Web.UI.ImageClickEventArgs) Handles
btnMale.ServerClick - lblTitle.InnerHtml "ltbgtWe have lots of gift
ideas for men.lt/bgt - lblGiftIdeasWomen.Visible False
- lblGiftIdeasMen.Visible True
- End Sub
13Using HTMLImageButton Server Controls
- The btnFemale_ServerClick event handler
- Private Sub btnFemale_ServerClick(ByVal sender As
System.Object, ByVal e As System.Web.UI.ImageClick
EventArgs) Handles btnFemale.ServerClick - lblTitle.InnerHtml
- "ltbgtWe have lots of gift ideas for women.lt/bgt"
- lblGiftIdeasWomen.Visible True
- lblGiftIdeasMen.Visible False
- End Sub
14Using HTMLInputButton Server Controls
- In the exercise, you import the HTML template
named HTMLInputButton.aspx - Retrieve the value property of the control
- Note
- You can use concatenation character () to append
strings - You can use the line termination character (_) to
continue the code across multiple lines - The character is used in the book to provide
you with emphasis that the line of code is split
in the book, but you should not split the line of
code in your application
15HTMLInputButton.aspx
16Hyperlinks and Form Fields
- Hyperlinks allow you to create links to other
pages or to internal targets within the same page - Check boxes, radio buttons, and drop-down lists
are form fields that allow you to select from
lists of options - In the following exercises you will add
hyperlinks, radio buttons, and drop-down list
boxes to the Web form named HTMLRadioButton.aspx
17HTMLRadioButton.aspx
- The code that determines which radio button is
checked - If (rdBridal.Checked True) Then
- lblTitle.InnerHtml "Celebrate your Wedding!"
- imgTop.Src "images/28.jpg"
- ElseIf (rdBooks.Checked True) Then
- lblTitle.InnerHtml "Your Favorite Irish Book
Selections!" - imgTop.Src "images/27.jpg"
- .
- End If
18HTMLRadioButton.aspx
19Creating a Page with a Drop Down List Control
- HTML drop down list controls are created with the
HTML Select tag - Option tags are used to create each individual
item in the list - A value can be associated with each item in the
list - You can obtain information about the option
selected by using the SelectedIndex property of
the drop-down list box - When nothing has been selected the SelectedIndex
property returns the value -1 - The Add method allows you to add items to the
list dynamically when the page loads, or when an
event occurs
20HTMLSelect.aspx
21Creating a Page with a Hyperlink Control
- The hyperlink control is used to create an anchor
tag - You can use the property window to assign the URL
or do it in the code behind the page - Link to another page or a target using the
ImageURL property - The displayed text is configured using the Text
property - The text property also becomes the tooltip by
default - AHome.Href "http//www.tarastore.com"
22HTMLAnchor.aspx
23Using ASP.NET WebForm Controls
- The ASP.NET controls are located on the WebForms
tab in the toolbox - The ASP.NET Webforms inherit from the Web Control
class which is found in the System.Web.UI.WebContr
ols namespace - ASP.NET controls can be grouped into
- WebForm controls
- Rich controls
- Data controls
- Validation Controls
- Mobile Controls
24Target Property
- The target is the window or frame to load the Web
page linked to when the HyperLink control is
clicked - The default value for the target is String.Empty
- The reserved windows are
- _New - renders the content in a new window
- _blank - renders the content in a new window
without frames - _parent - renders the content in the immediate
frameset parent - _self - renders the content in the frame with
focus - _top - renders the content in the full window
without frames
25Syntax Issues
- The color properties must be assigned using a
different syntax - Color is an object that inherits its properties
from the System.Drawing,Color namespace - You can assign the value by the known color name,
a 32-bit value, a hexadecimal value, or property
of an object - Known colors that you can refer to by name
- MyControl.BorderColor System.Drawing.Color.Green
- Assign the color value from the text box or form
- MyControl.BackColor Color.FromName(txtBackColor.
Value)
26Image Control
- The WebForm image control class produces an ltimggt
tag - If you need to capture mouse clicks on the image,
you use the ImageButton control - The ImageURL property provides the path to the
image by creating the SRC property for the IMG
tag - The AlternateText property provides the text that
is displayed when the image is not available - The AlternateText property generates the ALT
property in the HTML tag - The ImageAlign property provides the image
alignment property
27ASPSelect.aspx
- Add a drop-down list to a Web page, and
dynamically add the options to the list when the
page first loads - 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, and Video")
- dlCategory.Items.Add("Bridal")
- End If
28Submit Button Click Event Handler
- Get value and change the ImageURL property
- Select Case dlCategory.SelectedIndex
- Case 0
- lblTitle.Text "Let us help you find the best
gift!" - imgTop.ImageUrl "images/21.jpg"
- Case 1
- lblTitle.Text "Quality Jewelry at Affordable
Prices!" - imgTop.ImageUrl "images/22.jpg"
-
- Case Else
- lblTitle.Text "Select a Product Category"
- imgTop.ImageUrl "images/WaterfordGifts.jpg"
- End Select
29ASPSelect.aspx
30Panel, Placeholder, and Literal Controls
- The panel control can contain other controls and
creates a DIV tag to enclose the contents - You can set properties such as wrapping, absolute
positioning, font type, and scrollbars - The label control creates contents within a Panel
control using the SPAN tag - You can also use a literal control to write
content directly to the page - The placeholder control is used as a container to
store dynamically added server controls - The placeholder control does not produce any
visible output without the use of other controls
31ASPPlaceholder.aspx
- Use Add methods to dynamically create a hyperlink
and literal control using the placeholder control - In the Page_Load procedure dynamically create a
label and place the label within the placeholder - ' Create a label to contain text
- Dim MyLabel As New Label()
- placeholder.Controls.Add(MyLabel)
- MyLabel.Text "Please select one or more topics"
- MyLabel.ForeColor System.Drawing.Color.FromName(
"004040") - MyLabel.Font.Name "Trebuchet MS"
- MyLabel.Font.Size MyLabel.Font.Size.Smaller
- MyLabel.ID "lblMessage"
32ASPPanel.aspx
33Working with Checkboxes
- Format the checkboxes and retrieve the values
- Checkboxes can have more than one value checked,
so you have to look at each checkbox to see if
its been checked - Write the results to the string
34ASPCheckbox.aspx
- Dim MyMessage As String
- MyMessage "ltbgtYou selectedlt/bgtltbr /gtltbr /gt"
- If CB1.Checked Then
- MyMessage CB1.Text "ltbr /gt"
- End If
- If CB2.Checked Then
- MyMessage CB2.Text "ltbr /gt"
- End If
- ...
- MyMessage "ltbr /gtltbgtThank you.lt/bgt"
- lblTopics.Text MyMessage.ToString()
35Using Validation Controls
- The ForeColor property sets the color of the
error message - The five validation controls are
- RequiredFieldValidator Makes sure a form field
is not left blank - RangeValidator Makes sure a fields value falls
between a given range - CompareValidator Compares a fields value with
other values or other fields values - RegularExpressionValidator Evaluates data
against a regular expression - CustomValidator Evaluates data against custom
criteria
36Using Validation Controls
- The validation controls inherit from the
BaseValidator class which inherits from the label
class - Therefore, validation controls can display custom
error messages using labels - Validation controls that perform comparisons also
inherit from the BaseCompareValidator base class,
and therefore inherit additional properties
37Using Validation Controls
- They all support common properties and methods
- ForeColor property sets the color of the error
message - The default ForeColor property is red
- Display property is used to show the message
- Dynamic - space for the validation message is
dynamically added to the page if validation fails - Static - space for the validation message is
allocated in the page layout - None - the validation message is never displayed
in the browser
38IsValid Property
- Each of the controls inherits the validate method
which performs validation on the associated input
control and updates the IsValid property - The IsValid property indicates whether the
control that is being validated is valid - Check if the entire page is valid at the same
time by calling the Page.Validate method and then
using the Page.IsValid property - Page.Validate()
- If Page.IsValid Then
- Message.Text "Result Valid!"
- Else
- Message.Text "Result Not valid!"
- End If
- End Sub
39Individual Validation Controls
- The RequiredFieldValidator control is used to
determine if any value is entered or selected - ControlToValidate property specifies the input
control to validate - ValidationExpression property compares the input
control to the regular expression. Some common
regular expressions - Internet E-Mail Address
- \w(-.\w)_at_\w(-.\w)\.\w(-.\w)
- Internet URL
- http//(\w-\.)\w-(/\w- ./?)?
- US Zip Code
- \d5(-\d4)?
40ValidationSummary Control
- To summarize the error messages from all
validators on a Web page, in one location - DisplayMode displays as a list (List), a
bulleted list (BulletList), or a single paragraph
(SingleParagraph) - ShowSummary - shows the entire list of error
messages from invalid controls - ShowMessageBox - displays an additional message
in an alert box by setting - HeaderText - allows you to display a heading
message
41ASPValidateForm.aspx
42ASPValidationSummary.aspx
43Binding to Simple Data
- You can bind data to controls using the DataBind
method - By grouping them together in a single control,
you can set the properties for the entire group - RadioButtonList controls allow you to group a
series of one or more radio buttons - CheckboxList controls allow you to group a series
of one or more Checkbox controls - RepeatDirection property so that the group is
displayed horizontally or vertically - RepeatLayout property which will group the list
using a table or using paragraph tags
44ArrayList
- The ArrayList is a type of array whose size
dynamically increases as required - The ArrayList is declared using the keyword Dim,
the name of the array, and the keyword New - Properties and Methods
- Capacity - the number of items the list can hold
- The ArrayList is zero-based, which means that the
counting of items in the ArrayList 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
45ASPDBRadioButtonList.aspx
- Create a simple ArrayList that will populate a
RadioButtonList control - If Not Page.IsPostBack Then
- RBL.RepeatLayout RepeatLayout.Table
- RBL.RepeatDirection RepeatDirection.Vertical
- Dim AR1 As New ArrayList(9)
- AR1.Add("Current Events in Ireland")
- AR1.Add("Fishing in Ireland")
-
- RBL.DataSource AR1
- RBL.DataBind()
- End If
46ASPDBRadioButtonList.aspx
- The Submit button click procedure determines
which element is selected with the SelectedItem
object, and assigns the text property to a
variable, which is used to change the text
property of the label control - Dim strResult As String
- strResult "ltbgtYou selected lt/bgtltbr/gtltbr/gt"
- If RBL.SelectedIndex gt -1 Then
- strResult RBL.SelectedItem.Text
- End If
- lblTopics.Text strResult
47ASPDBRadioButtonList.aspx
48Binding CheckBoxLists to HashTables
- The items are added using a key and value pair
- Declare using the keyword Dim, the name of the
HashTable, and the keyword New - Add method adds items to the HashTable. You can
use the key in your programming to retrieve the
value for a particular item - Because you have a key and value pair, you must
specify the key and value - DataValueField is used to create the value for
the control - DataTextField is used to create the text
displayed for the control
49ASPDBCheckboxList.aspx
- Create a HashTable and populate the CheckBoxList
- CheckBoxList controls allow you to group a series
of one or more CheckBox controls - Add each pair of key and values and specify the
DataTextField and DataValueField properties - If Not Page.IsPostBack Then
- Dim HS1 As New HashTable(9)
- HS1.Add("Current Events in Ireland",
- "Current Events in Ireland")
-
- CBL.DataSource HS1
- CBL.DataTextField "Value"
- CBL.DataValueField "Key"
- CBL.DataBind()
- End If
50ASPDBCheckboxList.aspx
- Loop through each control in the list and read
the Selected property for each control - Then you can assign the text property of that
control to a variable which will be used to
change the text property of the label control - 'This determines if any item was selected
CBL.SelectedIndex gt -1 - 'This will get the number of items in the list
CBL.Items.Count - Dim strResult As String
51ASPDBCheckboxList.aspx
- If CBL.SelectedIndex gt -1 Then
- strResult "You selected the following
categories ltbr /gtltbr /gt" - Dim i As Integer
- For i 0 To CBL.Items.Count - 1
- If CBL.Items(i).Selected Then
- strResult CBL.Items(i).Text "ltbr /gt"
- End If
- Next
- Else
- strResult "You did not select a category."
- End If
- lblTopics.Text strResult
52ASPDBCheckboxList.aspx