0% found this document useful (0 votes)
24 views

AWP Unit 2

The document discusses ASP.NET file types and folders, the three-tier architecture of ASP.NET applications, the ASP.NET page lifecycle, differences between inline and code-behind code, differences between HTML and web server controls, properties and uses of the Page class, and the purpose and uses of global.asax and web.config files in ASP.NET applications.

Uploaded by

Mahesh Kudalkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

AWP Unit 2

The document discusses ASP.NET file types and folders, the three-tier architecture of ASP.NET applications, the ASP.NET page lifecycle, differences between inline and code-behind code, differences between HTML and web server controls, properties and uses of the Page class, and the purpose and uses of global.asax and web.config files in ASP.NET applications.

Uploaded by

Mahesh Kudalkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit-II

Topics:
Web Form Fundamentals |Form Controls

41
Q1. List and explain different files and folder in ASP.NET web application.
ASP.NET File Types: - ASP.NET applications can include many types of files. Below table
show list of files.
File Name Description
.aspx These are ASP.NET web pages. They contain the user interface
and, optionally, the underlying application code. Users request or
navigate directly to one of these pages to start our web application
.ascx These are ASP.NET user controls. User controls are similar to web
pages, except that the user can’t access these files directly. Instead,
they must be hosted inside an ASP.NET web page. User controls
allow you to develop a small piece of user interface and reuse it in as
many web forms as you want without repetitive code.
web.config This is the configuration file for your ASP.NET application. It includes
settings for customizing security, state management, memory
management, and much more.
global.asax This is the global application file. You can use this file to define
global variables (variables that can be accessed from any web page
in the web application) and react to global events (such as when a
web application first starts).
.cs These are code-behind files that contain C# code. They allow you to
separate the application logic from the user interface of a web page.
ASP.NET Web Folders.
Every web application starts with a single location, called the root folder. However, in a large,
well-planned web application.
Directory Description
App_Code Contains source code files that are dynamically compiled for use in
our application
App_GlobalResources Stores global resources that are accessible to every page in the
web application. This directory is used in localization scenarios,
when we need to have a website in more than one language.
App_Data Stores data, including SQL Server Express database files
App_Themes Stores the themes that are used to standardize and reuse
formatting in our web application.

Q2. Explain the three layer architecture of ASP.NET.


Asp.net architecture consists of 3 layers as follows:
Presentation Layer
The presentation layer consists of the Asp.net page that manages the appearance of application. This
layer can include bound data controls and ObjectDataSource objects that bind data controls to the
data.
Middle Layer
The middle layer contains the data access classes that manage the data access for the application.
This layer can also contain business objects that represent business entities such as customers,
products or employee and that implement business rules such as credit and discount policies.
Database Layer
This layer consists of the database that contains the data for the application. Ideally the SQL
statement that do the database access should be saved in stored procedure within the database, nut
the SQL statement are often stored in the data access classes.

42
Q3. Explain ASP.NET Life Cycle Page.
ASP.NET life cycle specifies, how:
 ASP.NET processes pages to produce dynamic output
 The application and its pages are instantiated and processed
 ASP.NET compiles the pages dynamically
When a page is requested, it is loaded into the server memory, processed and sent to the browser.
Then it is unloaded from the memory. At each of this steps, methods and events are available, which
could be overridden according to the need of the application.

Following are the different stages of an ASP.Net page:


Page request
When ASP.Net gets a page request, it decides whether to parse and compile the page or there would
be a cached version of the page; accordingly the response is sent
Starting of page life cycle:
At this stage, the Request and Response objects are set. If the request is an old request or post back,
the IsPostBack property of the page is set to true.
Page initialization
At this stage, the controls on the page are assigned unique ID by setting the UniqueID property and
themes are applied.

43
Page load
At this stage, control properties are set using the view state and control state values.
Validation
Validate method of the validation control is called and if it runs successfully, the IsValid property of
the page is set to true.
Postback event handling
If the request is a postback (old request), the related event handler is called.
Page rendering
At this stage, view state for the page and all controls are saved.
Unload
The rendered page is sent to the client and page properties, such as Response and Request are
unloaded and all cleanup done.
Following are the page life cycle events:
PreInit()
Init()
InitComplete()
LoadViewState()
LoadPostData()
PreLoad()
Load()
LoadComplete()
PreRender()
PreRenderComplete()
SaveStateComplete()
UnLoad()

Q4. Differentiate between inline code and code behind

44
Q.5Difference between HTML control and Web Server control.
HTML control Web Server control
HTML control runs at client side. ASP.Net controls run at server side.
We can run HTML controls at server side by Wecannot run ASP.Net Controls on client
adding attribute runat=”server”. side as these controls have this
attribute runat=”server” by default.
HTML controls are client side controls, so it ASP.Net Controls are Server side controls,
does not provide STATE management. provides STATE management.
HTML control does not require rendering. HTML control does not require rendering.
As HTML controls runs on client side, As ASP.Net controls run on server side,
execution is fast. execution is slow.
HTML controls does not support Object With ASP.Net controls, you have full support
Oriented paradigm. of Object oriented paradigm.
HTML control have limited set of properties ASP.Net controls have rich set of properties
and/or methods. and/or methods.
<input type="text" ID="txtName"> <asp:TextBoxId="txtName"runat="server">
</asp:TextBox>

Q.6 Short note on Page class.


When an ASP.NET page is requested and renders markup to a browser, ASP.NET creates an
instance of a class that represents our page. That class is composed not only of the code that we
wrote for the page, but also code that is generated by ASP.NET.
Page Properties
Property Description
IsPostBack This Boolean property indicates whether this is the first time the page is
being run (false) or whether the page is being resubmitted in response to
a controlevent, typically with stored view state information (true).
EnableViewState When set to false, this overrides the EnableViewState property of the
contained controls, thereby ensuring that no controls will maintain state
information.
Application This collection holds information that’s shared between all users in our
website. For example, we can use the Application collection to count the
number of times a page has been visited.
Session This collection holds information for a single user, so it can be used in
different pages. For example, we can use the Session collection to store
the items in the current user’s shopping basket on an e-commerce
website.
Request This refers to an HttpRequest object that contains information about the
current web request. We can use the HttpRequest object to get
information about the user’s browser.
Response This refers to an HttpResponse object that represents the response
ASP.NET will send to the user’s browser

Q7. Explain the use of global.asx and web.config files in ASP.NET application.
OR
Explain the files used to configure an ASP.NET Application.
 The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code
for responding to application-level events raised by ASP.NET or by HttpModules.
 The Global.asax file resides in the root directory of an ASP.NET-based application. The Global.asax file
is parsed and dynamically compiled by ASP.NET.

45
 The Global.asax file itself is configured so that any direct URL request for it is automatically rejected;
external users cannot download or view the code written within it.
 The Global.asax file does not need recompilation if no changes have been made to it. There can be
only one Global.asax file per application and it should be located in the application's root directory
only.
The Global.asax contains two types of events those are
o Events which are fired for every request
o Events which are not fired for every request
Events which are fired for every request:-
Application_BeginRequest() – This event raised at the start of every request for the web application.
Application_EndRequest() – This event raised at the end of each request right before the objects
released.
Application_PreRequestHandlerExecute() – T his event called before the appropriate HTTP handler
executes the request.
Application_PostRequestHandlerExecute() – This event called just after the request is handled by
its appropriate HTTP handler.
Events which are not fired for every request:-
Application_Start() – This event raised when the application starts up and application domain is
created.
Session_Start() – This event raised for each time a new session begins, This is a good place to put
code that is session-specific.
Application_Error() – This event raised whenever an unhandled exception occurs in the application.
This provides an opportunity to implement generic application-wide error handling.
Session_End() – This event called when session of user ends.
Application_End() – This event raised just before when web application ends.
Application_Disposed() – This event fired after the web application is destroyed and this event is
used to reclaim the memory it occupies.
Web.Config
 Configuration file is used to manage various settings that define a website. The settings are stored in
XML files that are separate from our application code. In this way we can configure settings
independently from our code.
 Generally a website contains a single Web.config file stored inside the application root directory.
However there can be many configuration files that manage settings at various levels within an
application.
 There are number of important settings that can be stored in the configuration file. Some of the most
frequently used configurations, stored conveniently inside Web.config file are:
- Database connections
- Caching settings
- Session States
- Error Handling
- Security
Benefits of XML-based Configuration files
 ASP.NET Configuration system is extensible and application specific information can be stored and
retrieved easily. It is human readable.
 We need not restart the web server when the settings are changed in configuration file. ASP.NET
automatically detects the changes and applies them to the running ASP.NET application.
Configuration file looks like this

46
1. <configuration>
2. <connectionStrings>
3. <add name="myCon" connectionString="server=MyServer;database=puran;uid=p
uranmehra;pwd=mydata1223" />
4. </connectionStrings>
5. </configuration/>

Q8. Explain TextBox control in ASP.NET with any five properties.


This is an input control which is used to take user input. To create TextBox either we can write
code or use the drag and drop facility of visual studio IDE.
This is server side control, asp provides own tag to create it. The example is given below.
< asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox>
This control has its own properties that are tabled below.
Property Description
Text It is used to set text to be shown for the control.
MaxLength It is used to set maximum number of characters that can be entered.
Readonly It is used to make control readonly.
TextMode It used to determine behavior of control. Possible value are Single / Multiline
/ Password
CausesValidation true/false – It is used to enable or disable validation effect on control

Example:
Assign a text to TextBox control when Button click event fires using c#

C# code for above TextBox ExampleC#


protected void btndisplay_Click(object sender, EventArgs e)
{
TextBox1.Text = "Asp.net";
}
protected void btnclear_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
}
Q9. What is the difference between buttons, Link Buttons and Image Buttons? Explain any three
common button attributes.
These controls differ only in how they appear to the user. A button displays text within a
rectangular area. A Link button displays text that look like a hyperlink and an image button displays
an image.
LinkButton control is a control just like a Button control along with the flexibility to make it look
like a Hyperlink. It implements an anchor <a/> tag that uses only ASP.NET postback mechanism
to post the data on the server. Despite being a hyperlink, we can't specify the target URL.
ImageButton control is used to post the form or fire an event either client side or server side. It’s
like a asp:Button control, the only difference is, we have the ability to place our own image as a

47
button. ImageButton control is generally used to post the form or fire an event either client side or
server side.

Button control is used to post the form or fire an event either client side or server side. Button
control is generally used to post the form or fire an event either client side or server side. When it
is rendered on the page, it is generally implemented through <input type=submit> HTML tag.

Q10. Explain CheckBox and RadioButton web server controls in ASP.NET.


CheckBox:
CheckBox control is an asp.net web server control. CheckBox control visually as square on web
forms. The Checkbox control allow user to check square or uncheck square.
In CheckBox control check and uncheck checkbox specify by the checked property of check box
true or false.
Basic syntax for check box:
<asp:CheckBox ID= "chkoption" runat= "Server"></asp:CheckBox>

CheckBox properties:
 AutoPostBack:Specifies whether the form should be posted immediately after the Checked
property has changed or not. Default is false
 CausesValidation:Specifies if a page is validated when a Button control is clicked
 Checked:Specifies whether the check box is checked or not
 Id:A unique id for the control
 Text: The text next to the check box
Event:
OnCheckedChanged
The name of the function to be executed when the checked property has changed

RadioButton
Radiobutton isasp.net web server control. Radiobutton is used to allow user to select a single
radiobutton from group of radiobutton. In asp.net generally we use more than one radiobutton
and select only one radiobutton at a time from all the radiobutton control. On other hand
in checkbox control we can check and uncheck multiple check box at a time.

48
Basic syntax for radio button:
<asp:RadioButton ID= "rdboption" runat= "Server"></asp: RadioButton>

RadioButton properties:
 AutoPostBack:A Boolean value that specifies whether the form should be posted immediately
after the Checked property has changed or not. Default is false
 Checked : A Boolean value that specifies whether the radio button is checked or not id a unique
id for the control
 GroupName : The name of the group to which this radio button belongs
 Text : The text next to the radio button

Q11. Explain Listbox with properties and methods.


ListBox control is an asp.net web server control. ListBox control used to store the multiple items
and allow user to select multiple item from ListBox control. ListBox control is same
as dropdownlist control.
The dropdownlist control allow user to select maximum only one item at a time, on other hand
ListBox control allow user to select multiple items same time. So we can also say ListBox is multi-
row selection box control.
In a ListBox control there is a SelectionMode property to change the mode of section from single
to multiple. By default ListBox control selection mode is single if we want to select multiple items
from ListBox, then just change the SelectionMode property to multiple.
<asp:ListBox ID="dropStatic" runat="server">
<asp:ListItem Text="Red" Value="red"></asp:ListItem>
<asp:ListItem Text="Blue" Value="blue"></asp:ListItem>
<asp:ListItem Text="Green" Value="green"></asp:ListItem>
</asp:ListBox>
Some properties are

Following are the important methods and events:


GetSelectedIndices
 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

49
SelectedIndexChanged event occurs when the selection from the list control changes between posts
to the server.
OnSelectedIndexChanged
 OnSelectedIndexChanged method raises the SelectedIndexChanged event.
 This allows you to provide a custom handler for the event.

Q12. What is the difference between List Box and Drop-Down Lists? List and explain any three common
properties of these controls.
 List boxes are used in cases where there are small numbers of items to be selected. In contrast,
drop-down lists are typically used with larger list so that they don’t take up much space on the
page.
 A list box lets a user select one or more items from the list of items. A drop-down list lets a user
choose an item from the drop-down list of items.
Following are common properties of ListBox and DropDownList:
Properties Description
Items Gets the collection of items from the dropdown box.
SelectedValue Get the value of the Selected item from the dropdown box.
SelectedIndex Gets or Sets the index of the selected item in the dropdown box.
SelectedItem Gets the selected item from the list.

Q13. Explain any five Methods/Property of List Item collection objects.


Following is list of Methods/Property of List Item collection objects:

Q14. Explain Sorted, SelectedMode, MultiColumn, SelectedItem and SelectedIndex properties of


ListBox control.
Sorted
The Sorted property set to true, the ListBox items are sorted. The following code snippet sorts the
ListBox items.
listBox1.Sorted = true;

50
Selected Mode:
SelectionMode property defines how items are selected in a ListBox. The SelectionMode value can be
one of the following four SelectionMode enumeration values. None - No item can be selected. One -
Only one item can be selected. MultiSimple - Multiple items can be selected. MultiExtended -
Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make
selections.
listBox1.SelectionMode = SelectionMode.MultiSimple;
listBox1.SetSelected(1, true);
listBox1.SetSelected(2, true);
MultiColumn:
A multicolumn ListBox places items into as many columns as are needed to make vertical scrolling
unnecessary. The user can use the keyboard to navigate to columns that are not currently visible. Set
the HorizontalScrollbar property to true to display a horizontal scroll bar that enables the user to
scroll to columns that are not currently shown in the visible region of the ListBox. The value of the
ColumnWidth property determines the width of each column.
listBox1.MultiColumn = true;
SelectedItem
Gets or sets the currently selected item in the ListBox. We can get text associated with currently
selected item by using Items property.
string selectedItem = listBox1.Items[listBox1.SelectedIndex].ToString();
SelectedIndex
Gets or sets the zero-based index of the currently selected item in a ListBox.
listBox1.SelectedIndex = 1;
Q15. Explain Table control with example in ASP.NET
Table control is used to structure a web pages. In other words to divide a page into several rows and
columns to arrange the information or images. When it is rendered on the page, it is implemented
through <table> HTML tag.
We can simply use HTML <table> control instead of using <asp:Table> control. However many of one
benefits of using <asp:Table> control is we can dynamically add rows or columns at the runtime or
change the appearance of the table.
Following are some important properties that are very useful.
BackImageUrl
Used to set background image of the table
Caption
Used to write the caption of the table.
Example:
ASP.NET code for a table control
<asp:Table ID="Table1" runat="server" Height="123px" Width="567px">
<asp:TableRow runat="server">
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server">
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
</asp:TableRow>

51
<asp:TableRow runat="server">
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell>
</asp:TableRow>
</asp:Table>

Q16. Explain Multiview and View control with example in ASP.NET


MultiView Control is an asp.net web server control. Multiview Control is a same as Tab control. If we
want make a complex designing on one web forms then you have to use multiview control.
MltiView control is a container of several view control. In a multiview control there are many view
control for designing separation of view for user.
The View control is a container of several web server controls. Using the multiview control we can
feel the multiple page view design on a single web page.
We can also say multiview control allow user to create different view on single web page. There are
many view control in a multiview control, each view control has some web server control for design
web page. We can see single view at a time on web page by specify the ActiveViewIndex property of
multiview control.
All view control assign automatically index to all it, the index always start from zero. The first view1
index is zero, second is one and so on, If we want to display first view on web page, then we need to
write MultiView1.ActiveViewIndex=0.
 Prefix for MultiView control is mv
 Prefix for View control is v
The MultiView control has the following important properties:

Q17. Explain Adrotator control with example in ASP.NET


The AdRotator is one of the rich web server control of asp.net. AdRotator control is used to display a
sequence of advertisement images as per given priority of image.
Adrotator control display the sequence of images, which is specified in the external XML file. In xml
file we indicate the images to display with some other attributes, like image
impressions, NavigateUrl, ImageUrl, AlternateText.

52
In Adrotator control images will be changed each time while refreshing the web page.
AdRotator Control Example in ASP.Net

The basic syntax of adding an AdRotator is as follows:


<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" />
The advertisement file is an XML file, which contains the information about the advertisements to be
displayed.
There are the following standard XML elements that are commonly used in the advertisement file:

The following code illustrates an advertisement file ads.xml:


<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>
<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>
</Advertisements>

53
Create a new web page and place an AdRotator control on it.
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile ="~/ads.xml"
onadcreated="AdRotator1_AdCreated" />
</div>
</form>

Q18. Explain Calendar control with example in ASP.NET


ASP.NET provides a Calendar control that is used to display a calendar on the Web page.
This control displays a one-month calendar that allows the user to select dates and move to the next
and previous months.

By default, this control displays the name of the current month, day headings for the days of the
weeks, days of the month and arrow characters for navigation to the previous or next month. The
class hierarchy for this control is as follows

Object->Control->WebControl->Calendar

The Calendar is complex, powerful Web server control that you can use to add calendar feature to
our web page. We can use calendar control display any date between 0 A.D. and 9999A.D.The
Calendar control is represented as:

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

The Calendar control when rendered to a user browser, it generates an HTML <table> element and a
set of associated JavaScript. The Calendar control can be used to select a single date or multiple
dates. The SelectionMode property is used for this. The SelectionMode properties are as:

54
Q19. Explain any five common properties of web server controls.
Following are common properties of web server controls:

Q20. What is use of autopostback and runat properties?


 AutoPostback or Postback is nothing but submitting page to server. AutoPostback is webpage going
to server, Server processes the values and sends back to same page or redirects to different page.
 HTML elements in ASP.NET files are, by default, treated as text. To make these elements
programmable, add a runat="server" attribute to the HTML element. This attribute indicates that
the element should be treated as a server control.
 The runat="server" attribute indicates that the form should be processed on the server. It also
indicates that the enclosed controls can be accessed by server scripts.
 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. If this property is set to TRUE the automatic post back is
enabled, otherwise FALSE. Default is FALSE.
Example
<asp:TextBox id= " t1" AutoPostBack="true" runat="server" />
Web server controls are created on the server and they require a runat="server" attribute to work.
This attribute indicates that the control should be treated as a server control.
Q21. Explain UrlEncode() and UrlDecode() methods in ASP.NET.
We cannot send special characters through query string. All special characters should be encoded
when you pass them through the query string. The encoded string must be decoded at the receiver.
There are two methods to achieve this: UrlEncode and UrlDecode():
The main purpose of these two methods is to encode and decode the URLrespectively. We need to
encode the URL because some of the characters are not safe sending those across browser.
Some characters are being misunderstood by the browser and that leads to data mismatch on the
receiving end. Characters such as a question mark (?), ampersand (&), slash mark (/), and spaces
might be truncated or corrupted by some browsers.

55
UrlEncode()
This method is used to encode a string to be passed through URL to another web page. URLencode
replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.
Syntax:
UrlEncode (string str )
UrlDecode()
This method is used to decode the encoded URL string. Decodes any %## encoding in the given
string.
Syntax:
UrlDecode (string str )

Q22.What is user control? How to create and use user control in ASP.NET Page.
A UserControl is a separate, reusable part of a page. We can put a piece of a page in a UserControl,
and then reuse it from a different location. A notable difference is that User Controls can be included
on multiple pages, while a page can't.
UserControls are used much like regular server controls, and they can be added to a page
declaratively, just like server controls can.
A big advantage of the UserControl is that it can be cached, using the OutputCache functionality
described in a previous chapter, so instead of caching an entire page, we may cache only the
UserControl, so that the rest of the page is still re-loaded on each request.
Creation of UserControl:
Following steps are used to create UserControl.
1. Open Visual Studio.
2. "File" -> "New" -> "Project..." then select ASP.NET Webform Application.
3. Add a new web form.
To create a new UserControl, in Solution Expolrer, Add New Item, provide your File Name and click
Add
Design UserControl as per our requirement. Next step to use UserControl in .aspx page. Add the
following line below the standard page declaration:

<%@RegisterTagPrefix="My"TagName="UserInfoBoxControl"Src="~/UserInfoBoxCont
rol.ascx" %>

Make sure that the src value matches the path to your UserControl file. Now you may use the
UserControl in your page, like any other control. For instance, like this:

<My:UserInfoBoxControlrunat="server"ID="MyUserInfoBoxControl"/>

Q23.Why we use validation controls? List various types of controls used in asp.net
Validation is important part of any web application. User's input must always be validated before
sending across different layers of the application.
Validation controls are used to:
 Implement presentation logic.
 To validate user input data.
 Data format, data type and data range is used for validation.
 Validation Controls in ASP.NET

56
An important aspect of creating ASP.NET Web pages for user input is to be able to check that the
information users enter is valid. ASP.NET provides a set of validation controls that provide an easy-to-
use but powerful way to check for errors and, if necessary, display messages to the user.
There are six types of validation controls in ASP.NET
 RequiredFieldValidation Control
 CompareValidator Control
 RangeValidator Control
 RegularExpressionValidator Control
 CustomValidator Control
 ValidationSummar
The below table describes the controls and their work:
Validation Control Description
RequiredFieldValidation Makes an input control a required field
CompareValidator Compares the value of one input control to the value of another
input control or to a fixed value
RangeValidator Checks that the user enters a value that falls between two values
RegularExpressionValidator Ensures that the value of an input control matches a specified
pattern
CustomValidator Allows you to write a method to handle the validation of the value
entered
ValidationSummary Displays a report of all validation errors occurred in a Web page

Q24.Explain following validation controls.


RequiredFieldValidator Control
The RequiredFieldValidator control is simple validation control, which checks to see if the data is
entered for the input control. We can have a RequiredFieldValidator control for each form element
on which you wish to enforce Mandatory Field rule.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate" runat="server" ControlToValidate="txtName"
ErrorMessage="Please enter name !!"></asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator Server Control is another validator control, which checks to see if a control value
is within a valid range. The attributes that are necessary to this control are: MaximumValue,
MinimumValue, and Type.
It has three specific properties:

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"

57
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a pattern of a
regular expression. The regular expression is set in the ValidationExpression property.
The syntax of the control is as given:
<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">
</asp:RegularExpressionValidator

Q25. What is the use of Compare Validator? Explain it along with its properties.
CompareValidator Control
 The CompareValidator control allows you to make comparison to compare data entered in an input
control with a constant value or a value in a different control.
 It can most commonly be used when you need to confirm password entered by the user at the
registration time. The data is always case sensitive.
 It has the following specific properties:

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">
</asp:CompareValidator>
Example:
Small number:<br />
<asp:TextBox runat="server" id="txtSmallNumber" /><br /><br />
Big number:<br />
<asp:TextBox runat="server" id="txtBigNumber" /><br />
<asp:CompareValidator runat="server" id="cmpNumbers" controltovalidate="txtSmallNumber"
controltocompare="txtBigNumber" operator="LessThan" type="Integer" errormessage="The first
number should be smaller than the second number!" /><br />

Q26. Explain the CustomValidator control with code


The CustomValidator control allows writing application specific custom validation routines for both
the client side and the server-side validation.

58
The client-side validation is accomplished through the ClientValidationFunction property. The client-
side validation routine should be written in a scripting language, such as JavaScript or VBScript, which
the browser can understand.
The server-side validation routine must be called from the control's ServerValidate event handler.
The server-side validation routine should be written in any .Net language, like C# or VB.Net.
Below table shows the properties of CustomValidator.

Example:
In this below example we will simply check the length of the string in the TextBox.
Custom Text:<br />
<asp:TextBox runat="server" id="txtCustom" />
<asp:CustomValidator runat="server" id="cusCustom" controltovalidate="txtCustom"
onservervalidate="cusCustom_ServerValidate" errormessage="The text must be exactly 8 characters
long!" />
<br /><br />

protected void cusCustom_ServerValidate(object sender, ServerValidateEventArgs e)


{
if(e.Value.Length == 8)
e.IsValid = true;
else
e.IsValid = false;
}
Q27. Explain Menu control in ASP.NET
The Menu control is used to create a menu of hierarchical data that can be used to navigate through
the pages. The Menu control conceptually contains two types of items. First is StaticMenu that is
always displayed on the page, second is DynamicMenu that appears when opens the parent item.

Following steps are used to create Menu Control:


Toolbox > Navigation > Menu or add the following few lines of code snippet.

<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">


<Items>
<asp:MenuItem Text="HOME" NavigateUrl="~/Default.aspx" Selected="true" />
<asp:MenuItem Text="HTML" NavigateUrl="~/HTML.aspx">
<asp:MenuItem Text="HtmlTagList" NavigateUrl="~/HtmlTagList.aspx" />
</asp:MenuItem>

59
<asp:MenuItem Text="CSS" NavigateUrl="~/CSS.aspx">
<asp:MenuItem Text="CssSelectors" NavigateUrl="~/CssSelectors.aspx" />
</asp:MenuItem>
</Items>
</asp:Menu>
Below are the various Properties of Menu Control

Q28. When to use TreeView control in ASP.NET


 ASP.NET TreeView Web control is used to display hierarchical data (such as a table of contents) in a
tree structure in a Web page.
 The TreeView control is made up of TreeNode objects. The TreeView control can be bound to data.
It supports the following features:
 Automatic data binding, this allows the nodes of the control to be bound to hierarchical data, such
as an XML document.
 Site navigation support through integration with the SiteMapDataSource control.
 Node text that can be displayed as either selectable text or hyperlinks.
 Customizable appearance through themes, user-defined images, and styles.
 Programmatic access to the TreeView object model, which allows you to dynamically create trees,
populates nodes, set properties, and so on.
 Node population through client-side callbacks to the server (on supported browsers).
 The ability to display a check box next to each node.

<asp:TreeView ExpandDepth="1" runat="server">


<Nodes>
<asp:TreeNode Text="Employees">
<asp:TreeNode Text="Bradley" Value="ID-1234" />
<asp:TreeNode Text="Whitney" Value="ID-5678" />
<asp:TreeNode Text="Barbara" Value="ID-9101" />
</asp:TreeNode>

60
</Nodes>
</asp:TreeView>

 Each node in the Tree is represented by a name/value pair (not necessarily unique), defined by the
Text and Value properties of TreeNode, respectively. The text of a node is rendered, whereas the
value of a node is not rendered and is typically used as additional data for handling postback events.
 This example also uses the ExpandDepth property of TreeView to automatically expand the tree 1
level deep when it is first rendered.
 The TreeView control is made up of one or more nodes. Each entry in the tree is called a node and is
represented by a TreeNode

Q29. Explain SiteMapPath control in ASP.NET


 The SiteMapPath control basically is used to access web pages of the website from one webpage to
another. It is a navigation control and displays the map of the site related to its web pages.
 This map includes the pages in the particular website and displays the name of those pages. We can
click on that particular page in the Site Map to navigate to that page. We can say that the
SiteMapPath control displays links for connecting to URLs of other pages.
 The SiteMapPath control uses a property called SiteMapProvider for accessing data from databases
and it stores the information in a data source.
The representation of the SiteMapPath control is as follows:
Root Node->Child Node

Following steps are used to create Menu Control:


Toolbox > Navigation >SiteMapPath
Following are some important properties that are very useful.

ParentLevelsDisplayed : It specifies the number of levels of parent nodes and then displays the
control accordingly related to the currently displayed node.
RenderCurrentNodeAsLink : It specifies whether or not the site navigation node that represents the
currently displayed page is rendered as a hyperlink.
PathSeperator : It specifies the string that displays the SiteMapPath nodes in the rendered navigation
path.
Style properties of the SiteMapPath class
CurrentNodeStyle : It specifies the style used for the display text for the current node.
RootNodeStyle : It specifies the style for the root node style text.
NodeStyle : It specifies the style used for the display text for all nodes in the site navigation path.
Sitemap file has been included in our project and we can see it in the Solution Explorer. And now we
have to set the URL and title attributes in the sitemap file.
<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="Default.aspx" title="myhomepage" description="">
<siteMapNode url="myweb1.aspx" title="myfirstpage" description="" />
<siteMapNode url="myweb2.aspx" title="mysecondpage" description="" />
</siteMapNode>
</siteMap>

61

You might also like