ASP_.net_-_unit_2
ASP_.net_-_unit_2
Right-click the project in Solution Explorer > Add > Web Form.
Example Code:
<!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>
In ASP.NET, events happen on the client side (user's browser) and are
handled on the server.
<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.
Drag a Button control from the toolbox onto the web form.
Click the yellow lightning bolt icon to switch to the Events tab.
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.
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 are basic form elements like <input> , <button> , and
<textarea> .
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).
They offer more functionality, like automatic data validation and binding.
Comparison Table:
Feature HTML Controls Web Server Controls
Object-Oriented
Limited Full support (OOP concepts)
Support
Example:
HTML Control:
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.
2. List Box:
5. Bulleted List:
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
1. Table Control:
It can hold other controls like text boxes, buttons, etc., inside table cells.
2. TableRow Control:
3. TableCell Control:
Key Properties:
Property Description
CellPadding Sets the space between the cell content and cell borders.
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.
2. Default Events:
3. AUTOPOSTBACK Event:
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
1. RequiredFieldValidator:
2. CompareValidator:
3. RangeValidator:
Ensures that a value falls within a specific range (e.g., age must be
between 18 and 100).
4. RegularExpressionValidator:
Example: Validates that the email field contains a properly formatted email
address.
5. ValidationSummary:
Example: Collects and shows all error messages at the top or bottom of
the form.
Example of RequiredFieldValidator:
Example of RangeValidator:
1. FileUpload Control:
2. Calendar Control:
3. AdRotator Control:
Example: Used on websites to display different ads each time the page is
refreshed.
Used to organize content into multiple views, where only one view is
visible at a time.
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
<script runat="server">
protected void Calendar1_SelectionChanged(object sender,
EventArgs e)
{
Response.Write("Selected Date: " + Calendar1.Selected
Date.ToShortDateString());
}
</script>
<script runat="server">
protected void NextView(object sender, EventArgs e)
{
These rich controls simplify common tasks like file uploads, date selections, and
content management.
1. SiteMapPath Control:
Example: "Home > Products > Electronics > Mobile Phones" shows how a
user navigated to the current page.
2. TreeView Control:
3. Menu Control:
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.
2. Use Case:
Example of CausesValidation:
Code Explanation:
Submit Button (CausesValidation = True):
If the field is empty, it will display the error message "Name is required."
When the Clear button is clicked, it will not trigger any validation, allowing
the form to be cleared without validation checks.
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.
Code Explanation:
Group 1 (User Information):
Code-Behind Example:
In this setup, each button validates only the fields in its respective group, ensuring
that different sections of the form are validated independently.
2. Types of Tracing:
Add the Trace="true" attribute in the page directive at the top of your .aspx
file.
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.
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:
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.
<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.
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);
}
Key Concepts:
Concept Description
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.