AWP Unit 2
AWP Unit 2
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.
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.
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()
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>
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/>
Example:
Assign a text to TextBox control when Button click event fires using c#
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.
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
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.
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>
52
In Adrotator control images will be changed each time while refreshing the web page.
AdRotator Control Example in ASP.Net
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>
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:
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:
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
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:
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 />
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
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
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