Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls...

39
CPAN 660 ASP.NET Lecture #8: Server Controls Server controls are GUI controls designed to be used with web forms. We have two kinds of server controls: HTML controls and web controls. Other kinds of control supported by ASP.NET are custom controls and user controls. HTML controls are defined in the namespace System.Web.UI.HtmlControls and correspond to HTML tags. For example HtmlButton correspond to the HTML tag <button>. HTML controls must have the attribute runat=”server” when used in a web form. Web controls are defined in the namespace System.Web.UI.WebControls and provide wider set of controls to be used with web forms. For example, Calendar control and AddRotator Control. View state is a mechanism where ASP.NET controls retain their values. This is done automatically when the view state is enabled by implementing a hidden field called VIEWSTATE. We can disable the view state but some controls such as TextBox will retain their values if the view state is disabled because they are submitted to the server on each form post. We can add data to the view state as follows: ViewState(“item1”)= value1 This will be added to the above value to the state bag class. Values added to the state bag class are automatically added to the hidden form variable VIEWSTATE. 1

Transcript of Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls...

Page 1: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

CPAN 660 ASP.NET

Lecture #8: Server ControlsServer controls are GUI controls designed to be used with web forms. We have two kinds of server controls: HTML controls and web controls. Other kinds of control supported by ASP.NET are custom controls and user controls.

HTML controls are defined in the namespace System.Web.UI.HtmlControls and correspond to HTML tags. For example HtmlButton correspond to the HTML tag <button>. HTML controls must have the attribute runat=”server” when used in a web form.

Web controls are defined in the namespace System.Web.UI.WebControls and provide wider set of controls to be used with web forms. For example, Calendar control and AddRotator Control. View state is a mechanism where ASP.NET controls retain their values. This is done automatically when the view state is enabled by implementing a hidden field called VIEWSTATE. We can disable the view state but some controls such as TextBox will retain their values if the view state is disabled because they are submitted to the server on each form post.

We can add data to the view state as follows:

ViewState(“item1”)= value1

This will be added to the above value to the state bag class. Values added to the state bag class are automatically added to the hidden form variable VIEWSTATE.

Following is a description of some of the web form controls in ASP.NET:

1- Label control: Displays static text in a web form. This control has an attribute called Text that is used to get or set the text displayed by the label.

2- Textbox control: Used to render any of the 3 html tags: text field, password field or text area. Some of the attributes for this control are:

AutoPostBack: Automatically post the form whenever a change is made to the text box

1

Page 2: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Columns: Indicates the horizontal size of the text in characters MaxLength: Determines the maximum number of characters that can be

entered in the textbox ReadOnly: Determines if the textbox can be modified. Rows: Gets or sets the number of lines in the textbox Text: Gets or sets the text displayed in the textbox TextMode: Specifies the type of the textbox. It can be SingleLine,

MultiLine, or password Wrap: Enables/disables word wrapping in a multiline textbox

ASP.NET has a feature called Request Validation. When it’s enabled, users cannot enter certain content into the textbox such as HTML code. This feature is added to improve security and prevent malicious attacks. This feature is enabled be default. To disable it, add the following directive at the top of you ASP.NET page:

<%@ ValidateRequest =”False” %>To disable it for the entire application, add the following to the system.web section of the application’s configuration file (web.config ):<Pages ValidateRequest =”False” />

The TextChanged event is triggered when the content of the text box is changed. OnTextChanged method raises the text change event.

3- Button ControlsWe can add 3 types of button controls to a web form that are used to submit the form to the web server:

Button: Displays a standard HTML button ImageButton: Displays an image button LinkButton: Displays a hypertext link

Some of the common properties of Button controls are: Text: Gets or Sets the text displayed on the button. CommandName: Passes the command name to the Command event. CommandArgument: Passes the command argument to the Command

event. CausesValidation: Determines whether the button s validated when the

form is submitted.

Button controls have similar events and methods. The Click event is raised when the button is clicked causing the form to be submitted to the server. Command event is raised as well when the button is clicked, but the commandName and commandArgument properties are passed to this event. Two methods are common to all buttons controls: OnClick and onCommand that raise Click and Command event respectively.

2

Page 3: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Some of the Image button attributes are: AlternativeText: Gets or sets the text displayed when the browser does

not support images. ImageURL: Specifies the URL of the image to be displayed with the

button.

4- Radio Button and RadioButtonList Controls: Radio buttons represent a group of mutual exclusive options. One radio button in a group can be checked at anytime. Radio buttons provide more control over the layout of the radio buttons in the group. Radio Button controls are added individually. To group them we assign the same name to the groupName property of each of them. The attribute checked has the value true when the radio button is checked and false otherwise. The attribute Text gets or sets the text associated with the radio button.

The method OnCheckedChanged is used to raise the event CheckedChanged. CheckedChanged is raised when the radio button control state is changed from checked to unchecked or vice versa.

RadioButtonList provides an easier way to display a group of options. It can be also used to display a group of options from a database table or a collection. Some of the properties of this control are:

DataSource: Specifies the data source for the items associated with the control.

DataMemeber: Specifies the table in the data source to be bind to the control.

DataTextField: Specifies the field in the data source to be used as labels for the radio buttons.

DateTextFormatString: Specifies a formatting string for DataTextField. DataValueField: Specifies the field in the data source to be used as

values for the radio buttons. Items: Represents a collection of items associated with the control. SelectedIndex: Gets or sets the index of the currently checked radio

button. SelectedValue: Gets or sets the selected radio button. SelectedItem: Represents the selected radio button. RepeatColumns: Determines the number of columns used to display the

radio buttons RepeatDirection: Determines how the radio buttons should be repeated.

Possible values are: Horizontal and vertical.

3

Page 4: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

RepeatLayout: Determines how the radio buttons are laid out. Possible values are: Table and flaw.

The event SelectedIndexChanged is raised when a new radio button in the radioButtonList is selected. The method DataBind is used to bind the RadioButtonList to its data source and load the items from the data source to the items collection. OnSelectedIndexChanged method raises the SelectedIndexChanged.

We can add radio buttons to a RadioButtonList in 3 ways: list the radio buttons when we declare the RadioButtonList, add them to the lists collection of the RadioButtonList, or bind the RadioButtonList to a data source.

5- CheckBox and CheckBoxList ControlsCheckbox and CheckBoxList controls are used to represent a list of non mutual exclusive options. Working with checkboxes is similar to radio buttons, except that we can check more than one box in the same time.

6- DropDownList ControlDropdown list is similar to a radiobuttonlist except it uses less space on the form. Some of the properties of this control are:

DataSource: Specifies the data source for the items associated with the control.

DataMemeber: Specifies the table in the data source to be bind to the control.

DataTextField: Specifies the field in the data source to be used as labels for the radio buttons.

DateTextFormatString: Specifies a formatting string for DataTextField. DataValueField: Specifies the field in the data source to be used as

values for the radio buttons. Items: Represents a collection of items associated with the control. SelectedIndex: Gets or sets the index of the currently checked radio

button. SelectedValue: Gets or sets the selected radio button. SelectedItem: Represents the selected radio button.

DropDownList controls have similar events and methods as the RadioButtonList controls.

7- ListBox Control:

This control is used to represent a list of option. This control can be set to enable single selection as well as multiple selections. Some of the attributes for this control are:

4

Page 5: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

DataSource: Specifies the data source for the items associated with the control.

DataMemeber: Specifies the table in the data source to be bind to the control.

DataTextField: Specifies the field in the data source to be used as labels for the radio buttons.

DateTextFormatString: Specifies a formatting string for DataTextField. DataValueField: Specifies the field in the data source to be used as

values for the radio buttons. Items: Represents a collection of items associated with the control. SelectedIndex: Gets or sets the index of the currently checked radio

button. SelectedValue: Gets or sets the selected radio button. SelectedItem: Represents the selected radio button. SelectionMode: Determines whether the user can select single item or

multiple items from the list.ListBox controls have the same methods and events as the RadioButtonList controls.

8- HyperLink Control:This controls is used to display a text or an image as a link. It functions in the same way as an HTML hyper link, but it provide us with the ability to modify it’ properties in our code. Some of the attributes for this control are:

ImageUrl: Specifies the URL for the image to be displayed in the link. NavigateUrl: Specifies the URL for the page where the user is transferred

when the link is clicked. Target: The target window or frame. Possible values are: _top, _self,

_parent, _search, and _blank.

The following code shows how to add a hyper link this control in an ASPX page

<asp:HyperLink id=”l1” runat=”server” ImageURL=”image1.gif”NavigatorUrl=”http://humber.ca” Text=”Visit humber” Target=”_blank” />

9- Panel Control

This control is layout region for other controls. It is equivalent to the DIV element in HTML. Some of the attributes for this control are:

BackImageUrl: Gets or sets the URL of the image to be displayed as a background

HorizontalAlign: Sets the horizontal alignment for the content of the panel.

5

Page 6: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Wrap : Determines whether the content of the panel is wrapped or not.

10- PlaceHolder ControlThis control acts as a container for other controls which are added dynamically to a web page.

11- Calendar ControlDisplays a one month calendar and enable the user to select a specific date. Some of the attributes of this control are:

VisibleDate: Gets or sets the date that specifies the month to display on the Calendar control.

TodaysDate: Gets or sets the value for today's date. TitleFormat: Gets or sets the title format for the title section. ShowNExtPrevMonth: Gets or sets a value indicating whether the

Calendar control displays the next and previous month navigation elements in the title section

ShowDayHeader: Gets or sets a value indicating whether the heading for the days of the week is displayed.

SelectWeekText: Gets or sets the text displayed for the week selection element in the selector column.

SelectedMonthText: Gets or sets the text displayed for the month selection element in the selector column.

SelectionMode: Gets or sets the date selection mode on the control that specifies whether the user can select a single day, a week, or an entire month.

SelectedDates : Gets a collection of System.DateTime objects that represent the selected dates on the control.

SelectedDate: Gets or sets the selected date.

The DayRender event occurs when each day is created in the control hierarchy. The SelectionChanged event is raised when the user selects a day, a week, or an entire month.

12- AddRotator ControlDisplays randomly selected ad banner on the web form. To use this control you need to create an xml file called the advertisement file. Some of the attributes for this control are:

AdvertisementFile: The path of the XML file that contains the advertisements.

KeywordFilter: applies a filter to the returned advertisements.

6

Page 7: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Target: The target window or frame. Possible values are: top, self, new, child, parent, and blank.

HorizontalAlign: Sets the horizontal alignment for the content of the panel.

Wrap : Determines whether the content of the panel is wrapped or not.

The AdCreated event is raised after an advertisement is returned from the advertisement file and before the controls is rendered.

13- Table control: This control is used to build an HTML table. Some of the properties of this control are:

CellSpacing: Gets or sets the amount of space between cells. CellPadding: Gets or sets the amount of space between the contents of a

cell and its border. Rows: Gets the collection rows in the table. BackImageURL: Gets or sets the URL of the background image to

display behind the control.

14- Repeater control

The Repeater control is a template based data-bound list control. Its template allows custom layout for each item displayed in the list. This control is usually used to format data from data source. Some of the properties of this control are:

DataSource: Specifies the data source for the items associated with the control.

DataMemeber: Specifies the table in the data source to be bind to the control.

FooterTemplate: Gets or sets the System.Web.UI.ITemplate that defines how the footer in the control is displayed.

HeaderTemplate: Gets or sets the System.Web.UI.ITemplate that defines how the header in the control is displayed.

ItemTemplate: Gets or sets the System.Web.UI.ITemplate that defines how items in the control are displayed.

SeparatorTemplate: Gets or sets the System.Web.UI.ITemplate that defines how separators between items are displayed.

Items: Gets a collection of RepeaterItem objects in the control.

The ItemCommand event is raised when a button is clicked in the control. The DataBind method is used to bind data from the data source to the control.

7

Page 8: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

15- Validation Controls

Validation controls are used to perform validation against any other controls. Following is a description of each:

RequiredFieldValidator: Used to validate that a control is been filled. Some of the important properties of this control are: ControlToValidate: Specifies the ID of the control to be validated. ErrorMessage: Specifies the error message to be displayed in the

ValidationSmmary control when the field is not valid. Text: Sets the error message that is displayed by the control. IsValid: Indicates whether the validation is successful or not.

CompareValidator: Compares the value of a control against another value. Some of the important properties of this control are: ControlToCompare: Specifies the ID of the control to be compared

against. ControlToValidate: Specifies the ID of the control to be validated. ErrorMessage: Specifies the error message to be displayed in the

ValidationSmmary control when the field is not valid. Text: Sets the error message that is displayed by the control. IsValid: Indicates whether the validation is successful or not. Operator: Gets or sets the operator used in the comparison. Type: Gets or sets the data types used in the comparison.

RangeValidator: Used to ensure that data entered falls within a certain range. Some of the important properties of this control are: ControlToValidate: Specifies the ID of the control to be validated. ErrorMessage: Specifies the error message to be displayed in the

ValidationSmmary control when the field is not valid. Text: Sets the error message that is displayed by the control. IsValid: Indicates whether the validation is successful or not. MaximumValue: Specifies the maximum value of the allowed range. MinimumValue: Specifies the minimum value of the allowed range.

RegularExpressionValidtor: Used to validate the value of a control against a regular expression. Some of the important properties of this control are: ControlToValidate: Specifies the ID of the control to be validated. ErrorMessage: Specifies the error message to be displayed in the

ValidationSmmary control when the field is not valid. Text: Sets the error message that is displayed by the control. IsValid: Indicates whether the validation is successful or not. ValidationExpression: Specifies a regular expression used in the

validation.

8

Page 9: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

CustomValidator: Used to validate a control using custom validation routine. Some of the important properties of this control are: ControlToValidate: The ID of the control to be validated. ClientValidationFunction: Specifies the name of the client side

validation function. EnableClientScript: Enables/ disables client side form validation. ErrorMessage: Specifies the error message to be displayed in the

ValidationSmmary control when the field is not valid. Text: Sets the error message that is displayed by the control. IsValid: Indicates whether the validation is successful or not.

ValidationSummary: Display a list of validation errors if they occur on a web page. Some of the important properties of this control are: DisplayMode: Sets the formatting of the error messages displayed by

the control. HeaderText: Sets the text displayed at the top of the control. SHowMessageBox: When true, display the error messages in a pop

up dialogs. ShowSummary: Enables/ disables the summary of the error

messages.

The validation controls RequiredFieldValidator, RegularExpressionValidator, CompareValidator and ,CustomValidator have a method called Validate. The Validate method performs the required validation and updates the IsValid property. The method OnServerValidate of CustomValidator raises the ServerValidate event. ServerValidate event represents the function for performing the server side validation.

The validation controls use a script library written in JavaScript file called WebUIValidation.js. This JavaScript file is installed by default under C:\Inetpub\wwwroot\aspnet_client\system_web\1_1_4322 when .NET Framework is installed. The .NET tool aspnet_regiis can be used to install and uninstall the validation library. To install the script library, use the command:aspnet_regiis –c and to uninstall it use the command aspnet_regiis –e .Note: For more detail, see the .NET framework help.

9

Page 10: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Examples:

Ex1: CommandEx.aspx

This example shows how to handle the Command event for multiple commands. When the Command event is raised, the commandName and commandArgument properties are passed to this event. We can write one handler for Command event and test the commandName property to know which button has generated the event. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="CommandEventEx.aspx.vb" Inherits="CommandEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><title> Command Event Example </title>

</HEAD>

<body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server">

<asp:button id="btnGreen" style="Z-INDEX: 101; LEFT: 345px; POSITION: absolute; TOP: 213px"

runat="server" Text="Green" Width="105px" Height="30px" CommandName="Green" CommandArgument="Green"

OnCommand="Button_Command"></asp:button><asp:button id="btnBlue" style="Z-INDEX: 102; LEFT: 347px; POSITION: absolute; TOP: 277px" runat="server"

Text="Blue" Width="106px" Height="32px" CommandName="Blue" CommandArgument="Blue" OnCommand="Button_Command"></asp:button></form>

</body></HTML>

And below is the code behind for this example:

10

Page 11: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.XmlImports System.Drawing

Public Class CommandEx:Inherits Page Protected WithEvents btnGreen As System.Web.UI.WebControls.Button Protected WithEvents btnBlue As System.Web.UI.WebControls.Button

Public Sub Button_Command(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs)

Dim s As New Style

If e.CommandName = "Green" Then s.BackColor = Color.Green s.Width = Unit.Pixel(120)

btnGreen.ApplyStyle(s) btnGreen.Style.Item("top") = 100

ElseIf e.CommandName = "Blue" Then s.BackColor = Color.Blue s.Width = Unit.Pixel(150) btnBlue.ApplyStyle(s) btnBlue.Style.Item("top") = 150

End If Response.Write("Hello from " & e.CommandArgument & " button")

End Sub

End Class

11

Page 12: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Ex2:DynButtonsEx.aspx

We can add controls to a web form dynamically at run time. The following example adds a button control with its event handler programmatically at run time. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="DynButtonsEx.aspx.vb" Inherits="DynButtonsEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><title> Dynamic buttons Example </title>

</HEAD>

<body MS_POSITIONING="GridLayout"><form id="myForm" method="post" runat="server">

</form></body>

</HTML>

Notice that we have to add the form tag before we can add the button programmatically to the form. Following is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.XmlImports System.Drawing

Public Class DynButtonsEx:Inherits Page

Dim cmd(4) As Button Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

12

Page 13: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Dim i As Integer For i = 0 To cmd.Length - 1 cmd(i) = New Button cmd(i).Text = "button" & (i + 1) cmd(i).CommandName = "button" & (i + 1) AddHandler cmd(i).Command, AddressOf button_Command Me.Controls.Item(1).Controls.Add(cmd(i)) Next End Sub Public Sub Button_Command(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs) Dim index As Integer If e.CommandName = "button1" Then For index = 0 To cmd.Length - 1 If index = 0 Then cmd(index).BackColor = Color.Red Else cmd(index).BackColor = Color.LightGray End If Next index ElseIf e.CommandName = "button2" Then For index = 0 To cmd.Length - 1 If index = 1 Then cmd(index).BackColor = Color.Red Else cmd(index).BackColor = Color.LightGray End If Next index ElseIf e.CommandName = "button3" Then For index = 0 To cmd.Length - 1 If index = 2 Then cmd(index).BackColor = Color.Red Else cmd(index).BackColor = Color.LightGray End If Next index ElseIf e.CommandName = "button4" Then For index = 0 To cmd.Length - 1 If index = 3 Then cmd(index).BackColor = Color.Red Else cmd(index).BackColor = Color.LightGray End If Next index

13

Page 14: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

ElseIf e.CommandName = "button5" Then For index = 0 To cmd.Length - 1 If index = 4 Then cmd(index).BackColor = Color.Red Else cmd(index).BackColor = Color.LightGray End If Next index End If End SubEnd Class

Ex3:RadioEx.aspxThis example shows how to work with a group of radio button. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="RadioEx.aspx.vb" Inherits="RadioEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD></HEAD><body>

<form id="myForm" runat="server"><asp:RadioButton id="rdb1" runat="server"

Text="Email" GroupName="group1"/>

<asp:RadioButton id="rdb2" runat="server" AutoPostBack="True" Text="mail" GroupName="group1"/>

<asp:Button id="btn" runat="server" Text="Click" />

</form></body>

</HTML>

14

Page 15: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

And here is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.DrawingImports System.Xml

Public Class RadioEx:Inherits Page

Protected WithEvents rdb1 As System.Web.UI.WebControls.RadioButton

Protected WithEvents rdb2 As System.Web.UI.WebControls.RadioButtonProtected WithEvents btn As System.Web.UI.WebControls.Button

public Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click if rdb1.Checked Then response.write("button 1 is checked") Elseif rdb2.Checked Then response.write("button 2 is checked") End if End SubEnd Class

Ex4:RadioButtonListEx.aspx

This example adds a RadioButtonList and its event to a web form programmatically. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="RadioButtonListEx.aspx.vb" Inherits="RadioButtonListEx"%>

15

Page 16: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><title> RadioButtonList Example </title>

</HEAD>

<body MS_POSITIONING="GridLayout"><form id="myForm" method="post" runat="server">

</form></body>

</HTML>

And following is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.XmlImports System.Drawing

Public Class RadioButtonListEx:Inherits Page Dim rList As new RadioButtonList

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim arlist() = {"red", "green", "blue"} rList.DataSource = arlist rlist.DataBind() rlist.AutoPostBack = True AddHandler rlist.SelectedIndexChanged, AddressOf rList_SelectedIndexChanged Me.Controls.Item(1).Controls.Add(rList)End Sub Public Sub rList_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Response.Write(rlist.SelectedItem.Text) End SubEnd Class

16

Page 17: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Ex5:CheckBoxEx.aspxThis example utilizes a group of checkboxes and handles their events. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="CheckBoxEx.aspx.vb" Inherits="CheckBoxEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD></HEAD><body>

<form id="myForm" runat="server"><asp:checkbox id="chk1" runat="server"

AutoPostBack="True" Text="Java" OnCheckedChanged="chk1_CheckChanged"/>

<asp:checkbox id="chk2" runat="server" AutoPostBack="True" Text=".NET" OnCheckedChanged="chk2_CheckChanged"/>

</form></body>

</HTML>

Below is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.DrawingImports System.Xml

Public Class CheckBoxEx:Inherits Page

Protected WithEvents chk1 As System.Web.UI.WebControls.CheckBox

17

Page 18: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Protected WithEvents chk2 As System.Web.UI.WebControls.CheckBox

Public Sub chk1_CheckChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) response.write("h1") End Sub public Sub chk2_CheckChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) response.write("h2") End SubEnd Class

Ex 6: CheckBoxList.aspx

The following example demonstrates how to work with a CheckBoxList. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="CheckBoxListEx.aspx.vb" Inherits="CheckBoxListEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD></HEAD><body>

<form id="myForm" runat="server"><asp:checkboxlist id="cList" runat="server" >

<asp:ListItem Value="C">C</asp:ListItem><asp:ListItem Value="vb">vb</asp:ListItem><asp:ListItem

Value="JScript">JScript</asp:ListItem></asp:checkboxlist><P>&nbsp;

<asp:button id="btn1" runat="server" Text="Click"></asp:button></P>

<P></P>

</form></body>

</HTML> 

18

Page 19: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

And here is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.DrawingImports System.Xml

Public Class CheckBoxListEx:Inherits Page

Protected WithEvents cList As System.Web.UI.WebControls.CheckBoxList Protected WithEvents btn1 As System.Web.UI.WebControls.Button

Private Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn1.Click Dim item As ListItem

For Each item In cList.Items If item.Selected Then Response.Write(item.Text & " is selected<br/>") End If Next End SubEnd Class

Ex 7: TableGenEx.aspxIn this example we will generate an HTML table programmatically. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="TableGenEx.aspx.vb" Inherits="TableGenEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><title> Table Example </title>

19

Page 20: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

</HEAD>

<body MS_POSITIONING="GridLayout"></body>

</HTML>

And following is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.DrawingImports System.Xml

Public Class TableGenEx:Inherits Page Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim t As Table Dim r As TableRow Dim c As TableCell Dim i, j As Integer

t = New Table t.Visible = True t.BackColor = Color.Cyan t.BorderStyle = BorderStyle.Solid

t.CellPadding = 10 t.CellSpacing = 1 t.GridLines = GridLines.Both

For i = 0 To 5 r = New TableRow

For j = 0 To 4 c = New TableCell c.Controls.Add(New LiteralControl("Cell("& i &"," & j & ")" )) r.Cells.Add(c) Next t.Rows.Add(r) Next

20

Page 21: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Me.Controls.Add(t) End SubEnd Class

Ex 8:ValidateEx.aspx

This example illustrates the usage of validation controls. It utilizes the FieldRequiredValidator, CompareValidator, RegularExpressionValidator, and CustomValidator. CustomValidator requires a client side validation function to be provided in the aspx file. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="ValidateEx.aspx.vb" Inherits="ValidateEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><title>WebForm6</title><meta content="Microsoft Visual Studio .NET 7.1"

name="GENERATOR"><meta content="Visual Basic .NET 7.1"

name="CODE_LANGUAGE"><meta content="JavaScript" name="vs_defaultClientScript"><meta content="http://schemas.microsoft.com/intellisense/ie5"

name="vs_targetSchema"><script language="javascript" type="text/javascript">

function validateMe(source,arguments){

if ((arguments.Value=="IT") || (arguments.Value=="HR") )arguments.IsValid=trueelsearguments.IsValid=false

}</script>

</HEAD><body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server">

21

Page 22: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

<asp:customvalidator id="CustomValidator2" style="Z-INDEX: 101; LEFT: 303px; POSITION: absolute; TOP: 260px"

runat="server" ClientValidationFunction="validateMe" Width="213px" Height="17px" ErrorMessage="Wrong Department. Valid values are (IT, or HR)"

ControlToValidate="txtDep"></asp:customvalidator><asp:textbox id="txtID" style="Z-INDEX: 102; LEFT: 173px; POSITION: absolute; TOP: 83px" runat="server"

Width="56px" Height="19px"></asp:textbox><asp:TextBox id="txtPass" style="Z-INDEX: 103; LEFT:

173px; POSITION: absolute; TOP: 123px" runat="server"Width="76px" Height="21px"></asp:TextBox>

<asp:RequiredFieldValidator id="RequiredFieldValidator1" style="Z-INDEX: 104; LEFT: 301px; POSITION: absolute; TOP: 84px"

runat="server" Width="229px" Height="26px" ErrorMessage="ID should not be empty" ControlToValidate="txtID"></asp:RequiredFieldValidator>

<asp:CompareValidator id="CompareValidator1" style="Z-INDEX: 105; LEFT: 302px; POSITION: absolute; TOP: 170px"

runat="server" Width="246px" Height="12px" ErrorMessage="Password do not match" ControlToValidate="txtrPass"

ControlToCompare="txtPass"></asp:CompareValidator><asp:RegularExpressionValidator

id="RegularExpressionValidator1" style="Z-INDEX: 106; LEFT: 299px; POSITION: absolute; TOP: 205px"

runat="server" Width="254px" Height="22px" ErrorMessage="Postal code must be in the format [a-zA-Z][0-9][a-zA-Z][0-9][a-zA-Z][0-9]"

ControlToValidate="txtpCode" ValidationExpression="[a-zA-Z][0-9][a-zA-Z][0-9][a-zA-Z][0-9]"></asp:RegularExpressionValidator>

<asp:TextBox id="txtrPass" style="Z-INDEX: 107; LEFT: 173px; POSITION: absolute; TOP: 165px"

runat="server" Width="76px" Height="21px"></asp:TextBox>

<asp:TextBox id="txtpCode" style="Z-INDEX: 108; LEFT: 173px; POSITION: absolute; TOP: 208px"

runat="server" Width="62px" Height="19px"></asp:TextBox>

<asp:Label id="lblID" style="Z-INDEX: 109; LEFT: 25px; POSITION: absolute; TOP: 82px" runat="server"

Width="128px" Height="19">ID</asp:Label>

22

Page 23: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

<asp:Label id="lblPass" style="Z-INDEX: 110; LEFT: 25px; POSITION: absolute; TOP: 123px" runat="server"

Width="128px" Height="19px">Password</asp:Label>

<asp:Label id="lblrPass" style="Z-INDEX: 111; LEFT: 26px; POSITION: absolute; TOP: 167px" runat="server"

Width="129" Height="19">Re enter Password</asp:Label>

<asp:Label id="lblpCode" style="Z-INDEX: 112; LEFT: 26px; POSITION: absolute; TOP: 210px" runat="server"

Width="130" Height="19">Postal Code</asp:Label>

<asp:Label id="lblDep" style="Z-INDEX: 113; LEFT: 27px; POSITION: absolute; TOP: 254px" runat="server"

Width="130px" Height="19px">Department</asp:Label>

<asp:TextBox id="txtDep" style="Z-INDEX: 114; LEFT: 173px; POSITION: absolute; TOP: 254px" runat="server"

Width="57px" Height="22px"></asp:TextBox><asp:Button id="Button1" style="Z-INDEX: 115; LEFT:

50px; POSITION: absolute; TOP: 317px" runat="server"Width="136px" Height="39px"

Text="btnSubmit"></asp:Button></form></body>

</HTML>

Following is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.DrawingImports System.Xml

Public Class ValidateEx:Inherits Page

Protected WithEvents CustomValidator2 As System.Web.UI.WebControls.CustomValidator Protected WithEvents RequiredFieldValidator1 As System.Web.UI.WebControls.RequiredFieldValidator

23

Page 24: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Protected WithEvents CompareValidator1 As System.Web.UI.WebControls.CompareValidator Protected WithEvents RegularExpressionValidator1 As System.Web.UI.WebControls.RegularExpressionValidator Protected WithEvents txtID As System.Web.UI.WebControls.TextBox Protected WithEvents txtPass As System.Web.UI.WebControls.TextBox Protected WithEvents txtrPass As System.Web.UI.WebControls.TextBox Protected WithEvents txtpCode As System.Web.UI.WebControls.TextBox Protected WithEvents lblID As System.Web.UI.WebControls.Label Protected WithEvents lblPass As System.Web.UI.WebControls.Label Protected WithEvents lblrPass As System.Web.UI.WebControls.Label Protected WithEvents lblpCode As System.Web.UI.WebControls.Label Protected WithEvents lblDep As System.Web.UI.WebControls.Label Protected WithEvents txtDep As System.Web.UI.WebControls.TextBox Protected WithEvents Button1 As System.Web.UI.WebControls.Button Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If RequiredFieldValidator1.IsValid And CompareValidator1.IsValid And RegularExpressionValidator1.IsValid And CustomValidator2.IsValid Then Response.Write("Validation successful ") End If End Sub

End Class

Ex9: AddRotatorandCalendar.aspx

The following example utilizes an AddRotator and a Calendar. It uses the AddRotator to randomly display advertisements. The advertisements must be stored in an XML file with a certain format. The Calendar control is used to schedule appointments. Following is the user interface for this example:

<%@ Page Language="vb" AutoEventWireup="false" Src="AddRotatorandCalendar.aspx.vb" Inherits="AddRotatorandCalendar"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><title>WebForm7</title><meta content="Microsoft Visual Studio .NET 7.1"

name="GENERATOR">

24

Page 25: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">

<meta content="JavaScript" name="vs_defaultClientScript"><meta content="http://schemas.microsoft.com/intellisense/ie5"

name="vs_targetSchema"></HEAD><body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server"><asp:adrotator id="AdRotator1" style="Z-INDEX: 101;

LEFT: 175px; POSITION: absolute; TOP: 16px"runat="server" AdvertisementFile="ad.xml"

Height="65px" Width="230px"></asp:adrotator><asp:textbox id="txtNote" style="Z-INDEX: 103; LEFT: 35px; POSITION: absolute; TOP: 159px" runat="server"

Width="283px"></asp:textbox><asp:label id="lblNote" style="Z-INDEX: 104; LEFT: 34px; POSITION: absolute; TOP: 122px" runat="server"

Height="30px" Width="280px">Enter a note and book a schedule</asp:label><asp:calendar id="Calendar1" style="Z-INDEX: 105; LEFT: 325px; POSITION: absolute; TOP: 121px"

runat="server" Height="109px" Width="233px" ShowGridLines="True"></asp:calendar></form>

</body></HTML>

Following is the code behind for this example:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.XmlImports System.Drawing

Public Class AddRotatorandCalendar:Inherits Page private shared ar(13,32) as String Protected WithEvents AdRotator1 As System.Web.UI.WebControls.AdRotator Protected WithEvents Calendar1 As System.Web.UI.WebControls.Calendar

25

Page 26: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Protected WithEvents txtNote As System.Web.UI.WebControls.TextBox Protected WithEvents lblNote As System.Web.UI.WebControls.Label Private Sub Calendar1_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Calendar1.SelectionChanged Dim dt As DateTime dt = Calendar1.SelectedDate If ar(dt.Month, dt.Day) = "" Then ar(dt.Month, dt.Day) = txtNote.Text End If End Sub

Private Sub Calendar1_DayRender(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender Dim cell As TableCell cell = e.Cell Dim dt As DateTime dt = e.Day.Date If ar(dt.Month, dt.Day) <> "" Then cell.BackColor = Color.Blue cell.Controls.Add(New LiteralControl(ar(dt.Month, dt.Day))) End If End Sub End Class

The example uses a shared two dimensional array to store the scheduling appointments. Below is an XML file called ad.xml used to store the advertisements:

<?xml version="1.0" ?><!--Advertisements must be the root element in the document. it can have only Add as a child element --><Advertisements><Ad><!-- absolute or relative path to the image file to display on the addrotator--><ImageUrl>images\ACBLENDS.GIF</ImageUrl><!-- URL of th site to navigate when the user clicks the addrotator-->

<NavigateUrl>http://yahoo.com</NavigateUrl><!--The text to display if the image is not found --><AlternateText>Ad1</AlternateText><!-- The Impressions value indicates how often the add will be displayed.

26

Page 27: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

The higher the value, the more the add is displayed --><Impressions> 80</Impressions><!--Keyword is used to filter the add --><Keyword>software</Keyword></Ad>

<Ad><ImageUrl>images\HORZ1.BMP</ImageUrl><NavigateUrl>http://hotmail.com</NavigateUrl><AlternateText>Ad2</AlternateText><Impressions> 80</Impressions><Keyword>micro</Keyword></Ad>

</Advertisements>

Ex 10: RepaeterEx.aspx

This example shows how to construct a repeater control. First we add the repeater control to the User Interface of the application as shown below:

<%@ Page Language="vb" AutoEventWireup="false" Src="RepeaterEx.aspx.vb" Inherits="RepeaterEx"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>

<HEAD><title>WebForm8</title><meta name="GENERATOR" content="Microsoft Visual Studio

.NET 7.1"><meta name="CODE_LANGUAGE" content="Visual Basic .NET

7.1"><meta name="vs_defaultClientScript" content="JavaScript"><meta name="vs_targetSchema"

content="http://schemas.microsoft.com/intellisense/ie5"></HEAD><body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" runat="server"><!-- a repeater with its template --><asp:Repeater id="Repeater1" runat="server">

<HeaderTemplate><table border="1">

27

Page 28: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

<tr><td>St ID </td><td>St Name </td><td>Website </td></tr></HeaderTemplate><ItemTemplate><tr><td><%# DataBinder.Eval(Container.DataItem,"Student

ID") %></td><td><%# DataBinder.Eval(Container.DataItem,"Student

Name") %></td>

<td><a href=' <%# DataBinder.Eval(Container.DataItem,"Student website") %>'> <%# DataBinder.Eval(Container.DataItem,"Student website") %></a></td>

</tr>

</ItemTemplate><FooterTemplate></table>

</FooterTemplate>

</asp:Repeater></form>

</body></HTML>

As you can see, we are also required to add a template that determines how the repeater is display. <% # %> is called data binding expression. It create binding between a server control and a data source.

Following is the code behind for this application:

Imports SystemImports System.WebImports System.Web.UIImports system.DataImports System.Web.UI.WebControlsImports System.Xml

28

Page 29: Introduction to XMLmunro.humber.ca/~zouri/cpan660/cpan660-lec8.doc  · Web view. HTML controls must have the attribute . runat=”server” when used in a web form.

Imports System.Drawing

Public Class RepeaterEx:Inherits Page Protected WithEvents Repeater1 As System.Web.UI.WebControls.Repeater

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.LoadDim dt As New DataTableDim dr As DataRowDim header() As DataColumn = {New DataColumn("Student ID"), New DataColumn("Student Name"), New DataColumn("Student website")} ' add header column to the data table dt.Columns.AddRange(header) ' create data row from arrays Dim dd As DataRow Dim ar1() As String = {"111-111-111", "Muthana Abdullah", "http://hal.humberc.on.ca/~abdullah"} dr = dt.NewRow dr.ItemArray = ar1 dt.Rows.Add(dr) Dim ar2() = {"111-222-111", "Sally Brown", "http://hal.humberc.on.ca/~abcd0000"} dr = dt.NewRow dr.ItemArray = ar2 dt.Rows.Add(dr) ' create a data view from the data table Dim dv As New DataView(dt) ' initialize the repeator Repeater1.DataSource = dv Repeater1.DataBind() ' Notice that you have to provide ' a template in the HTML to format the repeater End Sub End Class

29