Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 116

ASP.

NET
• ASP.NET is a programming framework used to create Web
Applications for PC as well as mobile devises. 

• It allow programmers to build dynamic Web applications.

• ASP.NET is an event-driven, server-side programming model.


Why Web Applications are extremely popular ?

• No installation is required at client side

• Seamless upgrades
• Availability from any machine over a network like internet
or intranet without you having to install client software and
works as long as the user has a working browser
Web Applications
– A web application consists of a set of web pages that are
generated in response of user requests.

– A web application can be accessed through the web browser.

– Examples: Email, search engines, auction sites, news sites,


online trading, online shopping, social networking such as
Facebook.

Cntd..
Web Applications
– The components of a web application includes:
 Clients
 A server
 A network connecting clients to server
Web Forms
– For a web application, content is generated from a web form.

– A web application can contain many web forms.

– The browser submits a web form to the web server and the
server returns an HTML page in response.
What is rendering a web page? 

• User make request for a page.


• Browser sends this request to the web server.
• The server inspects the request and compiles it.
• The response object is created and sends the HTTP
response back to the browser.
• The browser receives the response, and parses the HTML in
the response.
ASP.NET Server-side Comments

• Allows you to include code comments in the body of an .aspx


file.
• These will not be processed on the server or rendered to the
resulting page.
• Syntax: <%-- comments here --%>

• In HTML a comment line is added as follows:


• Syntax: <!-- comments here -->
Web Server Controls
• Web server controls are created on the web server.
• They require a runat="server" attribute to work. 
• Defined in the System.Web.UI.WebControls namespace

• The syntax for creating a Web server control is:

< asp:control_name id="some_id" runat="server" />

They can be self closed by having a forward slash (/) before


the ending tag or have a closing tag:
• <asp:textbox id="txt" runat="server" /> 
<asp:textbox id="txt" runat="server" ></asp:textbox>
Hierarchy of Web Server Controls
Common web server control properties
How to add web server controls to a web form?

• You can drag controls from the Toolbox onto the design surface of
the page.

• Or, move the cursor to where you want the control in either Source
or Design view, and double click on the control in the Toolbox to
place it there.

• For the controls that ship with ASP.NET 4 you always use the asp:
prefix followed by the name of the control.
• Example;-
<asp:Button>
<asp:TextBox>
<asp:Label>
Label Control
• Label controls are used to display text on a form.

• <asp:label id="myLabel" Text= "Example of a label"


runat="server" />

• A textbox can be associated with a label by setting the


AccociatedControlID property of the Label control.

• If you click on a label with an associated textbox, focus will go to


the associated textbox.
Label Control Example

<asp:Label AccessKey="1" AssociatedControlID="TextBox1" ID="Label1"


runat="server" Text="Enter a Number<u>1</u>" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br />

<asp:Label ID="Label2" runat="server" AccessKey="2"


AssociatedControlID="TextBox2" Text="Enter a Number<u>2</u>" />

<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>


Text Property of Label Control

• Use the Text property to specify or determine the text content of


the Label control. 
Example:-
Label1.Text= "Enter a Number"
TextBox Control
Properties
• TextMode : Get or set the behavior mode of a text box.
– SingleLine – Single line text box
– MultiLine – Multiline text box
– Password – Password text box
• Text : Gets or sets the text content of text box.
• ID : to set or get identifier for text box.
• MaxLength : to set or get maximum number of characters allowed
for text box content.
• Rows : to set or get the physical height.(for multiline text box).
• Columns : to set the physical width of the text box.
• Font : to set the font of a text box.
TextBox Control
Example:-
<form id="Form1" runat="server">
A password TextBox:
<asp:TextBox id="t1" TextMode="password" runat="server" />
<br /><br />
A multiline TextBox:
<asp:TextBox id="t2" TextMode="multiline" runat="server" />
<br /><br /></form>
Focus Method
Sets input focus to a control. 
Example: t.Focus();
Setting TextBox Properties in Code
Behind file
Example:-
tb2.TextMode = TextBoxMode.MultiLine;
// The TextBoxMode enumeration represents the
// different display options for Textbox controls.
// SingleLine, MultiLine, Password
tb2.BorderColor = System.Drawing.Color.Blue;
Or
tb2.BorderColor = System.Drawing.Color.FromArgb(255, 0, 0);
tb2.Font.Name = “verdana";
tb2.Font.Size = 24;
tb2.ForeColor = System.Drawing.Color.FromName("Yellow");
TextChanged Events
• Occurs when the content of the text box changes between posts to the
server.
// Aspx
<asp:TextBox id= " t1" Font-Bold="true" AutoPostBack="true"
OnTextChanged= " txtchanged" Font-Names="TIMES" runat="server" />
<asp:TextBox id= " t2" Font-Bold="true" runat="server" />
// AutoPostBack means that if any change happens on a control
//by the client, it should postback to the server to handle that
//change at server side.
//code behind
protected void txtchanged(object sender, EventArgs e)
{
t2.Text =t1.Text;
}
Button Control
• Push Button
• Basic syntax for button controls:
<asp:Button ID="Button1" runat="server" Text="Button" />
• Following are the common properties of Button control.
Property Description
Text The text displayed by the button.
CausesValidationDetermines whether page validation occurs when a user
clicks the button. The default is true.
CommandName A string value that's passed to the Command event when a
user clicks the button.
CommandArgument A string value that's passed to the Command event when a
user clicks the button.
PostBackUrl The URL of the page that should be requested when the
user clicks the button.
Click Event Vs. Command Event
• Both these events are raised when the Button control is clicked.

• If both event handlers are present in a page then:


– Click event handler is performed first
– Then command handler is performed.

• The click event of a button does not send any parameters to the code
behind file.

• Where as the Command will send parameters like CommandName


and CommandAgrument to codeBehind code.
Button Control
• To change background color of ASP.NET page add bgcolor parameter to
<body > tag.
• By default, body tag is not visible to server side code. Add runat="server"
attribute to make body visible to server.
• Also specify an ID to the body tag to refer it in the code behind
• <body id= "pbBody" runat="server">
CodeBehind File
protected void Button1_Click(object sender, EventArgs e)
{
pbBody.Attributes.Add("bgcolor", "red");
}
protected void Button2_Click(object sender, EventArgs e)
{
pbBody.Attributes.Add("bgcolor", "green");
}
protected void Button3_Click(object sender, EventArgs e)
{
pbBody.Attributes.Add("bgcolor", "blue");
}
CssClass
• The CssClass property enables you to set the style sheet class for
a control.
• Internal Style: By including <style> tag in head section
<style runat="server" type="text/css" >
.abc
{
font: "arial"; font-size:14pt;
font-weight:bold; color: white; background:#A7C942;
border-color:Lime; border-style:inset;
border-width:2pt;
} </style>
• External Style through .CSS file

<link href="StyleSheet.css" rel="stylesheet" type="text/css" />


How to set CssClass Property?

<asp:TextBox ID="TextBox1" CssClass="abc" />


DropDownList

• It is a single selection list of items. (User can select one item


from the list provided)
• To add items to the list, you define <asp:ListItem>
• The property SelectedValue or SelectedItem or SelectedIndex
can be used to get the selected item from the drop down list.
DropDownList Example
aspx code
• To add items to the list, you define <asp:ListItem> elements
between the opening and closing tags of the control, as shown in
the following example:

<asp:DropDownList ID= "l1" runat="server"


onselectedindexchanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Value= " 1 " >Cricket</asp:ListItem>
<asp:ListItem Value= " 2 " >Tennis</asp:ListItem>
<asp:ListItem Value= " 3 " >Football</asp:ListItem>
</asp:DropDownList>
DropDownList
• The DropDownList class is derived from System.Web.UI.WebControls.ListControl

• ListControl.Items Property
• public virtual System.Web.UI.WebControls.ListItemCollection Items { get; }

• ListItemCollection class
• The ListItemCollection class represents a collection of ListItem objects. 
• The ListItem objects, in turn, represent the items displayed in list controls such
as the DropDowmList and ListBox.
• Methods
Add(String) //Appends a ListItem to the end of the collection that represents the specified string.

Add(ListItem) //Appends the specified ListItem to the end of the collection.


DropDownList

• ListItem class
• It is a sealed library class.
• ListItem(String) --- Initializes a new instance of the ListItem class
with the specified text data.
• ListItem(String, String) ---- Initializes a new instance of the 
ListItem class with the specified text and value data.
ListItem

Property Description
Selected Gets or sets a value indicating whether the item is
selected.

Text Gets or sets the text displayed in a list control for


the item represented by the ListItem.

Value Gets or sets the value associated with the ListItem.


DropDownList

• Adding items in DropDownList through c# code


• DropDownList1.Items.Add(“Cricket”);
• DropDownList1.Items.Add(“Football”);
• DropDownList1.Items.Add(“Bascket Ball”);
SelectedIndexChanged Event
• SelectedIndexChanged event occurs when the selection from the list
control changes between posts to the server.
• OnSelectedIndexChanged method raises
the SelectedIndexChanged event.
• This allows you to provide a custom handler for the event. 
Code file
protected void DropDownList1_SelectedIndexChanged(object sender,
EventArgs e)
{
Label1.Text="The selected item is: "+l1.SelectedValue;
}
ListBox

• It is a multi-selection list. (User can select more than one

item from the list provided)

• To add items to the list, you define <asp:ListItem>


ListBox Properties
Property Description

Rows Sets the number of rows displayed in the list


Items Gets the items of the list
SelectionMode Specifies how a users is allowed to select items. The
ListSelectionMode enumeration is present in
System.Web.UI.WebControls namespace can have one of the
following values:
Single - Default. Multiple items can not be selected
Multiple - Multiple items can be selected
SelectedValue Gets the value of the selected item. (Returns string)
SelectedItem Gets an object that represents the current selection in the
control
(Returns an object of ListItem)
SelectedIndex Gets the index of the selected item. (Returns integer)
Write code for printing all selected items from the ListBox

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)


{
Label1.Text = "";
for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListItem li = ListBox1.Items[i];
if (li.Selected)
Label1.Text += li.Text + "<br>";
}
}
GetSelectedIndices() Method of
ListBox

• Gets the array of index values for currently selected items in


the ListBox control.

• public virtual int[] GetSelectedIndices()
• Say for example, if ID of the list box is ‘ListBox1’ then the following code
displays all selected items from the list box to a label with ID ‘Label1’.

int[] x = ListBox1.GetSelectedIndices();
Label1.Text = "";
for (int i = 0; i < x.Length; i++)
Label1.Text += ListBox1.Items[x[i]].Text + "<br>";
SelectedIndexChanged Event

• SelectedIndexChanged event occurs when the selection from the


list control changes between posts to the server.
• OnSelectedIndexChanged method raises
the SelectedIndexChanged event.
• This allows you to provide a custom handler for the event. 
ListBox Example
aspx code
• To add items to the list, you define <asp:ListItem> elements between the
opening and closing tags of the control, as shown in the following example:
<asp:ListBox ID="ListBox1" SelectionMode="Multiple" AutoPostBack="true"
runat="server" onselectedindexchanged="ListBox1_SelectedIndexChanged">
<asp:ListItem Value="0">Win7</asp:ListItem>
<asp:ListItem Value="1">Linux</asp:ListItem>
<asp:ListItem Value="2">Mac</asp:ListItem>
<asp:ListItem Value="3">Vista</asp:ListItem> </asp:ListBox>
Code file
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e) {
int[] x = ListBox1.GetSelectedIndices();
Label1.Text = "";
for (int i = 0; i < x.Length; i++)
Label1.Text += ListBox1.Items[x[i]].Text + "<br>"; }
CheckBoxList
• The CheckBoxList control is used to
create a multi-selection check box
group.
• To add items to the list, you define
<asp:ListItem>
CheckBoxList Properties
Property Description
CellPadding The amount of pixels between the border and the
contents of the table cell
CellSpacing The amount of pixels between table cells
RepeatColumns The number of columns to use when displaying the
check box group
RepeatDirection Specifies whether the check box group should be
repeated horizontally or vertically
runat Specifies that the control is a server control. Must be set
to "server"
TextAlign On which side of the check box the text should appear
lign
t A i gn
Tex t tA l
Lef Tex ht
Ri g
CheckBoxList Example
aspx code: <asp:CheckBoxList AutoPostBack="true" CellSpacing="2"
CellPadding="10" RepeatDirection="Vertical" ID="CheckBoxList1"
runat="server"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged">
<asp:ListItem Value="0">Windows 7</asp:ListItem>
<asp:ListItem Value="1">Macintosh</asp:ListItem>
<asp:ListItem Value="2">Linux</asp:ListItem> </asp:CheckBoxList>
Code file
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
ListItemCollection o= CheckBoxList1.Items;
Label1.Text = "";
for (int i = 0; i < o.Count; i++)
{
if(o[i].Selected)
Label1.Text += CheckBoxList1.Items[i].Text + "<br>";
}
}
CheckBox

• Displays a check box that allows the user to select a true or


false condition.
• The CheckBox controls are used to create a multi-selection
check box group.
• In CheckBox control the check and uncheck checkbox
specify by the checked property of check box true or false.
CheckBox
Property Description
AutoPostBack Specifies whether the form should be posted immediately
after the Checked property has changed or not. Default is
false
Checked Specifies whether the check box is checked or not
Text Gets or sets the text label associated with the CheckBox.
TextAlign Gets or sets the alignment of the text label associated with
the CheckBox control.
runat Specifies that the control is a server control.  Must be set to
"server"

• Event: CheckedChanged

Occurs when the value of the Checked property changes between posts


to the server.
CheckBox Example
aspx code: <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True"
oncheckedchanged="Common_CheckedChanged" Text="Windows 7" />
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True"
oncheckedchanged="Common_CheckedChanged" Text="Macintosh" />
<asp:CheckBox ID="CheckBox3" runat="server" AutoPostBack="True"
oncheckedchanged="Common_CheckedChanged" ext="Linux" />
Code file
protected void Common_CheckedChanged(object sender, EventArgs e)
{ String str="";
if (CheckBox1.Checked)
str = str + "Windows 7" + "</br>";
if (CheckBox2.Checked)
str = str + "Macintosh" + "</br>";
if (CheckBox3.Checked)
str = str + "Linux" + "</br>";
Label1.Text = str;
}
RadioButtonList

• The RadioButtonList control is used to create a

single-selection radio button group.

• To add items to the list, you define

<asp:ListItem>
RadioButtonList
Property Description
CellPadding The amount of pixels between the border and the
contents of the table cell
CellSpacing The amount of pixels between table cells
RepeatColumns The number of columns to use when displaying the
check box group
RepeatDirection Specifies whether the check box group should be
repeated horizontally or vertically
runat Specifies that the control is a server control. Must be set
to "server"
TextAlign On which side of the check box the text should appear
RadioButtonList Example
aspx code
<asp:RadioButtonList AutoPostBack="true" CellSpacing="2"
CellPadding="10" RepeatDirection="Vertical" ID="r1" runat="server"
onselectedindexchanged="r1_SelectedIndexChanged">
<asp:ListItem Value="0">Windows 7</asp:ListItem>
<asp:ListItem Value="1">Macintosh</asp:ListItem>
<asp:ListItem Value="2">Linux</asp:ListItem>
</asp:RadioButtonList>
Code file
protected void r1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = RadioButtonList1.SelectedItem.Text;
}
RadioButton

• The RadioButton controls are used to create a single-selection radio

button group.

• In RadioButton control the check and uncheck checkbox specify by the

checked property of check box true or false.


RadioButton
Property Description
AutoPostBack Specifies whether the form should be posted immediately after
the Checked property has changed or not. Default is false
Checked Specifies whether the check box is checked or not
Text Gets or sets the text label associated with the CheckBox.
TextAlign Gets or sets the alignment of the text label associated with
the CheckBox control.
runat Specifies that the control is a server control.  Must be set to
"server"
GroupName Gets or sets the name of the group that the radio button belongs
to.

• Event: CheckedChanged

Occurs when the value of the Checked property changes between posts


to the server.
Panel
• Panel control act as container for other controls.
• This control can be used to display and hide groups of controls.

Properties Description
BackImageUrl URL of the background image of the panel.

Direction Text direction in the panel.


GroupingText Set or return caption text for the group of controls
in the Panel Control.
HorizontalAlign Horizontal alignment of the content in the panel.

ScrollBars Specifies visibility and location of scrollbars


within the panel.
Wrap Allows text wrapping in the Panel control .
Panel

<asp:Panel Width="200" GroupingText="Operating System" ID="Panel1"


runat="server">
Select Any Operating System<br />
<asp:CheckBoxList AutoPostBack="true" ID="l1" runat="server" >
<asp:ListItem Value="0">Win7</asp:ListItem>
<asp:ListItem Value="1">Mac</asp:ListItem>
<asp:ListItem Value="2">Linux</asp:ListItem>
</asp:CheckBoxList>
</asp:Panel>
Validation Controls
• They are web server controls used for the validation of form fields.
• These controls are included in System.Web.UI.WebControls namespace.
• They are used to validate the user input.
• They can perform both server-side and client-side validation.
• Following are the validation controls:

1. RequiredFieldValidator Control
2. RangeValidator Control
3. RegularExpressionValidator Control
4. CompareValidator Control
5. CustomValidator Control
Validation Controls
Common Validator Properties
RequiredFieldValidator Controls
• It ensures that the user has entered a value in the associated input
control.
• Use the RequiredFieldValidator control to make an input control a
mandatory field.
• By default, the initial value is an empty string (""), which
indicates that a value must be entered in the input control for it to
pass validation.
•  Both server-side and client-side validations are performed 
RequiredFieldValidator Properties
Property Description
ControlToValidate The ID of the control to validate
Display •None (the control is not displayed and error message is shown in the
ValidationSummary control)
•Static (in case of failure error message is shown in the space reserved).
•Dynamic (In case of failure error message is shown. Space is not
reserved.)
EnableClientScript A Boolean value that specifies whether client-side validation is enabled
or not
Enabled A Boolean value that specifies whether the validation control is enabled
or not
ErrorMessage The text to display in the ValidationSummary control when validation
fails. Note: This text will also be displayed in the validation control if the
Text property is not set
id A unique id for the control
InitialValue Specifies the starting value of the input control. Default value is ""
runat Specifies that the control is a server control. Must be set to "server"
Text The message to display when validation fails
ValidationGroup  Using this property we can assign every validation control to a group.
SetFocusOnError Set focus to the input control in case of error.
A property of required field validator
RequiredFieldValidator Example
• The RequiredFieldValidator control is used to make an input control a required
field.
.
.
.
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Enter your name:"></asp:Label>
<asp:textbox id="Name" runat="server"/>
<asp:RequiredFieldValidator id="rfv" runat="server"
ControlToValidate="Name"
ErrorMessage="*Name is mandatory" ForeColor="Red"
Display="dynamic"> </asp:RequiredFieldValidator>
<asp:Button ID="Button1" runat="server" Text="Update Button" />
</form>
.
.
.
ValidationSummary
• The ValidationSummary control does not perform any validation but
shows a summary of all errors in the page.
• The summary displays the values of the ErrorMessage property of all
validation controls that failed validation.
• The following are two important properties:

• ShowSummary: shows the error messages in specified format.


• ShowMessageBox: shows the error messages in a separate window.
• The syntax for the control:

• <asp:ValidationSummary ID="ValidationSummary1" runat="server"


DisplayMode = "BulletList" ShowSummary = "true"
HeaderText="Errors:" />
RangeValidator Controls
• The RangeValidator control is used to check whether the user
enters an input value that is within a specified range.
• Applicable for range of numbers, dates, and characters.
• Both server-side and client-side validation are performed 

<html> <body> <form id="Form1" runat="server">


Enter a number from 1 to 100:
<asp:TextBox id="t1" runat="server" /> <br /><br />
<asp:Button ID="b1" Text="Click" runat="server" />
<asp:RangeValidator ID="RangeValidator1"
ControlToValidate="t1" MinimumValue="1" MaximumValue="100"
Type="Integer" EnableClientScript="false"
Text="The value must be from 1 to 100!"
runat="server" /> </form> </body> </html>
RangeValidator Properties
Property Description
ControlToValidate The id of the control to validate
Display •None (the control is not displayed and error message is shown in the
ValidationSummary control)
•Static (in case of failure error message is shown in the space reserved).
•Dynamic (In case of failure error message is shown. Space is not
reserved.)
EnableClientScript A Boolean value that specifies whether client-side validation is enabled or
not
Enabled A Boolean value that specifies whether the validation control is enabled or
not
ErrorMessage The text to display in the ValidationSummary control when validation
fails.Note: This text will also be displayed in the validation control if the
Text property is not set
Id A unique id for the control
MaximumValue Specifies the maximum value of the input control
MinimumValue Specifies the minimum value of the input control
Runat Specifies that the control is a server control. Must be set to "server"
Type •Specifies the data type of the value to check. The types are:
Currency, Date, Double, Integer, String
Text The message to display when validation fails
CompareValidator Control
• The CompareValidator control is used to compare the value of one
input control to the value of another input control or to a fixed
value.
<html><body>
<form id="Form1" runat="server">
<asp:TextBox id="t1" runat="server" /> =
<asp:TextBox id="t2" runat="server" />
<asp:Button ID="Button1" Text="Validate" runat="server" />
<br />
<asp:CompareValidator id="c" Display="dynamic"
ControlToValidate="t1" ControlToCompare="t2"
Type="String" EnableClientScript="false"
Text="Validation Failed!"
runat="server" />
</form> </body></html>
CompareValidator Control Properties
Property Description
ControlToCompare The name of the control to compare with
ControlToValidate The id of the control to validate
Display • None (the control is not displayed and error message is shown in the
ValidationSummary control)
• Static (in case of failure error message is shown in the space reserved).
• Dynamic (In case of failure error message is shown. Space is not reserved.)
EnableClientScript A Boolean value that specifies whether client-side validation is enabled or
not
Enabled A Boolean value that specifies whether the validation control is enabled or not
ErrorMessage The text to display in the ValidationSummary control when validation
fails. Note: This text will also be displayed in the validation control if the
Text property is not set
id A unique id for the control
Operator The type of comparison to perform. The operators are: Equal, GreaterThan,
GreaterThanEqual, LessThan, LessThanEqual, NotEqual, DataTypeCheck
runat Specifies that the control is a server control. Must be set to "server"
Text The message to display when validation fails
Type Specifies the data type of the values to compare. The types are: Currency,
Date, Double, Integer, String
ValueToCompare A specified value to compare with
CustomValidator Control
• Validation is done based on a validation function.
• The control allows you to validate both client side and server
side.
Custom Validator Control Properties
Property Description
ClientValidation Specifies the name of the client-side validation script function to be
Function executed. 
ControlToValidate The id of the control to validate
Display • None (the control is not displayed and error message is shown in the
ValidationSummary control)
• Static (in case of failure error message is shown in the space reserved).
• Dynamic (In case of failure error message is shown. Space is not
reserved.)
EnableClientScript A boolean value that specifies whether client-side validation is enabled or not
Enabled A boolean value that specifies whether the validation control is enabled or
not
ErrorMessage The text to display in the ValidationSummary control when validation
fails. Note: This text will also be displayed in the validation control if the
Text property is not set
Id A unique id for the control
IsValid A Boolean value that indicates whether the control specified by
ControlToValidate is determined to be valid
OnServerValidate Specifies the name of the server-side validation script function to be executed
runat Specifies that the control is a server control. Must be set to "server"
Text The message to display when validation fails
CustomValidator Example
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<html><head>
<title></title></head> <body>
<form id="Form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Enter a username: " />
<asp:TextBox id="txt1" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server"/><br />
<asp:Label id="mess" runat="server"/> <br />
<asp:CustomValidator ID="CustomValidator1"
ControlToValidate="txt1" OnServerValidate="txt1_Validate"
forecolor="Red" Text="A username must be more than 8 characters!"
runat="server"/>
</form></body></html>
CustomValidator Example
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) { }
protected void cv1_ServerValidate(object sender, ServerValidateEventArgs e)
{
if (e.Value.Length >= 8)
e.IsValid = true;
else
e.IsValid = false;
}
}
RegularExpressionValidator Control
• The RegularExpressionValidator control is used to ensure that
an input value matches a specified pattern.
• These patterns are called regular expressions or regex.
• Patterns consists of literal characters and special characters.
• Literal characters are normal characters with no special
meaning where as special characters have special meaning in
the pattern.
•  Both server- and client-side validation are performed 
Special Characters used in Pattern
Spl. C. Meaning Example
. Matches Single Character Pattern m..h matches much
() Groups literal characters into a Pattern ..(joy). matches enjoys
string that must be matched exactly.
(||) or [] Contains a group of allowable (or Pattern m(a|o)m matches mam,mom
nonallowable) characters Pattern m[ao]m matches mam,mom
- All characters between two characters Pattern m[a-c]m matches mam,mbm,mcm
Or all numbers between two numbers Pattern [0-9] matches any digits
Pattern [a-z] matches any alphabets.

+ Matches one or more occurrence of Pattern Ra+m matches Ram,Raam,Raaam


preceding item etc.
* Matches a character or expression Pattern a[c-f]*e matches ae,ace,acce,acfe etc.
zero or more times
{,} Range of repetition a{5} matches aaaaa
a{2,4} matches aa, aaaa
RegularExpressionValidator Properties
Property Description

ControlToValidate The id of the control to validate


Display • None (the control is not displayed and error message is shown in the
ValidationSummary control)
• Static (in case of failure error message is shown in the space reserved).
• Dynamic (In case of failure error message is shown. Space is not
reserved.)
EnableClientScript A Boolean value that specifies whether client-side validation is enabled or
not
Enabled A Boolean value that specifies whether the validation control is enabled or
not
ErrorMessage The text to display in the ValidationSummary control when validation
fails. Note: This text will also be displayed in the validation control if the
Text property is not set
id A unique id for the control
IsValid A Boolean value that indicates whether the control specified by
ControlToValidate is determined to be valid
runat Specifies that the control is a server control. Must be set to "server"
Text The message to display when validation fails
ValidationExpressio Specifies the expression used to validate input control.
n
RegularExpressionValidator
<html>
<body>
<form id="Form1" runat="server">
Enter your Mobile no:
<asp:TextBox id="t1" runat="server" />
<asp:Button ID="B1" text="Click" runat="server" />
<asp:RegularExpressionValidator ID="REV1"
ControlToValidate="t1"
ValidationExpression="[0-9]{10}"
EnableClientScript="false"
forecolor="Red"
ErrorMessage="Mobile number must be of 10 digits"
runat="server" />
</form>
</body></html>
Rich Controls
• They are web server controls built with multiple HTML
elements and contain rich functionality. 

•  Calendar control and the AdRotator control are Examples of


rich controls.
Calendar Control
• The Calendar control has a rich set of properties and events.

• It allows you to perform the following tasks:

--Selecting a day, a week or a month.


--Selecting a range of days.
• The basic control markup of Calendar is as follows:

<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar>


Calendar Control Properties
Property Description

Caption Gets or sets the caption for the calendar control.


DayNameFormat Sets format of days of day names.
SelectedDate Gets a DateTime object representing the selected date.
Gets a collection of DateTime objects representing the
SelectedDates selected dates.
SelectionMode Sets the selection mode that specifies whether the user
can select a single day, a week or an entire month.
Possible values are:
• None
• Day
• DayWeek
• DayWeekMonth

ShowGridLines Set whether to show gridlines or not.


ShowNextPrevMonth Set whether to show next and previous month navigation
elements.

Cntd. to next slide


Calendar Control Properties
Property Description

ShowTitle Set whether to show title or not.


ShowDayHeader Set whether to show day header or not.
SelectMonthText Gets or sets the text for the month selection element in
the selector column.
SelectWeekText Gets or sets the text displayed for the week selection
element in the selector column.
NextPrevFormat Sets the format of the next and previous month
navigation control. Vales:
• CustomText
• ShortMonth
• FullMonth
TitleFormat Sets the format for the title section. Values:
• Month
• MonthYear

Cntd. to next slide


Calendar Control Style Properties
Property Description

DayHeaderStyle Sets style for the day heading part ( weekdays name)
DayStyle Sets the style properties for the days in the displayed
month.
NextPrevStyle Sets style for Previous and Next month navigation
part.
OtherMonthDayStyle Sets style for the numbered tiles which comes from
previous month and next month.
SelectedDayStyle Sets style for all the days selected in the control.
SelectorStyle Sets style for the Week and Month Selector of it.
TitleStyle Sets style for the Calendar’s Title( Month and Year )
TodaysDayStyle Sets style for the Today’s Date.
WeekendDayStyle Sets style for numbered tile which comes from
weekend days.
Cntd. to next slide
Calendar Control Events
Event Description
SelectionChanged It is raised when a day, a week or an entire
month is selected.

DayRender It is raised when each data cell of the


calendar control is rendered.

VisibleMonthChanged It is raised when user changes a month.


System.DateTime Structure
• Properties
– Now (Gets a DateTime object that is set to the current date and
time on this computer, expressed as the local time.)
– Today (Gets a DateTime object that is set to the current date and
time component to zero.)
– Day (Gets the day of the month represented by this instance.)

– Month (Gets the month component of the date represented by


this instance.)
– Year (Gets the year component of the date represented by this
instance.)
Displaying Selected Date from a Calendar

protected void Calendar1_SelectionChanged(object sender, EventArgs e)


{
DateTime d = Calendar1.SelectedDate;
Label1.Text = "" + d.Day + ":" + d.Month + ":" + d.Year;
}
How to display a range of dates as holidays
Hashtable ht;
protected void Page_Load(object sender, EventArgs e)
{
ht = new Hashtable();
ht["26/1/2020"] = "Republic Day";
ht["10/3/2020"] = "Holi";
ht[“2/4/2020"] = "Ram Navami";
ht["10/4/2020"] = "Good Friday";
ht["15/8/2020"] = "Independence Day";
ht["30/8/2020"] = "Muharram";
ht[“2/10/2020"] = "Gandhi Jayanti";
ht["25/10/2020"] = "Dussehra";
ht["25/12/2020"] = "Christmas";
}
How to display a range of dates as holidays
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{

DateTime d = e.Day.Date;
string s = d.Day + "/" + d.Month + "/" + d.Year;
if (ht[s] != null)
{
Literal x = new Literal();
x.Text = "<br/>";
e.Cell.Controls.Add(x);
Label lb = new Label();
lb.Text = ""+ht[s];
e.Cell.Controls.Add(lb);
}
}
Selecting entire week or month

protected void Calendar1_SelectionChanged(object sender, EventArgs e)


{
Label1.Text="";
SelectedDatesCollection dc = Calendar1.SelectedDates;
foreach(DateTime d in dc)
{

Label1.Text += "" + d.Day + ":" + d.Month + ":" + d.Year+"<br/>";


}
}
AdRotator Control
• Like Calendar, the AdRotator is a web server control of asp.net.

• It displays a different image each time a user enters or refreshes a


page

• It randomly picks banner from a list of banners specified in an


external XML file.

• This XML file is known as advertisement file.


Advertisement File
<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl> https://www8.hp.com/in/en/home.html </NavigateUrl>
<AlternateText> Order HP Laptops </AlternateText>
<Impressions> 10 </Impressions>
<Keyword> laptop </Keyword>
</Ad>
<Ad>
.
.
.
</Ad>
</ Advertisements>
Advertisement File XML Tages
Element Description
Advertisements Beginning of Advertisement
Ad Describe separate ad.
ImageUrl The path of image that will be displayed.
NavigateUrl The link that will be followed when the user clicks the ad.
AlternateText The text displayed if the picture cannot be displayed.
Keyword Category of the ad, which can be used to filter for specific
ads.
Impressions Frequency of ad to be displayed. 
Height Height of the ad in pixels.
Width Width of the ad in pixel. 
XMLFile1.xml
<Advertisements>
<Ad>
<ImageUrl>r1.jpg</ImageUrl>
<NavigateUrl>http://www.google.com</NavigateUrl>
<AlternateText> Order roses </AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>
<Ad>
<ImageUrl>r2.jpg</ImageUrl>
<NavigateUrl>http://www.chmcollege.in</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
<Ad>
</Advertisements>
Site Navigation
• Site Navigation allows you to navigate to other pages of
your site easily. 

• Following are the Site Navigation controls in ASP. Net.


Menu
SiteMapPath
TreeView
Site Map (Web.sitemap file)
• Web.sitemap contains XML tags that define the site structure.

• Sitemap file is created in the application root directory.

• The navigation controls consume this file and display its contents as

a menu, tree, or sitemappath.

• Sitemap file basically contains the following XML elements:


 siteMap - It is the root element (occurs only once in the file).

 siteMapNode. (One per each page).


siteMapNode
• The sitemap represent a hierarchical structure of the site.
• A sitemap file can have a set of siteMapNode element.
• Each siteMapNode defines a page in the site.
• The top siteMapNode represents the home page.

• Each siteMapNode should have a unique URL.


Site Map Example

<?xml version="1.0" encoding="utf-8" ?>


<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="~/Default.aspx" title= " Home Pages" description="">
<siteMapNode url="~/Page1.aspx" title="Page 1" description="" />
<siteMapNode url="~/Page2.aspx" title="Page 2" description="" />
<siteMapNode url="~/Page3.aspx" title="Page 3" description="" />
<siteMapNode url="~/Page4.aspx" title="Page 4" description="" />
</siteMapNode>
</siteMap>
Site Map (with sub menu structure)
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="~/Default.aspx" title="Master Pages" description="">
<siteMapNode url="~/Page1.aspx" title="Page 1" description="" />

<siteMapNode url="~/Page2.aspx" title="Page 2" description="" />


<siteMapNode url="~/Default2.aspx" title="Transactions" description="">

<siteMapNode url="~/Page3.aspx" title="Page 3" description="" />

<siteMapNode url="~/Page4.aspx" title="Page 4" description="" />

</siteMapNode>
</siteMapNode>

</siteMap>
SiteMapDataSource Control
• A TreeView or Menu should be bound to SiteMapDataSourceControl.
Ways to create a SitemapDataSource
• There are two ways:

1. Drag the control from the Toolbox. ( ToolBox >> Data >>

SiteMapDataSource)

2. Click the Smart Tag icon in the upper right corner of TreeView or

Menu control, then select New Data Source in the Choose Data

Source drop-down list.


Menu Control
• Displays a navigation hierarchy as links.

• Menu display modes:


 Static (menu is fully expanded all the time)
 Dynamic (child menu items are visible only when the user place
the mouse pointer over the parent node)

• Menu items can be added to the control by specifying them in

the Items property.

• The Items property gives a collection of MenuItem objects.   

• Must be bound to a SiteMapDataSourceControl.


TreeView Control

• It displays hierarchical data in a tree structure in a Web page.

• The TreeView contains one or more nodes. 

• Each node is a link that represents a page in the

web site.

• Users can click these tree nodes to navigate to the

corresponding web page.


SiteMapPath Control

• SiteMapPath control is a series of links that lead the let the user to

find his or her way back to home page.

• These links are also known as bread crumbs. 

• No SiteMapDataSource is required.

• Sitemap file is required.

• It directly gets the navigation information from the sitemap file.


Code Behind Model
• The ASP.Net Framework provides a new style of coding to develop web
pages. This is called Code-Behind.
• In Code Behind Model server maintains two types of files.

1. The HTML code page with .aspx extension maintains the code for
User Interface design.
2. The .aspx.cs file maintains the program logic.
• The file that contain the programming logic (.aspx.cs file) is known as
the code behind file.
• Only server controls can interact with the code behind the page; not the
HTML controls.
Code Behind Model
Using Code Behind Class
• The code behind class inherits from the Page class in the
System.Web.UI namespace.
• Therefore our web page inherits methods and properties from Page
class.
• All ASP.NET pages inherits from the Page class, or from a class which
inherits from the Page class.
Using Code Behind Class
• Visual Studio .NET uses Codebehind attribute to maintain a reference to
the associated code-behind file for the .aspx page.

• <%@ Page Language="C#" AutoEventWireup="true"

CodeBehind="WebForm1.aspx.cs"

Inherits="WebApplication15.WebForm1" %>
Using Code Behind Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication16
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
}
}
Working of Code Behind Model
1. The code-behind file contains a partial class that inherits from Page class.

2. The .aspx file contains an Inherits attribute in the @ Page directive that
points to the code-behind partial class.

3. When the page is compiled, ASP.NET generates a partial class based on


the .aspx file; this class is a partial class of the code-behind class file.

4. Then ASP.NET generates another class that inherits from the class generated
in Step 3. This class contains the code required to build the page.
Stages in ASP.Net Page Life Cycle
Stage Description
When the page is requested by a user, ASP.NET determines whether to
Page request parse and compile the page or there would be a cached version of the
page; accordingly the response is sent
In the start stage, page properties such as Request and Response are set.
Start At this stage, the page also determines whether the request is a postback
or a new request and sets the IsPostBack property.
During page initialization, controls on the page are available and each
Initialization
control's UniqueID property is set.
During load, if the current request is a postback, control properties are
Load
loaded with information recovered from view state and control state.
Postback event if the request is a postback, the related event handler is called. After that,
handling the Validate method of all validator controls is called.
Before rendering, view state is saved for the page and all controls. During
the rendering stage, the page calls the Render method for each control,
Rendering
providing a text writer that writes its output to the OutputStream object
of the page's Response property.
Unload The rendered page is sent to the client and page properties, such as
Response and Request are unloaded and all cleanup done.
The ASP.NET Page life Cycle Events
Inside the life cycle of an ASP.Page there is a collection of events and some
of these events can be controlled through user code events
PreInit
• It is the first event in page life cycle.
• Triggered after the start stage is complete and before the initialization stage
begins.
• This event can be used to checks the IsPostBack property to determine
whether the page is requested for the first time or is it a subsequent request ,
creates or re-creates dynamic controls, sets a master page dynamically and
so on and so forth.
• This event can be handled by the Page_PreInit handler.
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("<b><font size=24>PreInit event Triggered<br>");
}
The ASP.NET Page life Cycle Events
Init
• Triggered after all controls have been initialized and any skin settings have
been applied for those controls.
• In this phase of the page life cycle, all the server controls of the web page
are initialized to their default values.
• Init event can be used to initialize control properties.
• The in Init event of individual controls occurs before the Init event of the
page.
• This event can be handled by Page_Init handler.
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("Init event triggered <br>");
}
The ASP.NET Page life Cycle Events
InitComplete
• Is raised after all of the initialization is taken place (controls as well as
page).
• All the controls turn on tracking view-state changes.
• This event can be handled by Page_InitComplete handler.
PreLoad
• Raised after the page loads view state for itself and all controls, and after it
processes postback data that is included with the Request instance.
• It is the event where programmer can perform any processing on the page or
a control before its load event.
• This event can be handled by Page_PreLoad handler.
protected void Page_PreLoad (object sender, EventArgs e)
{
Response.Write("PreLoad event triggered <br>");
}
The ASP.NET Page life Cycle Events
Page_Load
• Load is raised for page first and recursively for all child controls.
• In the event handler associated with this event you can write code that needs
to be executed for each postback of the web page.
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Load event Triggered<br>");
}
The ASP.NET Page life Cycle Events
LoadComplete
• In LoadComplete event we can do any task which are required for all of the
other controls on the page to be loaded and validated.
• At this state controls have been created in the memory and ready for
rendering.
• This event can be handled by Page_LoadComplete handler.

protected void Page_LoadComplete(object sender, EventArgs e)


{
Response.Write("LoadComplete event Triggered<br>");
}
The ASP.NET Page life Cycle Events
PreRender
• Raised after the Page object has created all controls that are required in order
to render the page.
• It occurs for each control on the page.
• It is raised for the Page first and recursively for all child controls.
• This event can be used to make final changes to the contents of the page or
its controls before rendering the page.
• This event can be handled by Page_PreRender handler.
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("PreRender event Triggered<br>");
}
The ASP.NET Page life Cycle Events
PreRenderComplete
• Raised after each data bound control whose DataSourceID property is set calls
its DataBind method.
SaveStateComplete
• Before the SaveStateComplete event get fired the view state for the entire page
and for all of the controls of the page has been saved.
• This event can be handled by Page_ SaveStateComplete handler.
protected void Page_ SaveStateComplete(object sender, EventArgs e)
{
Response.Write("SaveStateComplete event Triggered<br></b></font>");
}
The ASP.NET Page life Cycle Events
Render
• This is not an event; instead, at this stage of processing, the Page object calls
this method on each control.
• All ASP.NET Web server controls have a Render method that writes out the
control's markup to send to the browser.
Unload
• This event is the last event in the ASP.NET page life cycle.
• Since this is the last event and is raised after rendering of the page, it has no
relevance besides releasing resources and discarding the web page from
memory.
• This event is raised recursively for all child controls and then finally for the
page itself.
• This event can be handled by Page_UnLoad handler.
protected void Page_ UnLoad(object sender, EventArgs e)
{

You might also like