Chapter 1

advertisement
Further Examples of Form and ASP.NET
Web Controls
ASP.NET Web controls (HTML server controls and ASP.NET Server
controls) are placed in the HTML portion of an ASP.NET web page. These
controls are converted to HTML markup when accessed the web page by a
browser. However, Web controls can be accessed programmatically
through the page’s source code. Web controls can be divided into a
number of categories, such as to display text, collect user input, display
data from a database, and so on.
Examining the Web Controls to Display Text
There are two ASP.NET controls designed to display text:
 Literal Web Control
 Label Web Control
These two controls differ in the HTML markup that is rendered when a Web
page is executed. Note, HTML texts returned by a Web page can be
produced by three different ways:
 Using HTML markup language: HTML markup used in the HTML
portion of a Web page is passed on to the browser as it is typed in.
The browser formats the text according to the markup.
 Resonse.Write () statements in the source code section of a page:
The HTML markup produced by this statement is precisely the string
content that is passed on to the browser to interpret.
Response.Write (“<bold>Hello!</bold>”) will print Hello!.
 HTML markup rendered by WEB controls: The markup produced by
these controls is dependent on the property setting of each Web
control.
1
Using the Literal Web Control:
Literal Web control is one of the simple Web controls, and it is used to
display text. As shown below, there are only five properties of this control:
(DataBinding), (ID), EnabaleViewState, Text, and Visible. The HTML
markup produced by the Literal Web control is precisely the value set to the
“Text” property of the control either in the design time.
<%@ Page Language="VB" %>
<script runat="server">
' Insert page code here
'
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Literal id="Literal1"
runat="server"
Text="Management Information
System"></asp:Literal>
<!-- Insert content here -->
</form>
</body>
</html>
The ID property can be used to access the properties of any Web control
from the code section of a Web page. The code syntax to assign the text
property of a Literal control is:
LiteralControlID.Text = value,
where value is the text that is to be displayed. For example, to
display/change text for ID = TextControl:
TextControl.Text =”‘Management Information System”
To display text for ID = CurrentTime with a value from of a VB.NET built-in
routine such as DateTime:
CurrentTime.Text = DateTime.Now
(See code and result below)
2
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(sender as Object, e as
EventArgs)
currentTime.Text = DateTime.Now
End Sub
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Literal id="currentTime"
runat="server"></asp:Literal>
<!-- Insert content here -->
</form>
</body>
</html>
There is an important difference between the results of Response.Write()
and that using the Literal control. With the Response.Write(), the result is
displayed before any HTML is displayed, whereas the output of the Literal
control can be controlled depending on the place of the control within a
page.
Using the Label Web Control:
The Label control differs from the Literal control such that there are more
properties of the Label control that can be set to control the HTML output.
Some of the properties are: ID, BorderColor, BackColor, BorderWidth, Text,
Font (bold, italic, underline, size, names, ..), Visible, and so on. Again the
properties can be set in the design time and they can be changed in the run
time. Example below shows some of the properties set at design time.
<html>
<head>
</head>
<body>
<form runat="server">
<asp:Label id="Label1" runat="server" Font-Size="Medium" Font-Names="Arial Black" FontItalic="True" ForeColor="Red" BorderColor="#0000C0" BackColor="Aqua"
BorderStyle="Double">Text Properties from Label Control</asp:Label>
<!-- Insert content here -->
</form>
</body>
</html>
Run This Code
3
Using the Input Web Control
The Input boxes are commonly used to obtain user inputs. There can be
three kinds of Input boxes: HTML control, HTML Server control, and Web
Control. However, only the server controls’ properties can be accessed
from the program code.
The example below shows how ASP.NET Input Web control is used along
with a Button Web control to gather user input and display results through
the onClick event of the Button control and using Response.Write (). The
results could also be displayed using the Literal or Label Web controls.
<%@ Page Language="VB" %>
<script runat="server">
Sub btnSubmit_Click (sender As Object, e As EventArgs)
'Find out the person's height and weight
Dim h as Integer = height.Text
Dim w as Integer = weight.Text
'Calculate the person's BMI
Dim BMI as Double
BMI = (w / (h * h)) * 703
Response.Write ("Your BMI is " & BMI)
End Sub
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
</p>
<p>
</p>
<p>
Your height (in inches): <asp:TextBox id="height" runat="server"></asp:TextBox>
</p>
<p>
Your weight (in pounds): <asp:TextBox id="weight" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button id="btnSubmit" onclick="btnSubmit_Click" runat="server" Text="Calculate
BMI"></asp:Button>
</p>
<p>
</p>
</form>
</body>
</html>
View Result in the next page
(Make sure to enter some values)
4
Note the location of the HTML output due to Response.Write (). The
location of the output can be changed using an ASP.NET Label control, as
shown below.
<%@ Page Language="VB" %>
<script runat="server">
Sub btnSubmit_Click(sender As Object, e As EventArgs)
results.Text = "Hello, " & name.Text
results.Text &= ". You are " & age.Text & " years old."
End Sub
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
</p>
<p>
Your name:<asp:TextBox id="name" runat="server"></asp:TextBox>
</p>
<p>
Your age:<asp:TextBox id="age" runat="server"></asp:TextBox>
</p>
<p>
<asp:Button id="btnSubmit" onclick="btnSubmit_Click" runat="server" Text="Click Me">
</asp:Button>
</p>
<p>
</p>
<p>
<asp:Label id="results" runat="server"></asp:Label>
</p>
</form>
</body>
</html>
5
Using Multiline Textboxes
Using multiple lines in a text box is simple for a Web control. Simply set the
Textmode property to “multiline” as well as set the rows and columns
properties of the box as desired. For example:
<asp:TextBox id="TextBox1" runat="server" TextMode="MultiLine" Rows="5"
Columns="25" ></asp:TextBox>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
</p>
<p>
Share your thoughts:
<asp:TextBox id="TextBox1"
runat="server" Rows="5" Columns="25"
TextMode="MultiLine"></asp:TextBox>
</p>
</form>
</body>
</html>
Note, this form does not have any action, as there is no script to process
the input.
Using Password Textboxes
The Textbox Web control can also be used to enter password. In this case,
the Textmode property needs to set as “Password”. Here is code section to
process a userid and
<%@ Page Language="VB" %>
password.
<script runat="server">
Again the inputs are not
processed, as there is no
code event associated with
the Button control.
</script>
<html>
<head> </head>
<body>
<form runat="server">
<p> Username: <asp:TextBox id="TextBox1"
runat="server"></asp:TextBox> </p>
<p> Password:
<asp:TextBox id="TextBox2" runat="server"
TextMode="Password"></asp:TextBox>
</p>
<p> <asp:Button id="Button1" runat="server"
Text="Login"></asp:Button></p>
<!-- Insert content here -->
</form>
</body>
</html>
6
Using the DropDownList Web Control
A drop-down list can contain many items, from which a user can select an
item. The DropDownList control has many properties, and DataSource and
Items can be used to populate the control in design time or run-time. The
DataSource is used to populate from an external database table/query and
the Items collection is used to populate the list with internal data.
7
The code section below shows how a DropDownList control is populated in
design time. The result is shown a the bottom.
<%@ Page Language="VB" %>
<script runat="server">
Sub btnSubmit_Click(sender As Object, e As EventArgs)
results.Text = "You like " & flavors.SelectedItem.Text
End Sub
</script>
<html><head></head><body>
<form runat="server">
<p> What is your favorite ice cream flavor?  
<asp:DropDownList id="flavors" runat="server">
<asp:ListItem Value="Chocolate">Chocolate</asp:ListItem>
<asp:ListItem Value="apple">apple</asp:ListItem>
<asp:ListItem Value="Strawberry">Strawberry</asp:ListItem>
<asp:ListItem Value="Vanilla">Vanilla</asp:ListItem>
</asp:DropDownList>
</p>
<p>
<asp:Button id="btnSubmit" onclick="btnSubmit_Click" runat="server"
Text="Click Me"></asp:Button>
</p>
<p>
<asp:Label id="results" runat="server"></asp:Label>
</p>
</form>
</body></html>
8
Using the RadioButton Web Control
Another means of collecting input is using radio buttons. They can work
together in a group such that more than one radio buttons can not be
selected. This can be achieved by setting the GroupName property of a
group of radio buttons to be the same name. Also, if one of the radio
buttons should be selected at the opening of the Web page, the Checked
property of that button should be set to “True”.
<asp:RadioButton id="vanilla" runat="server" Text="Vanilla" GroupName="flavors" Checked="True">
</asp:RadioButton>
<asp:RadioButton id="chocolate" runat="server" Text="Chocolate" GroupName="flavors">
</asp:RadioButton>
<asp:RadioButton id="strawberry" runat="server" Text="Strawberry" GroupName="flavors">
</asp:RadioButton>
<%@ Page Language="VB" %>
<script runat="server">
Sub btnSubmit_Click (sender As Object, e As EventArgs)
If vanilla.Checked then
results.Text = "You like Vanilla"
ElseIf chocolate.Checked Then
results.Text = "You like Chocolate"
ElseIf strawberry.Checked Then
results.Text = "You like Strawberry"
End If
End Sub
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p> What is your favorite ice cream flavor?
<asp:RadioButton id="vanilla" runat="server"
Text="Vanilla" GroupName="flavors"
Checked="True"></asp:RadioButton>  
<asp:RadioButton id="chocolate" runat="server"
Text="Chocolate" GroupName="flavors"></asp:RadioButton>
 
<asp:RadioButton id="strawberry" runat="server"
Text="Strawberry" GroupName="flavors"></asp:RadioButton>
 
<asp:Button id="btnSubmit" onclick="btnSubmit_Click"
runat="server" Text="Click Me"></asp:Button>
<asp:Label id="results" runat="server"></asp:Label>
</p>
</form>
</body>
</html>
9
Using the CheckBox Web Control
The CheckBox is similar to RadioButton, except it does not work in a group.
More than one check boxes can be selected. Again, the Checked property
can be set in the design time and its value can be verified at run time.
<%@ Page Language="VB" %>
<script runat="server">
Sub btnSubmit_Click (sender As Object, e As EventArgs)
'Clear out the value of the results Text property
results.Text = ""
If vanilla.Checked then
results.Text &= "You like Vanilla."
End If
If chocolate.Checked then
results.Text &= "You like Chocolate."
End If
If strawberry.Checked then
results.Text &= "You like Strawberry."
End If
End Sub
</script>
<html><head></head><body>
<form runat="server">
What are your favorite ice cream flavors?
<asp:CheckBox id="vanilla" runat="server" Text="Vanilla">
</asp:CheckBox>
<asp:CheckBox id="chocolate" runat="server"
Text="Chocolate"> </asp:CheckBox>
<asp:CheckBox id="strawberry" runat="server"
Text="Strawberry"> </asp:CheckBox>
<asp:Button id="btnSubmit" onclick="btnSubmit_Click"
runat="server" Text="Click Me"></asp:Button>
<asp:Label id="results" runat="server"></asp:Label>
</p>
</form>
</body></html>
10
Using the Validation Web Controls
When entering user information through text boxes, there is no guarantee
that the user will always enter correct or desired data. Also, there is a
question of format for a particular data type such as a telephone number or
social security number. ASP.NET provides four controls that provide
validation to user inputs. They are:
 RequiredFieldValidator
 CompareValidator
 RangeValidator, and
 RegularExpressionValidator
These controls work in conjunction with the input controls. There are
specific properties of these controls that need to be set to make these
controls work with the input controls. Typically, a validation control is placed
right after the input box that needs validation. More than one control can be
associated with a specific input box for various types of validation. All four
controls have two properties common: ControlToValidate and
ErrorMessage.
RequiredFieldValidator
It ensures that the user has entered data in a specific input box. This
control has many properties, and among them the most important ones are:
ControlToValidate and ErrorMessage. The ControlToValidate property is
used to specify the input box whose data should be validated. The
ErrorMessage property is used to display a message when the user fails to
enter any data in the input box.
<asp:TextBox id="name" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
ControlToValidate="name" ErrorMessage="You must provide your
name."></asp:RequiredFieldValidator>
CompareValidator
This control is used to compare the user input with a value using a property
called Operator, whose values can be: Equal (=), NotEqual (<>),
GreaterThan (>), LessThan (<), GreaterThanEqual (>=), LessThanEqual
(<=), and DataTypeCheck. The comparison is performed against a
11
constant value of another property called, ValueToCompare. In addition to
the Operator property, we need to set the data Type property, which can
take values of: string, integer, double, date, and currency. Thus combining
these two properties, a user input data is validated. It also uses the
property of ErrorMessage.
<asp:TextBox id="totalChildren" runat="server" </asp:TextBox>
<asp:CompareValidator id="CompareValidator1" runat="server"
ControlToValidate="totalChildren" ErrorMessage="The total number of children
must be a whole number greater than or equal to 0" Type="Integer"
ValueToCompare="0" Operator="GreaterThanEqual"></asp:CompareValidator>
The CompareValidator can also be used to compare data entered in one
input to that of another input. It is performed by using the property,
ControlToCompare.
<asp:TextBox id="totalChildren" runat="server" </asp:TextBox>
<asp:CompareValidator id="CompareValidator1" runat="server"
ControlToValidate="totalChildren" Type="Integer" ValueToCompare="0"
Operator="GreaterThanEqual"></asp:CompareValidator>
<asp:TextBox id="maleChildren" runat="server" </asp:TextBox>
<asp:CompareValidator id="CompareValidator2" runat="server"
ControlToValidate="maleChildren" ErrorMessage="The number of male children
must be less than or equal to the number of total children" Type="Integer"
Operator="LessThanEqual"
ControlToCompare="totalChildren"></asp:CompareValidator>
RangeValidator
If the upper and lower values of a range of data is constant, we can use a
RangeValidator control. In addition to the property for data Type, this
control has two properties to set the range of values: MinimumValue and
MaximumValue.
<asp:TextBox id="age" runat="server" Columns="4"></asp:TextBox>
<asp:RangeValidator id="RangeValidator1" runat="server"
ControlToValidate="age" ErrorMessage="Age must be between 0 and 150"
MaximumValue="150" MinimumValue="0" Type="Integer"></asp:RangeValidator>
12
RegularExpressionValidator
Many inputs such as the telephone number, social security number, or email address requires a specific format. In addition to some common
properties, the RegularExpressionValidator has a property called
ValidationExpression which can be set to a specific format for input. Most
ASP.NET editors come up with built-in expressions such as phone number,
social security number, and zip code, which can be set in the design time.
Social Security Number:
<asp:TextBox id="ssn" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server" ControlToValidate="ssn" ErrorMessage="Your social security number
must be in the format XXX-XX-XXXX" ValidationExpression="\d{3}-\d{2}\d{4}"></asp:RegularExpressionValidator>
Validation Through a Code Section
After setting validations to all the user inputs, it is possible to
programmatically verify whether the user has entered all data correctly.
This validation is performed through the IsValid property of the Page object.
<%@ Page Language="VB" %>
<script runat="server">
Sub btnSubmit_Click(sender As Object, e As EventArgs)
If Page.IsValid then
Response.Write("Input is valid...")
Else
Response.Write("Input is <b>not</b> valid...")
End If
End Sub
</script>
<html><head></head><body>
<form runat="server">
……………………………………………………………………..
……………………….. (Input controls and validation controls)
……………………………………………………………………...
<asp:Button id="btnSubmit" onclick="btnSubmit_Click" runat="server"
Text="Click Me"></asp:Button>
</form>
</body></html>
13
14
Download