🌐
ASP .NET - UNIT 2
1. How to Create and Run the First ASP.NET Application
1. Open Visual Studio
Launch Visual Studio.
2. Create a New Project
Go to File > New > Project .
Choose Web > ASP.NET Web Application.
Name your project (e.g., "DemoApplication") and choose a location.
3. Choose Web Application Type
Select Empty and check Web Forms.
Click OK to create the project.
4. Add a Web Form
Right-click the project in Solution Explorer > Add > Web Form.
Name the form (e.g., "Demo.aspx").
5. Write Code to Display "Hello World"
In Demo.aspx, add this code:
<%= "Hello World" %>
6. Run the Application
Press F5 or click the Run button.
Example Code:
ASP .NET - UNIT 2 1
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Dem
o.aspx.cs" Inherits="DemoApplication.Demo" %>
<!DOCTYPE html>
<html xmlns="<http://www.w3.org/1999/xhtml>">
<head runat="server">
<title>Hello World App</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%= "Hello World" %>
</div>
</form>
</body>
</html>
2. Event & Event Handler
1. What is an Event?
An event is an action like clicking a button, pressing a key, or moving the
mouse.
In ASP.NET, events happen on the client side (user's browser) and are
handled on the server.
2. What is an Event Handler?
An event handler is a method that defines what happens when an event
occurs.
For example, if a user clicks a button, the server checks if there is a
handler for that button's click event. If yes, it runs the code in the handler.
3. Common Events in ASP.NET:
Click: Happens when a button is clicked.
TextChanged: Happens when text in a textbox changes.
ASP .NET - UNIT 2 2
SelectedIndexChanged: Happens when a new item is selected from a list.
Example Code for Event Handling:
<asp:Button ID="Button1" runat="server" Text="Click Me" OnCli
ck="Button1_Click" />
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Button Clicked!");
}
</script>
In this example, when the button is clicked, it triggers the Button1_Click method on
the server, which writes "Button Clicked!" to the page.
3. Adding Event Handlers
1. Create a Web Application
First, create a new ASP.NET project as described earlier.
2. Design a Web Form with a Button
Add a button to your web form:
Go to Design View in Visual Studio.
Drag a Button control from the toolbox onto the web form.
3. Open Properties Window
Right-click on the button and choose Properties.
Click the yellow lightning bolt icon to switch to the Events tab.
4. Double-Click the Event
Find the event you want to handle (e.g., Click).
Double-click the event name to generate an event handler in the code-
behind file.
ASP .NET - UNIT 2 3
Example Code for Adding an Event Handler:
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick
="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("You clicked the button!");
}
In this case, the Button1_Click event handler is triggered when the button is
clicked, and the message "You clicked the button!" is displayed.
4. ASP.NET Controls
1. What are ASP.NET Controls?
ASP.NET controls are tools used to build the web interface, like text boxes,
buttons, labels, etc.
These controls allow users to enter data, make selections, and interact
with the application.
2. Types of Controls:
HTML Controls: Simple HTML elements like <input> , <button> , etc. These
are rendered as-is in the browser and can be converted to server-side
controls by adding runat="server" .
Server Controls: Advanced controls that run on the server, allowing for
more functionality like validation, security, and state management.
Example of HTML Control:
<input id="UserName" type="text" runat="server" />
ASP .NET - UNIT 2 4
Here, an ordinary HTML text field becomes a server control by adding
runat="server" , allowing you to handle it on the server.
Example of Server Control:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
In this example, a TextBox is created as a server control, meaning its value can be
accessed and processed on the server side.
Comparison Table:
HTML Controls Server Controls
Run on the client side Run on the server
No state management Provides state management
Limited functionality Rich functionality (validation, security, etc.)
Faster execution (client-side) Slower execution (server-side)
Requires JavaScript for interactions Can interact directly with server
5. Difference between HTML Control and Web Server Control
1. HTML Controls:
HTML controls are basic form elements like <input> , <button> , and
<textarea> .
They run on the client side (in the browser).
By default, they cannot interact with the server unless explicitly converted
to server controls using runat="server" .
They do not support state management (they don’t remember data after a
postback).
2. Web Server Controls:
Web server controls are advanced ASP.NET elements like <asp:TextBox> ,
<asp:Button> , etc.
ASP .NET - UNIT 2 5
They run on the server side, which means they interact directly with
server-side code.
Server controls automatically manage their state (data is preserved during
postbacks).
They offer more functionality, like automatic data validation and binding.
Comparison Table:
Feature HTML Controls Web Server Controls
Runs on Client-side (browser) Server-side
State Management No Yes
Object-Oriented
Limited Full support (OOP concepts)
Support
Renders directly as Renders as HTML after server-side
Rendering
HTML processing
Execution Speed Fast (client-side) Slower (server-side)
Example:
HTML Control:
<input type="text" id="txtName" />
Web Server Control:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
In the first example, txtName is just a simple HTML input field. In the second
example, it's a server control that interacts with server-side code and remembers
its state across postbacks.
6. List Control
ASP.NET provides several controls to display a list of items that users can interact
with.
ASP .NET - UNIT 2 6
1. Drop-Down List:
Displays a list of items in a dropdown format.
Users can select one item at a time.
2. List Box:
Displays a list of items in a box.
Can allow single or multiple item selections, depending on the settings.
3. Radio Button List:
Displays multiple options as radio buttons.
Only one option can be selected at a time.
4. Check Box List:
Displays multiple options as checkboxes.
Users can select multiple options.
5. Bulleted List:
Displays a simple bulleted or numbered list of items.
Can be styled as plain text or hyperlinks.
Example of Drop-Down List:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Option 1</asp:ListItem>
<asp:ListItem Value="2">Option 2</asp:ListItem>
<asp:ListItem Value="3">Option 3</asp:ListItem>
</asp:DropDownList>
Example of List Box:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Mult
iple">
<asp:ListItem>Item 1</asp:ListItem>
ASP .NET - UNIT 2 7
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
</asp:ListBox>
Example of Radio Button List:
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>Option A</asp:ListItem>
<asp:ListItem>Option B</asp:ListItem>
<asp:ListItem>Option C</asp:ListItem>
</asp:RadioButtonList>
Example of Check Box List:
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>Choice 1</asp:ListItem>
<asp:ListItem>Choice 2</asp:ListItem>
<asp:ListItem>Choice 3</asp:ListItem>
</asp:CheckBoxList>
Example of Bulleted List:
<asp:BulletedList ID="BulletedList1" runat="server" BulletSty
le="Numbered">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
</asp:BulletedList>
7. Table Controls
ASP.NET provides Table Controls to display data in rows and columns. These
controls allow you to organize information in a structured format, similar to an
ASP .NET - UNIT 2 8
HTML table.
1. Table Control:
Used to create a table in ASP.NET with rows and columns.
It can hold other controls like text boxes, buttons, etc., inside table cells.
2. TableRow Control:
Represents a single row in a table.
Can contain multiple TableCell controls.
3. TableCell Control:
Represents a single cell in a table row.
Can contain text or other controls (e.g., buttons, labels).
Example Code for Table Control:
<asp:Table ID="Table1" runat="server" GridLines="Both">
<asp:TableRow>
<asp:TableCell>Row 1, Cell 1</asp:TableCell>
<asp:TableCell>Row 1, Cell 2</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell>Row 2, Cell 1</asp:TableCell>
<asp:TableCell>Row 2, Cell 2</asp:TableCell>
</asp:TableRow>
</asp:Table>
Key Properties:
Property Description
GridLines Determines if lines between rows/columns are visible.
CellPadding Sets the space between the cell content and cell borders.
CellSpacing Sets the space between cells.
ASP .NET - UNIT 2 9
HorizontalAlign Aligns the content horizontally in cells.
This allows you to display data in a tabular format where each row and cell can
contain different types of content, like text or even other controls.
8. Web Control Events
ASP.NET Web Controls can trigger events that allow the server to respond to user
actions like clicks, selections, or text changes.
1. Page and Control Events:
Page Events: These are related to the lifecycle of a web page.
Page_Load: Happens when the page is loaded.
Page_Init: Happens when the page is initialized.
Page_Unload: Happens when the page is unloaded from memory.
Control Events: These are triggered by actions on specific controls.
Button.Click: Triggered when a button is clicked.
TextBox.TextChanged: Triggered when the text in a textbox is
changed.
DropDownList.SelectedIndexChanged: Triggered when a new item is
selected in a dropdown.
2. Default Events:
Each control has a default event that is triggered automatically. For
example, the default event for a button is the Click event.
3. AUTOPOSTBACK Event:
Some controls, like TextBox or DropDownList, can automatically post data
to the server without needing a button click.
This is controlled by the AutoPostBack property. If set to true , the page
will post back as soon as the control value changes.
Example of Button Click Event:
ASP .NET - UNIT 2 10
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick
="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Button clicked!");
}
Example of TextBox with AutoPostBack:
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
OnTextChanged="TextBox1_TextChanged" />
protected void TextBox1_TextChanged(object sender, EventArgs
e)
{
Response.Write("Text changed!");
}
Common Control Events Table:
Control Event Description
Button OnClick Triggered when button is clicked
TextBox OnTextChanged Triggered when text is changed
DropDownList OnSelectedIndexChanged Triggered when an item is selected
Triggered when checkbox is
CheckBox OnCheckedChanged
checked/unchecked
9. Validation
ASP.NET provides several validation controls to ensure that user inputs are
correct before being processed by the server. These validation controls help in
ASP .NET - UNIT 2 11
checking if the data entered is valid, ensuring a good user experience and
preventing errors.
1. RequiredFieldValidator:
Ensures that a specific field is not left empty.
Example: Used to make sure a user enters a value in a textbox.
2. CompareValidator:
Compares the value of one input field to another or to a constant value.
Example: Used for password confirmation (comparing two password
fields).
3. RangeValidator:
Ensures that a value falls within a specific range (e.g., age must be
between 18 and 100).
Example: Validates that a number or date is within a given range.
4. RegularExpressionValidator:
Ensures that a value matches a specific pattern, like email addresses,
phone numbers, or postal codes.
Example: Validates that the email field contains a properly formatted email
address.
5. ValidationSummary:
Displays all validation errors in a summary section.
Example: Collects and shows all error messages at the top or bottom of
the form.
Example of RequiredFieldValidator:
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server" Contr
olToValidate="txtName" ErrorMessage="Name is required." />
ASP .NET - UNIT 2 12
Example of CompareValidator (Password Confirmation):
<asp:TextBox ID="txtPassword" runat="server" TextMode="Passwo
rd"></asp:TextBox>
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode
="Password"></asp:TextBox>
<asp:CompareValidator ID="cvPassword" runat="server" ControlT
oValidate="txtConfirmPassword" ControlToCompare="txtPassword"
ErrorMessage="Passwords do not match." />
Example of RangeValidator:
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RangeValidator ID="rvAge" runat="server" ControlToValida
te="txtAge" MinimumValue="18" MaximumValue="100" Type="Intege
r" ErrorMessage="Age must be between 18 and 100." />
Example of RegularExpressionValidator (Email Validation):
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail" ValidationExpression="\\w+@\\w+
\\.\\w+" ErrorMessage="Invalid email address." />
Key Validation Concepts:
Validator Purpose
RequiredFieldValidator Ensures field is not empty
CompareValidator Compares two fields or a field and a constant
RangeValidator Ensures value is within a specific range
RegularExpressionValidator Validates input against a regular expression pattern
ValidationSummary Displays all validation errors in one place
ASP .NET - UNIT 2 13
10. Rich Controls
ASP.NET offers Rich Controls that provide enhanced functionality and
interactivity. These controls make complex tasks like file uploads, date selection,
and advertisements easier to manage.
1. FileUpload Control:
Allows users to upload files from their computer to the server.
Example: Used for uploading profile pictures, documents, etc.
2. Calendar Control:
Displays a calendar for users to select dates.
Example: Used for date selection, such as booking appointments or
selecting a birthday.
3. AdRotator Control:
Displays rotating banner advertisements from an external XML file.
Example: Used on websites to display different ads each time the page is
refreshed.
4. MultiView and View Controls:
Used to organize content into multiple views, where only one view is
visible at a time.
Example: Helpful for creating multi-step forms (e.g., registration forms
with multiple sections).
Example of FileUpload Control:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick
="Button1_Click" />
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
ASP .NET - UNIT 2 14
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" +
FileUpload1.FileName));
Response.Write("File Uploaded: " + FileUpload1.Fi
leName);
}
else
{
Response.Write("Please select a file.");
}
}
</script>
Example of Calendar Control:
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChange
d="Calendar1_SelectionChanged" />
<script runat="server">
protected void Calendar1_SelectionChanged(object sender,
EventArgs e)
{
Response.Write("Selected Date: " + Calendar1.Selected
Date.ToShortDateString());
}
</script>
Example of AdRotator Control:
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFi
le="~/ads.xml" />
ads.xml (Advertisement File):
ASP .NET - UNIT 2 15
<Advertisements>
<Ad>
<ImageUrl>~/Images/ad1.jpg</ImageUrl>
<NavigateUrl><http://www.example.com></NavigateUrl>
<AlternateText>Ad 1</AlternateText>
<Impressions>100</Impressions>
</Ad>
<Ad>
<ImageUrl>~/Images/ad2.jpg</ImageUrl>
<NavigateUrl><http://www.example.com></NavigateUrl>
<AlternateText>Ad 2</AlternateText>
<Impressions>200</Impressions>
</Ad>
</Advertisements>
Example of MultiView and View Controls:
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex
="0">
<asp:View ID="View1" runat="server">
<h2>Step 1</h2>
<asp:Button ID="ButtonNext" runat="server" Text="Nex
t" OnClick="NextView" />
</asp:View>
<asp:View ID="View2" runat="server">
<h2>Step 2</h2>
<asp:Button ID="ButtonPrevious" runat="server" Text
="Previous" OnClick="PreviousView" />
</asp:View>
</asp:MultiView>
<script runat="server">
protected void NextView(object sender, EventArgs e)
{
ASP .NET - UNIT 2 16
MultiView1.ActiveViewIndex = 1;
}
protected void PreviousView(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
}
</script>
These rich controls simplify common tasks like file uploads, date selections, and
content management.
11. Navigation Controls
ASP.NET provides Navigation Controls to help users move around a website
easily. These controls manage and display the structure of the website, offering
different ways to navigate through pages.
1. SiteMapPath Control:
Displays the navigation path (also known as breadcrumb) to show users
where they are on the website.
Example: "Home > Products > Electronics > Mobile Phones" shows how a
user navigated to the current page.
2. TreeView Control:
Displays data in a tree-like structure, with expandable and collapsible
nodes.
Example: Used to display categories and subcategories, such as a file
explorer or a product category list.
3. Menu Control:
Displays a hierarchical menu of options with submenus that users can
click to navigate to different pages.
Example: A horizontal navigation bar with dropdown menus for sections
like "Home," "Products," and "Contact Us."
ASP .NET - UNIT 2 17
Example of SiteMapPath Control:
<asp:SiteMapPath ID="SiteMapPath1" runat="server" />
This control automatically generates a breadcrumb navigation based on the site
map file.
Example of TreeView Control:
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>
<asp:TreeNode Text="Home" NavigateUrl="~/Default.asp
x"></asp:TreeNode>
<asp:TreeNode Text="Products" NavigateUrl="~/Product
s.aspx">
<asp:TreeNode Text="Electronics" NavigateUrl="~/E
lectronics.aspx"></asp:TreeNode>
<asp:TreeNode Text="Furniture" NavigateUrl="~/Fur
niture.aspx"></asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
Example of Menu Control:
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
<Items>
<asp:MenuItem Text="Home" NavigateUrl="~/Default.asp
x"></asp:MenuItem>
<asp:MenuItem Text="Products">
<asp:MenuItem Text="Electronics" NavigateUrl="~/E
lectronics.aspx"></asp:MenuItem>
<asp:MenuItem Text="Furniture" NavigateUrl="~/Fur
niture.aspx"></asp:MenuItem>
ASP .NET - UNIT 2 18
</asp:MenuItem>
<asp:MenuItem Text="Contact Us" NavigateUrl="~/Contac
t.aspx"></asp:MenuItem>
</Items>
</asp:Menu>
Key Navigation Controls:
Control Description
SiteMapPath Shows the breadcrumb trail of the current page's location.
TreeView Displays a collapsible tree structure for hierarchical data.
Menu Provides a clickable menu with submenus for website navigation.
These navigation controls make it easy to guide users through the site's structure
and enhance the user experience by allowing easy access to different sections.
12. CausesValidation Property of Button
1. What is CausesValidation?
This property determines whether validation controls should be triggered
when a button (or any control) is clicked.
If CausesValidation is set to true (default), the button click will trigger
validation for input fields.
If CausesValidation is set to false , the button will not trigger validation.
2. Use Case:
Submit Button: Set CausesValidation to true so that all validation checks
are performed when the form is submitted.
Reset or Cancel Button: Set CausesValidation to false because you don’t
want to validate input when the form is being cleared.
Example of CausesValidation:
ASP .NET - UNIT 2 19
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvName" runat="server" Contr
olToValidate="txtName" ErrorMessage="Name is required." />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Cause
sValidation="True" OnClick="SubmitForm" />
<asp:Button ID="btnClear" runat="server" Text="Clear" CausesV
alidation="False" OnClick="ClearForm" />
Code Explanation:
Submit Button (CausesValidation = True):
When the Submit button is clicked, the RequiredFieldValidator checks if the
txtName field has a value.
If the field is empty, it will display the error message "Name is required."
Clear Button (CausesValidation = False):
When the Clear button is clicked, it will not trigger any validation, allowing
the form to be cleared without validation checks.
Code-Behind Example for Button Clicks:
protected void SubmitForm(object sender, EventArgs e)
{
// Code for form submission, triggered after validation
Response.Write("Form Submitted!");
}
protected void ClearForm(object sender, EventArgs e)
{
// Code for clearing form fields
txtName.Text = "";
}
ASP .NET - UNIT 2 20
In this setup, the Submit button performs validation, while the Clear button does
not trigger any validation.
13. Grouping Controls for Validation
1. What is ValidationGroup?
The ValidationGroup property is used to group controls together so that
specific buttons only trigger validation for certain fields.
Useful when a page has multiple forms or sections, and you want to
validate each section separately.
2. How it Works:
Assign the same ValidationGroup name to the controls you want to group.
The button with the same ValidationGroup will trigger validation for only
those controls.
Example of Grouping Controls for Validation:
<!-- Group 1: User Information -->
<asp:TextBox ID="txtFirstName" runat="server" ValidationGroup
="Group1"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvFirstName" runat="server"
ControlToValidate="txtFirstName" ValidationGroup="Group1" Err
orMessage="First Name is required." />
<asp:TextBox ID="txtLastName" runat="server" ValidationGroup
="Group1"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvLastName" runat="server" C
ontrolToValidate="txtLastName" ValidationGroup="Group1" Error
Message="Last Name is required." />
<asp:Button ID="btnSubmitGroup1" runat="server" Text="Submit
User Info" ValidationGroup="Group1" OnClick="SubmitGroup1" />
<!-- Group 2: Account Information -->
ASP .NET - UNIT 2 21
<asp:TextBox ID="txtEmail" runat="server" ValidationGroup="Gr
oup2"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" Cont
rolToValidate="txtEmail" ValidationGroup="Group2" ErrorMessag
e="Email is required." />
<asp:TextBox ID="txtPassword" runat="server" ValidationGroup
="Group2" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server" C
ontrolToValidate="txtPassword" ValidationGroup="Group2" Error
Message="Password is required." />
<asp:Button ID="btnSubmitGroup2" runat="server" Text="Submit
Account Info" ValidationGroup="Group2" OnClick="SubmitGroup2"
/>
Code Explanation:
Group 1 (User Information):
Fields: txtFirstName and txtLastName .
Button: btnSubmitGroup1 triggers validation for Group1 only.
Group 2 (Account Information):
Fields: txtEmail and txtPassword .
Button: btnSubmitGroup2 triggers validation for Group2 only.
Code-Behind Example:
protected void SubmitGroup1(object sender, EventArgs e)
{
// Code for processing Group 1 (User Info)
Response.Write("User Info Submitted!");
}
ASP .NET - UNIT 2 22
protected void SubmitGroup2(object sender, EventArgs e)
{
// Code for processing Group 2 (Account Info)
Response.Write("Account Info Submitted!");
}
In this setup, each button validates only the fields in its respective group, ensuring
that different sections of the form are validated independently.
14. Tracing in ASP.NET
1. What is Tracing?
Tracing helps you view diagnostic information about the execution of a
page or an application.
It shows the sequence of events, variables, and execution details, which
can help you debug issues.
2. Types of Tracing:
Page Level Tracing: Enabled for specific pages only.
Application Level Tracing: Enabled for the entire application.
Page Level Tracing:
1. How to Enable Page Level Tracing:
Add the Trace="true" attribute in the page directive at the top of your .aspx
file.
<%@ Page Language="C#" Trace="true" %>
2. Output:
When you run the page, a detailed trace of events, like request data,
session variables, and control lifecycle, will appear at the bottom of the
page.
ASP .NET - UNIT 2 23
Application Level Tracing:
1. How to Enable Application Level Tracing:
In the Web.config file, add or modify the <trace> element to enable tracing
for the entire application.
<configuration>
<system.web>
<trace enabled="true" pageOutput="false" requestLimit
="10" localOnly="false" />
</system.web>
</configuration>
2. Settings in Web.config:
enabled="true" : Turns on tracing for the entire application.
pageOutput="false" : Hides trace information on individual pages but logs it
for analysis.
requestLimit="10" : Limits the number of trace requests stored.
localOnly="false" : Allows tracing to be visible from remote clients (if set to
true , only visible on local machine).
Viewing Trace Information:
1. Trace.axd:
If tracing is enabled, you can view trace logs for the entire application by
visiting /Trace.axd in your browser (e.g., http://localhost:1234/Trace.axd ).
This page shows detailed trace information for multiple requests, including
control events, data bindings, and request/response details.
Example of Enabling Page Level Tracing:
<%@ Page Language="C#" Trace="true" %>
ASP .NET - UNIT 2 24
<html xmlns="<http://www.w3.org/1999/xhtml>">
<head>
<title>Tracing Example</title>
</head>
<body>
<h1>Tracing is Enabled</h1>
</body>
</html>
Example of Web.config for Application Level Tracing:
<configuration>
<system.web>
<trace enabled="true" pageOutput="false" requestLimit="1
0" localOnly="false" />
</system.web>
</configuration>
In this setup, tracing provides you with detailed insight into the internal workings
of your ASP.NET page or application, which is very helpful for debugging and
optimizing performance.
15. Exception Handling in ASP.NET
1. What is Exception Handling?
Exception handling is a process used to manage errors that occur during
the execution of a program.
In ASP.NET, it allows developers to gracefully handle errors and provide
feedback to users.
2. Why Use Exception Handling?
To prevent the application from crashing due to unexpected errors.
To log errors for troubleshooting and debugging.
ASP .NET - UNIT 2 25
To provide user-friendly error messages instead of displaying technical
details.
3. Common Exception Handling Techniques:
Try-Catch Block: The most basic method to catch exceptions.
Global Exception Handling: Using Application_Error in the Global.asax file
to handle unhandled exceptions globally.
Example of Try-Catch Block:
try
{
// Code that may throw an exception
int result = 10 / int.Parse(txtNumber.Text);
Response.Write("Result: " + result);
}
catch (FormatException ex)
{
Response.Write("Please enter a valid number.");
}
catch (DivideByZeroException ex)
{
Response.Write("Cannot divide by zero.");
}
catch (Exception ex)
{
Response.Write("An unexpected error occurred: " + ex.Mess
age);
}
Example of Global Exception Handling:
In the Global.asax file:
ASP .NET - UNIT 2 26
void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
// Log the exception (e.g., to a file or database)
// Redirect to a custom error page
Response.Redirect("~/ErrorPage.aspx");
}
Key Concepts:
Concept Description
Try Block Contains code that may throw exceptions.
Catch Block Defines how to handle specific exceptions.
Optional; executes code after try-catch, regardless of an
Finally Block
error.
Global Exception
Captures unhandled exceptions application-wide.
Handling
Summary:
Using exception handling in ASP.NET helps maintain application stability and
improve user experience by providing meaningful error messages and logging
error details for further investigation.
ASP .NET - UNIT 2 27