ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Unit -1
Overview of the ASP.NET, Framework & Coding Standards
1. What is Asp.Net?
o ASP.NET is an open source web framework, created by Microsoft, for building
modern web apps and services with .NET.
o ASP.NET is cross platform and runs on Windows, Linux, macOS, and Docker.
o It was first released in January 2002. It is built on the Common Language
Runtime (CLR) and allows programmers to write code using any supported
.NET language.
2. .NET Framework Architecture
● CLI:
o CLI Stands for Common Language Infrastructure.
o The language-independent nature of the CLI makes it easier to transition your
app across different platforms.
o It also streamlines the process of migrating an app from one platform to
another because it has a standard code structure, a single standard library, and
21BCACC602 - Programming with ASP.NET Page 1 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
as a result, a single standard application deployment process across all
platforms.
o The CLI is an app development framework that is language-independent.
Therefore, developers don’t have to worry about changing the language or
syntax of their source code when switching from one platform to another.
● CLR:
o CLR Stands for Common Language Runtime.
o CLR is the basic and Virtual Machine component of the .NET Framework. It is
the run-time environment in the .NET Framework that runs the codes and
helps in making the development process.
o It is responsible for managing the execution of .NET programs regardless of
any .NET programming language.
o It also helps in the management of code, as code that targets the runtime is
known as Managed Code, and code that doesn’t target the runtime is known
as Unmanaged code.
● ADO .NET
o ADO.NET (ActiveX Data Objects for .NET) is a set of data access services
provided by Microsoft as part of the .NET Framework.
o ADO.NET enables developers to interact with and manage data stored in
relational databases, XML, and other types of data sources.
o ADO.NET provides a set of classes and components for performing tasks such
as connecting to databases, retrieving and manipulating data, and managing
data integrity.
● .NET Remoting
o .NET Remoting is a technology in the .NET Framework that enables
communication between objects in different application domains, processes,
or across different machines.
o It provides a way for distributed components to interact with each other in a
seamless manner.
o .NET Remoting was introduced in earlier versions of the .NET Framework, but
it has been largely superseded by Windows Communication Foundation (WCF)
in more recent versions.
● ASP.NET Web Forms & Web Services
o ASP.NET Web Forms is a web application framework within the ASP.NET stack.
o It allows developers to build dynamic, data-driven web applications using a
model that is similar to traditional Windows Forms programming.
o Web Forms abstracts the complexities of HTML, CSS, and client-side scripting,
providing a high-level, event-driven programming model.
21BCACC602 - Programming with ASP.NET Page 2 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o Web Services provide a standardized way for applications to communicate
with each other over the web. They enable interoperability between different
platforms and technologies.
● Windows Forms, Console Application:
o Windows Forms (WinForms) is a graphical user interface (GUI) framework for
building desktop applications on the Microsoft Windows platform.
o It provides a set of controls, events, and visual designers for creating rich
Windows-based applications with a traditional, event-driven programming
model.
o A console application is a text-based program that runs in a console window
(Command Prompt or Terminal).
o It typically interacts with the user through text input and output. Console
applications are lightweight and are commonly used for tasks that don't
require a graphical user interface.
● FCL:
o FCL Stands for Framework Class Library.
o It is the collection of reusable, object-oriented class libraries and methods, etc
that can be integrated with CLR.
o Also called the Assemblies. It is just like the header files in C/C++ and packages
in java.
o Installing the .NET framework basically is the installation of CLR and FCL into
the system.
● CTS:
o The Common Type System defines a common set of data types that can be
used across all .NET languages.
o It ensures that data types in one language can be seamlessly used in another,
promoting language interoperability.
● CLS
o Common Language Specification helps in easy creation of the apps and
software.
o It is the standardized set of rules and guidelines that are followed to develop
software in one language.
o It helps in reducing the complexity of the apps and software. Common
Language Specification also helps in reduction of cost.
o It helps in reducing the development time and cost.
● Different Languages
o Different Languages used in Asp.Net The ASP.NET application codes can be
written in any of the following languages:
21BCACC602 - Programming with ASP.NET Page 3 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o C#, Visual Basic.Net ,Jscript, J# ASP.NET is used to produce interactive, data-
driven web applications over the internet.
o It consists of a large number of controls such as text boxes, buttons, and labels
for assembling, configuring, and manipulating code to create HTML pages.
o Some CLR Feachers
3. Visual Studio IDE.
• Start Page: The goal of this start page was to provide a location, available when the
product first started, for the user to either find out about Visual Studio or to easily
get back to what they were working on.
• Toolbox: The Toolbox window displays controls that you can add to Visual Studio
projects. You can drag and drop different controls onto the surface of the designer
you are using, and resize and position the controls.
• Server Explorer: Server Explorer allows you to graphically create databases, tables,
views, and stored procedures completely from within Visual Studio . NET. You can
also edit and delete existing database objects.
• Properties: The Properties window is used to view and change the design-time
properties and events of selected objects that are located in editors and designers.
You can also use the Properties window to edit and view file, project, and solution
properties.
• Solution Explorer: The Solution Explorer is used to create, explore & manage your
solutions and projects and to view & interact with your code.
• Output: The Output window displays status messages for various features in the
21BCACC602 - Programming with ASP.NET Page 4 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
integrated development environment (IDE).
• Error List: The Error List window lets you perform the following tasks: Display the
errors, warnings, and messages produced while you write code.
• File > New > Project > Visual C# + Web + .Net Framework 4 + ASP.NET Web
Application + Ok
• File > New > Project > Visual C# + Web + .Net Framework 4 + ASP.NET Empty Web
Application + Ok
• File > New > Website > Visual C# + .Net Framework 4 + ASP.NET Web Site + Ok
• File > New > Website > Visual C# + .Net Framework 4 + ASP.NET Empty Web Site + Ok
4. Overview Web Server (IIS)
• Internet Information Services, also known as IIS, is a Microsoft web server that runs
on Windows operating system and is used to exchange static and dynamic web
content with internet users.
• IIS can be used to host, deploy, and manage web applications using technologies
such as ASP.NET and PHP.
• Before we discuss the applications of IIS, what is an IIS server exactly?
• IIS uses various protocols for communication and data exchange with remote clients
or computers, such as HTTP, SMTP, and FTP.
• As a core Windows product, IIS comes integrated with Windows Server and runs on
Windows OS.
• You can use third-party utilities to run IIS over Linux and macOS, but it often offers
less stability and poor performance.
5. Asp.net Life Cycle
• The ASP.NET life cycle could be divided into two groups:
o Application Life Cycle
o Page Life Cycle
Application Life Cycle
• The application life cycle contains the following steps:
1. Application Start
• The webserver executes the application start when a user requests an application for
access. In this method, it sets all global variables to default.
2. Object Creation
• Object creation holds all the HTTP Context, HTTP Request, and HTTP Response by the
21BCACC602 - Programming with ASP.NET Page 5 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
webserver. It also contains information about the request, cookies, and browsing
information.
3. HTTP Application
• HTTP Application is an object created by the webserver. It helps to process all the
subsequent information that is sent to the user.
4. Dispose
• Dispose is an event that is called before the application is destroyed. It also helps to
release manually unmanaged resources when the objects are no longer needed.
5. Application End
• Application End is the last stage of the application life cycle. It helps to unload the
memory.
Page Life Cycle
• The Page Life Cycle has certain phases that help in writing custom controls and
initializing an application.
• Following are the different phases of the Page Life Cycle:
1. Page Request
• Page Request is the first step of the page life cycle. When a user request is made, the
server checks the request and compiles the pages. Once the compilation is done, the
21BCACC602 - Programming with ASP.NET Page 6 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
request is sent back to the user.
2. Page Start
• Page Start helps in creating two objects: request and response. The request holds all
the information which the user sent, while the response contains all the information
that is sent back to the user.
3. Page Initialization
• Page Initialization helps to set all the controls on the pages. It has a separate ID, and
it applies themes to the pages in this step.
4. Page Load
• Page Load helps to load all the control properties of an application. It also helps to
provide information using view state and control state.
5. Validation
• Validation happens when the execution of an application is successful. It returns two
conditions: true and false. If execution is successful, it returns true, otherwise false.
6. Event Handling
• Event Handling takes place when the same pages are loaded. It is a response for the
validation. When the same page is loaded, a Postback event is called, which checks
the page’s credentials.
7. Rendering
• Rendering happens before it sends all the information back to the user. And all this
information is stored before being sent back.
8. Unload
• Unload is a process that helps in deleting all unwanted information from the
memory once the output is sent to the user
6. Types of Files in ASP.NET.
• In an ASP.NET web application, various types of files play different roles in the
development, deployment, and execution of the application. Here are some
common types of files you may encounter in an ASP.NET project:
A. ASPX Files:
• ASPX (Active Server Pages Extended) files are the main files in ASP.NET web
applications. They contain the markup and server-side code that define the structure
and behavior of web pages. ASPX files are processed by the server, and the resulting
HTML is sent to the client's browser.
B. Code-Behind Files (.aspx.cs or .aspx.vb):
• Code-behind files contain the server-side code associated with ASPX files. They are
separate files, often with a .cs (C#) or .vb (VB.NET) extension, and are used to
separate the presentation logic (in the ASPX file) from the code (in the code-behind
file).
C. Master Pages (.master):
21BCACC602 - Programming with ASP.NET Page 7 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Master pages provide a template for consistent layout and design across multiple
pages in a web application. They define the common structure, such as headers,
footers, and navigation, and can be referenced by content pages.
D. Web Configuration File (web.config):
• The web.config file is a configuration file that contains settings for the ASP.NET
application. It includes information about authentication, authorization, custom
error pages, and other application-specific settings.
E. Global Application File (Global.asax):
• The Global.asax file contains code for handling application-level events in the
ASP.NET application lifecycle. It allows developers to respond to application-level
events such as application start, end, and session start.
F. User Controls (.ascx):
• User controls are reusable components that encapsulate a specific piece of
functionality or UI. They are similar to ASPX pages but can be included in multiple
pages to promote code reuse.
G. Class Files (.cs or .vb):
• In addition to code-behind files, you may have standalone class files that contain
reusable classes and business logic used across multiple parts of your application.
H. Style Sheets (.css):
• Cascading Style Sheets (CSS) files are used to define the visual styles and layout of
your web pages. They help separate the presentation layer from the content.
I. JavaScript Files (.js):
• JavaScript files contain client-side script code that adds interactivity and behavior to
your web pages. They are used to enhance the user experience by providing features
that run in the browser.
7. Advantages & Disadvantage of ASP.NET
❖ Rich Class Library (FCL):
• ASP.NET benefits from the extensive .NET Framework Class Library (FCL), providing a
broad set of pre-built, reusable components that streamline development.
❖ Language Interoperability:
• ASP.NET supports multiple programming languages, including C#, VB.NET, and F#.
This language interoperability allows developers to choose the language that best
fits their skills and project requirements.
❖ Rapid Development with Visual Studio:
• Visual Studio, the integrated development environment (IDE) for ASP.NET, offers
powerful tools, debugging capabilities, and design features that contribute to rapid
and efficient application development.
❖ Server-Side Technologies:
• ASP.NET offers server-side technologies like Web Forms and MVC, simplifying the
21BCACC602 - Programming with ASP.NET Page 8 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
development of dynamic and data-driven web applications.
❖ State Management:
• ASP.NET provides various options for state management, including ViewState,
Session, and Application state, making it easier to maintain data between client
requests.
❖ Security Features:
• ASP.NET includes robust security features, such as authentication and authorization
mechanisms, encryption, and prevention of common web vulnerabilities.
❖ Scalability:
• ASP.NET applications can scale horizontally by distributing the load across multiple
servers. Additionally, features like caching and output caching contribute to
improved performance.
❖ Integration with Other Microsoft Technologies:
• ASP.NET seamlessly integrates with other Microsoft technologies, such as SQL
Server, Azure, and SharePoint, facilitating the development of comprehensive
solutions.
❖ Support for Web Services:
• ASP.NET supports the creation of web services using technologies like ASMX, WCF,
and Web API, enabling the development of service-oriented architectures.
• Disadvantages of ASP.NET:
❖ Platform Dependency:
• ASP.NET applications are primarily designed to run on Windows servers. This
platform dependency can be a limitation for developers who prefer cross-platform
development or need to deploy on non-Windows servers.
❖ Learning Curve:
• The learning curve for ASP.NET can be steep for beginners, especially when dealing
with advanced concepts and features. The complexity may be higher compared to
simpler frameworks.
❖ View State Overhead:
• Web Forms applications often use ViewState to maintain the state of controls
between postbacks. While this is convenient, it can result in increased page size and
affect performance.
❖ Proprietary Technology:
• ASP.NET is a Microsoft technology, and while it is widely used, it may not be the
preferred choice for organizations that prefer open-source solutions or cross-
platform development.
❖ Performance:
• While ASP.NET is generally performant, certain scenarios, such as heavy server-side
21BCACC602 - Programming with ASP.NET Page 9 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
processing or complex page life cycles, may impact performance compared to
lightweight frameworks.
❖ Costs:
• Licensing costs for Windows Server and other Microsoft technologies may be a
consideration, particularly for smaller businesses or projects with budget constraints.
8. What is Master page? Requirement of Master Page.
• A Master Page is a feature in ASP.NET that allows developers to create a consistent
layout and design for multiple pages in a web application.
• It provides a template that defines the common structure, layout, and UI elements,
such as headers, footers, and navigation, which can be shared across multiple
content pages.
• The main purpose of Master Pages is to promote a consistent look and feel
throughout an entire website.
• Key Components of Master Pages:
1) Content Placeholder:
• A Master Page typically contains one or more content placeholders. These are
regions where content pages can insert their unique content. For example, you
might have placeholders for the main content, header, footer, or side navigation.
2) Master Page File (.master):
• The Master Page is defined in a separate file with a .master extension. This file
contains the HTML and controls that make up the common layout and structure.
3) Content Pages:
• Content pages are individual pages that reference and inherit from the Master Page.
They include only the unique content specific to that page. Content pages can use
the placeholders defined in the Master Page to insert their content.
21BCACC602 - Programming with ASP.NET Page 10 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Requirement of Master Page.
• There are several benefits or Requirements of using a Master Page in ASP.NET:
• Consistent layout: A Master Page allows for a consistent layout across all pages in a
website, which helps to improve the user experience.
• Code reuse: By defining a common layout in a Master Page, developers can reduce
the amount of code that needs to be written and maintained, resulting in less time
and effort required to create and update a website.
• Easy maintenance: By centralizing the layout on a Master Page, it is much easier to
make updates or changes to the overall look and feel of a website.
• Improved organization: Master Pages can help to organize the codebase of a
website, making it easier for developers to understand the structure and layout of
the site.
• Enhance security: By using Master Pages, the common elements like the header,
footer, and menus are separate and can be easily secured without affecting the
other pages.
• Better SEO: With a consistent layout and navigational links, Master Pages can help
improve the SEO of the website.
• Better performance: By using Master Pages, the common elements are cached on
the browser which improves the performance of the website.
• How to create MasterPage in ASP.NET
• Follow the below steps to create MasterPage in ASP.NET:
• STEP 1: Open Visual Studio and create a new web project.
• STEP 2: Right-click on the project in Solution Explorer and select "Add" > "New Item".
• STEP 3: In the Add New Item dialog box, select "Master Page" from the list of
templates.
21BCACC602 - Programming with ASP.NET Page 11 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• STEP 4: Give the master page a name and click "Add".
• STEP 5: The master page will be added to your project and opened in the designer.
You can add any elements you want to appear on every page of your website to the
master page, such as a header, footer, or navigation menu.
• STEP 6: Once you have finished designing the master page, you can create a new
web page that uses it.
• STEP 7: Right-click on your project in Solution Explorer and select "Add" > "New
Item".
• STEP 8: In the Add New Item dialog box, select "Web Form" from the list of
templates.
• STEP 9: Give the web page a name and click "Add".
• STEP 10: In the newly created web page, you can now select the master page from
the list of available master pages.
• STEP 11: You can now define content placeholders on the master page to define
where the content from the child pages will appear.
• STEP 12: You can now add content to the child pages and it will be rendered within
the master page.
9. Content Page
• A content page is the page which uses a master page.
• The content page contains one or more Content controls which map to the
ContentPlaceHolder controls in the master page.
• If a content control which maps to the ContentPlaceHolder in the master page is not
available in the content page, then the content inside the ContentPlaceHolder of the
master page is rendered in the content page. The Content controls can contain
HTML Controls, Web Server Controls, or Standard controls similar to that of ASP.NET
web pages.
• Below is an example of a Content control.
• <asp:Content
ID="Content1"
ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
</asp:Content>
10.Page Directive Attributes.
• This directive is used to define the attributes for the page parser and compiler
specific to the page file.
• There cannot be more than one Page directive for each page file whereas each Page
21BCACC602 - Programming with ASP.NET Page 12 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
directive can have multiple attributes.
• The basic syntax of Page directive is:
• <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" Trace="true" %>
• The Page directive has many possible attributes out of which the most common
attributes are given in the list below:
Attributes Description
AutoEventWireup The Boolean value that enables or disables page events that are being
automatically bound to methods; for example, Page_Load.
Buffer The Boolean value that enables or disables HTTP response buffering.
ClassName The class name for the page.
ClientTarget The browser for which the server controls should render content.
CodeFile The name of the code behind file.
Debug The Boolean value that enables or disables compilation with debug
symbols.
Description The text description of the page, ignored by the parser.
EnableSessionState It enables, disables, or makes session state read-only.
EnableViewState The Boolean value that enables or disables view state across page
requests.
ErrorPage URL for redirection if an unhandled page exception occurs.
Inherits The name of the code behind or other class.
Language The programming language for code.
Src The file name of the code behind class.
Trace It enables or disables tracing.
TraceMode It indicates how trace messages are displayed, and sorted by time or
category.
Transaction It indicates if transactions are supported.
ValidateRequest The Boolean value that indicates whether all input data is validated
against a hardcoded list of values.
21BCACC602 - Programming with ASP.NET Page 13 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Unit -2
ASP.NET Standard Controls, Rich Controls &
Navigation Controls
1. Standard Controls
o Label
• This control is used to display textual information on the web forms.
• It is mainly used to create caption for the other controls like: textbox.
• To create label either we can write code or use the drag and drop facility.
• This is server side control, asp provides own tag to create label.
• The example is given below.
• < asp:LabelID="Label1" runat="server" Text="Label" ></asp:Label>
• This control has its own properties that are tabled below.
Property Description
Text It is used to set text to be shown for the label.
Height It is used to set height of the control.
Width It is used to set width of the control.
o Text Box
• 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>
• Server renders it as the HTML control and produces the following code to the
browser.
• <input name="TextBox1" id="TextBox1" type="text">
• 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.
Height It is used to set height of the control.
Width It is used to set width of the control.
MaxLength It is used to set maximum number of characters that can be entered.
Readonly It is used to make control readonly.
Columns It is used to set the number of Columns.
Rows It is used to set the number of rows.
21BCACC602 - Programming with ASP.NET Page 14 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
2. Web Controls for Buttons
o Buttons
• This control is used to perform events. It is also used to submit client request to the
server. To create Button either we can write code or use the drag and drop facility of
visual studio IDE.
• This is a server side control and asp provides own tag to create it. The example is
given below.
• < asp:ButtonID="Button1" runat="server" Text="Submit" BorderStyle="Solid" ToolTip
="Submit"/>
• Server renders it as the HTML control and produces the following code to the
browser.
• <input name="Button1" value="Submit" id="Button1" title="Submit" style="border-
style:Solid;" type="submit">
• 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.
Height It is used to set height of the control.
Width It is used to set width of the control.
o Image Button
• The image button is used to display a clickable image,and a control that displays an
image and responds to mouse clicks on the image.
• Following are some important properties that are very useful.
Property Description
ImageUrl Gets or Sets the location of the image to display.
CausesValidation Value can be set as true/false. This indicates whether validation should
be performed when a button is clicked.
PostBackUrl Indicates the URL on which the Form will be posted back.
ValidationGroup Gets or Sets the name of the validation group that the button belongs
to. This is used to validate only a set of Form controls with a Button.
OnClick Attach a server side method that will fire when button will be clicked.
OnClientClick Attach a client side (javascript) method that will fire when button will
be clicked.
o Link Button
• LinkButton displays the button like a HyperLink. Use the Text property to change the
LinkText.
• This control looks like a Hyperlink control but almost has the functionality of the
Button control. Despite being a hyperlink, you can't specify the target URL. There is
no UserSubmitBehavior property like the Button control with this control.
21BCACC602 - Programming with ASP.NET Page 15 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Following are some important properties that are very useful.
Property Description
CausesValidation Value can be set as true/false. This indicates whether validation will
be performed when this button will be clicked.
PostBackUrl Indicates the URL on which the Form will be posted back if this button
will be clicked.
ValidationGroup Gets or Sets the name of the validation group that the button belongs
to. This is used to validate only a set of Form controls with this
Button.
OnClick Attach a server side method that will fire when this button will be
clicked.
OnClientClick Attach a client side (javascript) method that will fire when this button
will be clicked.
3. Web Controls for Selecting Choices
o Radio Button
• It is an input control which is used to takes input from the user. It allows user to
select a choice from the group of choices.
• To create RadioButton we can drag it from the toolbox of visual studio.
• This is a server side control and ASP.NET provides own tag to create it. The example
is given below.
• < asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupName="gen
der"/>
• Server renders it as the HTML control and produces the following code to the
browser.
• <input id="RadioButton1" type="radio" name="gender" value="RadioButton1" /><la
belforlabelfor="RadioButton1">Male</label>
• 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.
Height It is used to set height of the control.
Width It is used to set width of the control.
GroupName It is used to set name of the radio button group.
o Radio Button List Control
• The RadioButton List class is derived from the Web Control class which groups the
radio button controls. This immensely helps programmers by providing a single
selection radio button group. This group can also be generated dynamically with the
21BCACC602 - Programming with ASP.NET Page 16 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
help of data binding. In this topic, we are going to learn about ASP.NET
RadioButtonList.
• The RadioButtonList control supports three important properties that affect its
layout:
RepeatColumns: It displays the number of columns of radio buttons.
RepeatDirection: The direction that the radio buttons repeat. By default
RepeatDirection value is vertical. Possible values are Horizontal and Vertical.
RepeatLayout: Determines whether the radio buttons display in an HTML table.
o Check Box
• It is used to get multiple inputs from the user. It allows user to select choices from
the set of choices.
• It takes user input in yes or no format. It is useful when we want multiple choices
from the user.
• To create CheckBox we can drag it from the toolbox in visual studio.
• This is a server side control and ASP.NET provides own tag to create it. The example
is given below.
• < asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>
• Server renders it as the HTML control and produces the following code to the
browser.
• < input id="CheckBox2" type="checkbox" name="CheckBox2" />
• <label for="CheckBox2">J2EE</label>
• 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.
Height It is used to set height of the control.
Width It is used to set width of the control.
Checked It is used to set check state of the control either true or false.
o Check Box List Control
• The checkboxlist can be created using the design section by dragging and dropping
the control from the ASP.NET toolbar window, or else it can also create from the
markup section using the following code.
• <asp:CheckBoxList id= "checkboxlist1" AutoPostBack = "True" TextAlign = "Right"
OnSelectedIndexChanged = "CheckList_Clicked" runat= "server">
• <asp:ListItem> Item 1 </asp:ListItem>
• <asp:ListItem> Item 2 </asp:ListItem>
• <asp:ListItem> Item 3 </asp:ListItem>
• The above code will create a checkboxlist named “checkboxlist1” containing items
“Item1”, “Item2” and “item3” created using the element <asp:ListItem>. These items
21BCACC602 - Programming with ASP.NET Page 17 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
contain a checkbox preceding every element in the list.
4. Web Controls for Creating List
o DropDown List
• The DropDownList is a web server control which is used to create an HTML Select
component. It allows us to select an option from the dropdown list.
• It can contain any number of items
• ASP.NET provides a tag to create DropDownList for web application. The following is
the Syntax of DropDownList tag.
<asp:DropDownList id="DropDownList1" runat="server"
DataSource="<% databindingexpression %>"
DataTextField="DataSourceField"
DataValueField="DataSourceField"
AutoPostBack="True|False"
OnSelectedIndexChanged="OnSelectedIndexChangedMethod">
<asp:ListItem value="value" selected="True|False">
Text
</asp:ListItem>
</asp:DropDownList>
• Now, to add items to the list, visual studio provides Items property where we can
add items. The property window looks like this.
• Click on the items (collection) and it will pop up a new window as given below.
Initially, it does not have any item. It provides add button to add new items to the
list.
21BCACC602 - Programming with ASP.NET Page 18 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Adding item to the DropDownList, by providing values to the Text and Value
properties.
• We have added more items to it and now, it looks like the following.
o ListBox
21BCACC602 - Programming with ASP.NET Page 19 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• The ListBox in ASP.NET control provides a means to display a list of selectable items
on a web page.
• There are several methods and properties available for adding items and customizing
the behavior of the ListBox control:
• The properties, methods, and events of this control are listed in Table
Property Description
Items Represents the collection of items in the list box.
AutoPostBack If True, the form is automatically posted when a new option is
selected from the list box.
SelectedItem Represents the selected option.
SelectedIndex Specifies the index number of currently selected option.
SelectionMode Determines whether a user can select more than one list item.
Possible values are Single and Multiple.
Rows Indicates the number of rows to display in the list box. Default is
4.
DataSource Identifies the data source for the items listed in the list box.
DataMember Identifies the particular table in a data source to bind to the
control.
DataTextField Identifies the field from the data source to use for option text.
DataValueField Identifies the field from the data source to use for option
values.
DataTextFormatString Gets or sets a format string that determines how DataTextField
is displayed.
ListBox1.Items.Count = Return the total count of items in the listbox.
ListBox1.Items.Add(“ItemName”) = Add the new item in to the listbox control.
ListBox1.Items.Insert(int index, “ItemName”) = Add the new item at specific position in
listbox control.
ListBox1.Items.Remove(“ItemName”) = Remove the item from the listbox control.
ListBox1.Items.RemoveAt(int index) = Remove the item from the listbox at desired position
index.
ListBox1.Items.Clear() = Clear all the items from listbox control.
ListBox1.SelectedItem.Text = Returns the Text value of selected item of the listbox.
ListBox1.SelectedValue = Returns the Value property of the selected item of the listbox.
ListBox1.SelectedIndex = Returns the Index of selected item of listbox. (Index always start
from Zero).
Here, is the code for bind listbox control from database.
ListBox1.DataSource = DataTable OR DataSet
ListBox1.DataTextField = Bind the Text to listbox (It is visible in listbox)
ListBox1.DataValueField = Bind the Value to listbox (It is Invisible in listbox)
ListBox1.DataBind();
21BCACC602 - Programming with ASP.NET Page 20 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o Bulleted List
• The BulletedList control renders either an unordered (bulleted) or ordered
(numbered) list.
• Each list item can be rendered as plain text, a LinkButton control, or a link to another
web page. For example, the page given below uses the BulletedList control to render
an unordered list of products.
• We can control the appearance of the bullets that appear for each list item with the
BulletStyle property.
• This property accepts the following values:
✔ Circle
✔ CustomImage
✔ Disc
✔ LowerAlpha
✔ LowerRoman
✔ NotSet
✔ Numbered
✔ Square
✔ UpperAlpha
✔ UpperRoman
• We can set BulletStyle to Numbered to display a numbered list. If you set this
property to the value CustomImage and assign an image path to the BulletImageUrl
property, then we can associate an image with each list item.
• For example, the page given below displays an image named Bullet_List.gif with each
list item.
o Common Properties for all Control
Property Description
AccessKey Use the AccessKey property to specify the keyboard shortcut for the Web
server control. This allows you to navigate quickly to the control by
pressing the ALT key and the key for the specified character on the
keyboard. For example, setting the access key of a control to the
string "D" indicates that the user can navigate to the control by pressing
ALT+D.
tabindex The tab index of the Web server control. The default is 0, which indicates
that this property is not set.
Attributes The Attributes collection contains a collection of all attributes declared in
the opening tag of a Web server control. This allows you to
21BCACC602 - Programming with ASP.NET Page 21 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
programmatically control the attributes associated with a Web server
control. You can add attributes to the collection or remove attributes from
the collection.
Width A Unit that represents the width of the control. The default is Empty.
PostBackurl The PostBackUrl property allows you to perform a cross-page post using
the Button control. ... Only correctly specified paths work with this
property.
5. Rich Controls
o Calendar Control
• It is used to display selectable date in a calendar. It also shows data associated with
specific date. This control displays a calendar through which users can move to any
day in any year.
• We can also set Selected Date property that shows specified date in the calendar.
• To create Calendar we can drag it from the toolbox of visual studio.
• This is a server side control and ASP.NET provides own tag to create it. The example
is given below.
< asp:CalendarID="Calendar1" runat="server" SelectedDate="2017-06-
15" ></asp:Calendar>
• 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.
NextMonth Text It is used to set text for the next month button.
TitleFormat It sets format for month title in header.
DayHeaderStyle It is used to set style for the day header row.
DayStyle It is used to apply style to days.
NextPrevStyle It is used to apply style to the month navigation buttons.
o Adrotator Control
• 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 displays the sequence of images, which is specified in the external
XML file. In a xml file we indicate the images to display with some other attributes,
like image impressions, NavigateUrl, ImageUrl, AlternateText.
• In a Adrotator control images will be changed each time while refreshing the web
page.
AdRotator Control Syntax :
21BCACC602 - Programming with ASP.NET Page 22 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
<asp:AdRotator ID=“AdRotator1“ runat=“server“ />
AdRotator Control Example in ASP.Net
• Follow below step to create Adrotator control in asp.net web application.
Step 1 – Open Visual Studio –> Create a new empty web application / website.
Step 2 – Create New web page for display AdRotator control.
step 3 – Drag and drop AdRotator Control on web page from toolbox.
step 4 – Right click on Solution Explorer –> Add New Item –> Add New XML File in project
for write advertisement detail.
step 5 – Write code in xml file for advertisement.
step 6 – Assign XML File to AdvertisementFile Property of AdRotator control.
Now, let’s understand the adrotator control with an asp.net example.
Create asp.net web application and take an adrotator control on web forms like below:
• Now, Add new XML file to project.
• Right click on Solution Explorer –> Add New Item –> XML file –> Add.
21BCACC602 - Programming with ASP.NET Page 23 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• How to use Adrotator control in asp.net C#.
• Select XML file, assign any name for xml file and click Add button to add new xml file
in webiste.
21BCACC602 - Programming with ASP.NET Page 24 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• The XML file contains list of advertisement information.
Properties Description
ImageUrl It is describe the path of image which will be displayed in adrotator control.
NavigateUrl Describe the navigation webpage link when user click on ad Image.
AlternateText The text will be displayed when image can not be displayed.
Impressions Describe the display rate of image or priority of image
Keyword It is a category of Ad.
• Advertisement XML File for Adrotator Control
• Write below code in xml file for advertisement.
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>img/1.jpg</ImageUrl>
<NavigateUrl>https://google.com</NavigateUrl>
<AlternateText> Academy</AlternateText>
<Impressions>50</Impressions>
<Keyword>google</Keyword>
</Ad>
<Ad>
<ImageUrl>img/2.png</ImageUrl>
<NavigateUrl>https://www.w3schools.com</NavigateUrl>
<AlternateText> Aademy</AlternateText>
<Impressions>100</Impressions>
<Keyword>w3school</Keyword>
</Ad>
<Ad>
<ImageUrl>img/3.png</ImageUrl>
<NavigateUrl>https://www.javatpoint.com/asp-net-tutorial</NavigateUrl>
<AlternateText> Aademy</AlternateText>
<Impressions>50</Impressions>
<Keyword>javatpoint</Keyword>
</Ad>
</Advertisements>
• Now, assign the XML file to adrotator control at AdvertisementFile property of
adrotator control.
21BCACC602 - Programming with ASP.NET Page 25 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• The output of Adrotator control example in c#.
21BCACC602 - Programming with ASP.NET Page 26 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• In above Adrotator control example we assign three images in Advertisement xml
file.
• We can see in above figure each time ad image will be changed when we refresh the
webpage.
o FileUpload Control
• The fileupload control in asp.net used to upload any file like image, document file,
zip file ..etc to asp.net website.
Step 1 – Open the Visual Studio –> Create a new empty Web application.
Step 2 – Create a New web page for display FileUpload control.
Step 3 – Drag and drop FileUpload control on web page along with one Button control
from Toolbox.
Step 4 – Write server side code in button click event for upload image using FileUpload
control.
Step 5 – Create new folder “img” in solution explorer to store images.
• Now, add new folder for save uploaded image by right click on website project and
select New Folder shows like below. give name img to newly created folder in
asp.net. when we upload file or image using fileupload control the file uploaded in to
img folder in our website.
21BCACC602 - Programming with ASP.NET Page 27 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Here, is the asp.net fileupload control example design layout. here we took one
fileupload control, a button control and a label control for design web page.
• fileupload control brows and select the image or file from our local drive fro upload
and the button control upload the file to desired folder in out website.
• In this fileupload control example we make img folder for save file on website.
• Here, we can see the output when we browse the file for upload. just select any file
from local drive and select open button to select the file for upload.
21BCACC602 - Programming with ASP.NET Page 28 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• After selecting file for upload click the Upload button to upload file to desired
location at website.
• Here, is the button click event code for upload file to specific folder on website.
protected void btnupload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/img/") + FileUpload1.FileName);
Label1.Text = "Image Uploaded Successfully !!";
}
else
{
Label1.Text = "Select image first !!";
}
}
21BCACC602 - Programming with ASP.NET Page 29 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
6. Other Web Controls
o Literal Controls
• The Literal Control is similar to the Label Control as they both are used to display
static text on a web page.
• The Literal Control is not inherited from WebControl namespace.
• The Literal Control doesn't provide substantial functionality but Literal text is
programmable.
• It doesn't add any HTML elements to the web page. This control makes it possible to
add HTML code directly in the code designer window without switching to design
view and clicking the HTML button to edit the HTML.
• You cannot apply a style to a literal control.
• Unlike Label control, there is no property like BackColor, ForeColor, BorderColor,
BorderStyle, BorderWidth, Height etc. for Literal control. That makes it more
powerful, you can even put a pure HTML contents into it.
When to user Literal Control?
• Literal control is one of the rarely used controls but it is very useful.
• Literal control is light weight control.
• The Literal Control is useful when you want to add text to the output of the page
dynamically (from the server).
• With that you can even programmatically manipulate the Literal text from the code
behind.
o Image Control
• To use the Image control, you need to add it to your ASP.NET markup (e.g., in an
.aspx file) and specify the source of the image using the ImageUrl property.
Property Description
AlternateText Enables you to provide alternate text for the
21BCACC602 - Programming with ASP.NET Page 30 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
image (required for accessibility).
GenerateEmptyAlternateText Enables you to set the AlternateText
property to an empty string.
ImageUrl Enables you to specify the URL to the image.
ImageAlign Enables you to align the image relative to
other HTML elements in the page. Possible
values are AbsBottom, AbsMiddle, Baseline,
Bottom, Left, Middle, NotSet, Right, TextTop,
and Top.
DescriptionUrl Enables you to provide a link to a page that
contains a detailed description of the image
(required to make a complex image
accessible).
o Image Map Control
• The ImageMap control in ASP.NET 2.0 and onward versions can be used to create an
image that contains defined hot spot regions.
• When a user clicks a hot spot region, the control can either generate a post back to
the server or navigate to a specified URL.
• There are three kinds of hot spot regions defined in ImageMap control.
• RectangleHotSpot
• CircleHotSpot
• PolygonHotSpot
• The RectangleHotSpot defines rectangular hot spot regions.
• The CircleHotSpotdefines circle-shaped ones and the PolygonHotSpot is used for
irregularly shaped hot spot area.
Property Description
ImageUrl Url of image location.
AlternetText Appears if image not loaded properly
Tooltip Appears when on mouse over the image
ImageAlign Used to align the Text beside image.
HotSpotMode PostBack/Navigate .... When Navigate, the user is navigated to a different
URL. In case of PostBack, the page is posted back to the server.
OnClick Attach a server side event that fires after clicking on image when
HostSpotMode is PostBack.
PostBackValu You can access it in the server side click event through
e ImageMapEventArgs. (eg. e.PostBackValue)
21BCACC602 - Programming with ASP.NET Page 31 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o Panel Control
• The Panel control works as a container for other controls on the page. It controls the
appearance and visibility of the controls it contains. It also allows generating controls
programmatically.
• The basic syntax of panel control is as follows:
• <asp:Panel ID= "Panel1" runat = "server">
• </asp:Panel>
• The Panel control is derived from the WebControl class. Hence it inherits all the
properties, methods and events of the same. It does not have any method or event
of its own. However it has the following properties of its own:
Properties Description
BackImageUrl URL of the background image of the panel.
DefaultButton Gets or sets the identifier for the default button that is
contained in the Panel control.
Direction Text direction in the panel.
GroupingText Allows grouping of text as a field.
HorizontalAlign Horizontal alignment of the content in the panel.
ScrollBars Specifies visibility and location of scrollbars within the panel.
Wrap Allows text wrapping.
o Hyperlink Control
• It is a control that is used to create a hyperlink. It responds to a click event. We can
use it to refer any web page on the server.
• 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.
NavigateUrl It is used to set navigate URL.
Target Target frame for the navigate url.
21BCACC602 - Programming with ASP.NET Page 32 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o Understanding Site Maps
• 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.
• You 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 SiteMapProvider internally utilizes the SiteMapProvider abstract class defined
under the System.Web namespace.
o Sitemap Path Control
• 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.
• You 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
21BCACC602 - Programming with ASP.NET Page 33 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
data from databases and it stores the information in a data source.
• The SiteMapProvider internally utilizes the SiteMapProvider abstract class defined
under the System.Web namespace.
• The representation of the SiteMapPath control is as follows:
• Root Node->Child Node
Creating the SiteMapPath Control
• Now let's create an application by using the SiteMapPath control. In this application
we design the following three pages:
• The Home Page (Default.aspx)
• The First Page (myweb1.aspx)
• The Second page (myweb2.aspx)
• Now we can use the SiteMapPath control using the following steps:
• Step 1: Open Microsoft Visual Studio 2010.
• Step 2: Select File->New->Web Site.
• Step 3: Select ASP.NET Web Site and name it as mywebsite.
• Step 4: Add two web forms to the application named myweb1.aspx and
myweb2.aspx by performing the following steps:
• Move to the Solution Explorer window
• Right-click on the application name and select the Add New Item option from the
context menu
• Name the web form as myweb1.aspx and click the Add button
• Step 5: Similarly add the myweb2.aspx web form to the application. After that we
have to add the Site Map file into the project. The Site Map file is the XML file and
has the extension .sitemap. The steps are as follows.
• Step 6: Right-click the application in the Solution Explorer window and then click the
Add New Item option from the context menu.
• Step 7: Select the Site Map Template from the Templates Pane. Note that, by
default, the file has the name web.sitemap.
21BCACC602 - Programming with ASP.NET Page 34 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Step 8: Now click the Add button to add the sitemap file to our application.
• Step 9: Now we can check that the 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.
1. <?xml version="1.0" encoding="utf-8" ?>
2. <siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-
1.0" >
3. <siteMapNode url="Default.aspx" title="myhomepage" descriptio
n="">
4. <siteMapNode url="myweb1.aspx" title="myfirstpage" descr
iption="" />
5. <siteMapNode url="myweb2.aspx" title="mysecondpage" desc
ription="" />
6. </siteMapNode>
7. </siteMap>
• Step 10: Now, Add SiteMapDataSource control from toolbox to our asp.net web
21BCACC602 - Programming with ASP.NET Page 35 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
form.
• Step 11: Add SiteMapPath control from Navigation part of toolbox to web form.
21BCACC602 - Programming with ASP.NET Page 36 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• You can write below code of SiteMapDataSource control and SiteMapPath control
to all pages insted of drag and drop control.
• <asp:SiteMapDataSource ID=”SiteMapDataSource1″ runat=”server” />
<asp:SiteMapPath ID=”SiteMapPath1″ runat=”server”>
</asp:SiteMapPath>
• Step 12: Write above code in all web page for SiteMapDataSource and SiteMapPath.
21BCACC602 - Programming with ASP.NET Page 37 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o Menu Control
• The ASP.NET Menu supports you to display a Menu of list-out items.
• This Menu is based on UL-LI hierarchy, where the sub-list items can be rendered as
the sub-menu items.
• You can also render the Menu control with local and remote data source.
Properties of Menu Control
DataSourceID Indicates the data source to be used (You can use .sitemap file as
datasource).
Text Indicates the text to display in the menu.
Value Indicates the nondisplayed value (usually unique id to use in server side
events)
NavigateUrl Indicates the target location to send the user when menu item is clicked. If
not set you can handle MenuItemClick event to decide what to do.
Selectable true/false. If false, this item can't be selected. Usually in case of this item
has some child.
ImageUrl Indicates the image that appears next to the menu item.
ImageToolTip Indicates the tooltip text to display for image next to the item.
PopOutImageUrl Inidcates the image that is displayed right to the menu item when it has
some subitems.
Orientation Vertical / Horizontal , set the menu orientation.
21BCACC602 - Programming with ASP.NET Page 38 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• From the following guideline, you can learn how to customize the Menu control for a
website.
Step 1: Add Menu Tool From toolbox.
Step 2: Click on edit Menu Items for edit Menu.
21BCACC602 - Programming with ASP.NET Page 39 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Step 3: Click on add root item for add root.
Step 4: After add root items Click on Add child Item for add sub menu.
21BCACC602 - Programming with ASP.NET Page 40 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Step 5: Set the NavigateUrl Property for all the root and sub menu for Navigate page.
o Tree View Control
• ASPxTreeView is an easy and useful navigation control that allows you to represent
hierarchical structure data as a tree.
• With ASPxTreeView, you can manually create a tree or easily populate it with data by
binding to hierarchical data sources, including XmlDataSource and
SiteMapDataSource.
• You can also operate in Virtual Mode to efficiently use your server resources when
working with complex or dynamically created hierarchies.
• The ASPxTreeView control is highly customizable: you can change the appearance of
almost any visual element in ASPxTreeView. With integrated template technology
you can easily transform nodes into anything you can imagine.
21BCACC602 - Programming with ASP.NET Page 41 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Properties Of Tree View Control:
Property Description
Gets the total number of TreeView nodes. For the treeNodeProxy control,
Count this property gets the number of child nodes under the specific node. (Int32
type)
Nodes Gets a collection of TreeView nodes (IList[] type).
Gets the character used to delineate child nodes in the path string identifying
PathSeparator
a particular node. This property also displays in the Properties window.
RootNode Gets the main (root) node for the TreeView. (TreeNode type)
SelectedNode Gets the currently selected TreeView node (TreeNode type).
• From the following guideline, you can learn how to customize the Tree View control
for a website.
Step 1: Add Treeview Tool From toolbox.
Step 2: Click on Edit Nodes for Add Root Node of Tree.
21BCACC602 - Programming with ASP.NET Page 42 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Also you can click on Nodes from Property for add Root Node of Tree.
Step 3: Click on Add Root Node for Add Root Node of Tree. And Give the Root Node
Name.
21BCACC602 - Programming with ASP.NET Page 43 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Step 4: Click on Add Child Root Node for Add child Node of Tree. And Give the child
Node Name.
Tree View Out put
21BCACC602 - Programming with ASP.NET Page 44 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• What is Themes & Skin file
• Sometimes we need to change the layout of application for different-different user.
For example if a single application is used by different-different client and every
client has his own color schema, logo, font etc. requirements then we use themes A
theme is a collection of skin files, css, graphics, images etc.
• A theme is a collection of property settings that allow you to define the look of pages
and controls, and then apply the look consistently across pages in a Web application,
across an entire Web application, or across all Web applications on a server.
• Themes are made up of a set of elements: skins, cascading style sheets (CSS), images,
and other resources. At a minimum, a theme will contain skins. Themes are defined
in special directories in your Web site or on your Web server.
• Skins
• A skin file has the file name extension .skin and contains property settings for
individual controls such as Button, Label, TextBox, or Calendar controls. Control skin
settings are like the control markup itself, but contain only the properties you want
to set as part of the theme. For example, the following is a control skin for
a Button control:
• Skin files are those files in which we define the common property setting for asp.net
controls like button, texbox, label etc. The extension of skin files is .skin. It comes
under the themes.
• Type of Skin
• There are two type of skin in asp.net and these are as follows:-
• Default Skin
• When we want to apply same property for all controls in the page then we use
default skin. This skin automatically applies to the control which defined in the skin.
This type of skin does not contain the SkinId property.
• Named skin
• A named skin is applied to those controls in which we pass skin id. A named skin
contains the SkinId.
• Example of Skin:-
• Right click on the theme in which you want to add skin file and give it proper name.
21BCACC602 - Programming with ASP.NET Page 45 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Empty the skin file and add your own code in this file. For example I added skin for
button where I add the back color property which is as follows:-
<asp:Button runat="server" BackColor="Red" skinid="sk1" />
<asp:Label runat="server" BackColor="Pink" skinid="sk2" />
<asp:TextBox runat="server" BackColor="Blue" skinid="sk3" />
• The output of this code as follows:-
• This is the example of Default skin file.
• Now add the control property using skinId which is as follows:-
<asp:Label ID="Label1" runat="server" SkinID="
" Text="Enter Name:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" SkinID="sk3"></asp:TextBox>
<asp:Button ID="Button1" runat="server" SkinID="sk1" Text="Button" />
21BCACC602 - Programming with ASP.NET Page 46 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Unit -3 ASP.NET Validation Controls & State Management
• ASP.Net provides various validation controls that validate the user data to ensure
that the data entered by the user are satisfied with the condition.
• ASP.NET supports two types of validation controls:
1. Client-side validation controls
2. Server-side validation controls
1. Client-side validation is good, but we must depend on browser and scripting language
support. The client-side validation is done in the user's browser using JavaScript and
another scripting. You can use client-side validation libraries such as
WebUIValidation.js in .NET.
2. Server-side validation in ASP.NET is done in the C# code-behind, where the value of
the user input is read and validated on the server. This process is time-consuming
but provides better security and is easier to implement in ASP.NET. For example, if
an app wants to check the date range, the date value will be read from ASP.NET in
C#, and the C# code behind the validation method will be compared against the
rules.
• ASP.Net provides RequiredFieldValidator, RangeValidator, CompareValidator,
RegularExpressionValidator, CustomValidator and ValidationSummary.
• RequirefFieldValidator is used when the specific filed is required, RangeValidator is
used when specific value needs to be within the specified range, CompareValidator
is used to compare the value of one control with fixed value of another control,
RegularExpressionValidator validate the input value with the pattern of regular
expression, CustomValidator allows user to create own validation,
ValidationSummary gives summary.
• All the validation controls in ASP.Net inherit the properties and methods of the
BaseValidator class. It helps in making a generic suite of validation controls. The
important properties and methods of the BaseValidator class are:
Members Description
ControlToValidate Indicates the input control to validate.
Display Indicates how the error message is shown.
EnableClientScript Indicates whether client side validation will take.
Enabled Enables or disables the validator.
ErrorMessage Indicates error string.
Text Error text to be shown if validation fails.
IsValid Indicates whether the value of the control is valid.
21BCACC602 - Programming with ASP.NET Page 47 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
SetFocusOnError It indicates whether in case of an invalid control,
the focus should switch to the related input
control.
ValidationGroup The logical group of multiple validators, where this
control belongs.
Validate() This method revalidates the control and updates
the IsValid property.
• Required Field Validator Control
• The RequiredFieldValidator control ensures that the required field is not empty. It is
generally tied to a text box to force input into the text box.
• The syntax of the control is as given:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="RequiredFieldValidator"
ForeColor="Red">
</asp:RequiredFieldValidator>
• Compare Field Validator Control
• The CompareValidator control compares a value in one control with a fixed value or
a value in another control.
• It has the following specific properties:
Properties Description
Type It specifies the data type.
ControlToCompare It specifies the value of the input control to
compare with.
ValueToCompare It specifies the constant value to compare with.
Operator It specifies the comparison operator, the available
values are: Equal, NotEqual, GreaterThan,
GreaterThanEqual, LessThan, LessThanEqual, and
DataTypeCheck.
• The basic syntax of the control is as follows:
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="TextBox1"
ControlToValidate="TextBox2"
ErrorMessage="CompareValidator" Type="Integer"
ValueToCompare="Equal">
</asp:CompareValidator>
• Range Validator Control
• The RangeValidator control verifies that the input value falls within a predetermined
range.
• It has three specific properties:
21BCACC602 - Programming with ASP.NET Page 48 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Properties Description
Type It defines the type of the data. The available values
are: Currency, Date, Double, Integer, and String.
MinimumValue It specifies the minimum value of the range.
MaximumValue It specifies the maximum value of the range.
• The syntax of the control is as given:
<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
• Regular Expression Validator Control
• 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="RegularExpressionValidator1"
runat="server"
ControlToValidate="TextBox2"
ErrorMessage="RegularExpressionValidator"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-
.]\w+)*">
</asp:RegularExpressionValidator>
• Validation Summary Control
• The ValidationSummary control does not perform any validation but shows a
summary of all errors in the page. The summary displays the values of the
ErrorMessage property of all validation controls that failed validation.
• The following two mutually inclusive properties list out the error message:
• ShowSummary : shows the error messages in specified format.
• ShowMessageBox : shows the error messages in a separate window.
• The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />
• Custom Validator Control
• What if there is no validator control that matches your need? In that case, you can
use the CustomValidator control. The CustomValidator control in ASP.NET allows you
to create your own custom logic to validate user data.
21BCACC602 - Programming with ASP.NET Page 49 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• The CustomValidator Control can be used on the client side and server side.
JavaScript is used for client validation; you can use any .NET language to do server-
side validation. Ib this example, I use the server-side CustomValidator.
• for Example:
protected void CustomValidator1_ServerValidate1(object source,
ServerValidateEventArgs args)
{
int val = Convert.ToInt32(TextBox1.Text);
if (val < 18)
args.IsValid = false;
else
args.IsValid = true;
}
• State Management Techniques. What is State?
• All web applications are stateless. means in asp.net each page posted to the server,
the state of controls is lost. In other word, all user can send request to web server
but web server does not know about request from they coming same user or new
user.
• We must make web pages which will remember about the user. Using state
management technique we identify the each user uniquely on same web pages. To
preserve state of control we use state management technique in asp.net.
• Why State Management is required?
• State basically means an interaction between the user and the server and the HTTP
Protocol acts like a bridge between them.
• But since the HTTP Protocol is a Stateless protocol, it is not able to store the state
during that session. With each request the objects are created and memory is being
allocated. These resources are destroyed once the server completes its process.
• In such a case, the information given by the user or the State of an Application gets
lost during each round trip. So this is where State Management helps.
21BCACC602 - Programming with ASP.NET Page 50 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Types of State Management
• Client Side State Management
• The options available in client side state management help in storing information
either in the page or at the client computer. No information is stored at server side.
1. Cookies State Management
• Cookies is a small pieces of text information which is stored on user hard drive using
users browser for identify users. It may contain username, ID, password or any
information. Cookie does not use server memory.
• Cookies stored user computer at “C”\Document and Setting\Current
login_User\Cookie”.
• Types of Cookies
• Persistence Cookie
• Non-Persistence Cookie
1. Persistence Cookie
• This types of cookies are permanently stored on user hard drive.
Cookies which have an expiry date time are called persistence cookies. This types of
cookies stored user hard drive permanently till the date time we set.
• Example to create persistence cookie
• Response.Cookies[“name”].Value = “Atmiya”;
Response.Cookies[“Atmiya”].Expires = DateTime.Now.AddMinutes(10);
• we can also create same cookies as like below
• HttpCookie strname = new HttpCookie(“name”);
strname.Value = “Atmiya”;
strname.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(strname);
• In above code we use Response.Cookies object for create Cookie.
In above example we have set 10 Minute time for Expire Cookie, we can retrieve
cookie values up to 10 minutes, after 10 minutes the cookies automatically expires.
21BCACC602 - Programming with ASP.NET Page 51 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
2. Non-Persistence Cookie
• This types of cookies are not permanently stored on user hard drive. It stores the
information up the user accessing the same browser. When user close the browser
the cookies will be automatically deleted.
• Example to create non-persistnce cookie
• Response.Cookies[“name”].Value = “Atmiya”;
• we can also create same non-persistence cookies as
• HttpCookie strname = new HttpCookie(“name”);
strname.Value = “Atmiya”;
Response.Cookies.Add(strname);
• Read Cookie Information
• if (Request.Cookies[“name”] != null)
{
Label1.Text = Request.Cookies[“name”].Value;
}
• Advantages
• Very easy to use.
• Stored on the client's machine, hence no server resources are utilized.
• Disadvantages
• A user can disable cookies using browser settings.
• Since the cookies are stored on the client's machine, there are chances that if the
client's machine is hacked then the hacker can view these cookie values. Hence we
should not store sensitive information in cookies.
2. View State Management
• View State can be used to maintain the State at a page level. The term "Page Level"
means that the information is being stored for a specific page and until that specific
page is active (i.e. the page which is being currently viewed by the user). Once the
user is re-directed or goes to some other page, the information stored in the View
State gets lost.
• It basically makes use of a "Dictionary Object" to store data, which means that the
information is stored in a key and value pair. It stores this information in a Hidden
field on the page itself in a hashed format. A View State can store a string value only
of a specific length. If the length is exceeded then the excess information is stored in
another hidden field.
• Using a View State is quite simple. In fact, it is the default way for storing the page
or the control's information. Typically the View State is used, when we want a user
to be re-directed to the same page and the information being added by the user
remains persistent until the user is on the same page.
21BCACC602 - Programming with ASP.NET Page 52 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Storing Value in a View State
• Here in the code above, "Username" is the key and the value is the text being
inputted by the user (txtFName.Text).
• Retrieving Value from a View State
• Here as you can see in the image, I am retrieving the value from the View State, in
the Page Load event of a page by first checking if the View State is not empty or null
and then assigning its value to a Label. This is just a simple example which is shown
to make you understand about, how to use a View State.
• View State Information is stored in a Hashed Format
• If you look at the page source, then this is the way View State stores the value.
• View State Settings
• View State is customizable. With the term "Customizable" I mean, that we can apply
settings to a View State to store a value at various levels. We can set the View State
at various levels like:
• Setting View State at Application Level
If we do not want our pages in the Application to use view state, then we can disable
21BCACC602 - Programming with ASP.NET Page 53 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
or enable it in the web.config file, as shown in the image below.
• Setting View State at Page Level
If we do not want a specific page to use View State, then we can disable or enable it
in the @ Page Directive which is the first line of our aspx page.
• Setting View State at Control Level - If we do not want a specific control to use View
State, then we can disable or enable it at a Control Level as follows:
• Advantages of using a View State
• It is very simple to use.
• Data is stored in hashed format and hence a layman won't be able to understand the
value of the View State (It still can be hacked by Hackers, so to make it more secure
we should try to store the value in an encrypted format.). Check out this link
http://msdn.microsoft.com/en-us/library/ms178199(v=vs.85).aspx to understand,
how to secure View State.
• It is customizable, as shown above.
• Disadvantages of using a View State
• Information is not encrypted, so it can be easy for a Hacker to get its value.
• Cannot be used to store sensitive data (eg: Passwords, Credit Card Pins, etc).
• Might make a page heavy if lots of data is stored in View State.
3. Control State Management
• Another client-side state management mechanism is Control State. We can use the
view state if we construct a custom control and wish to keep certain information.
However, if the view state is deliberately disabled by the user, the control will not
perform as planned. We must use the Control State attribute to get expected results
for the control.
• The control state is distinct from the view state. And here’s how you utilize the
control state property -
• Using the control state property is straightforward. First, override the control’s
OnInit() method and add a call to the Page. With the instance of the control to
register, call the RegisterRequiresControlState() function. Then, in order to store the
appropriate state information, override LoadControlState and SaveControlState.
21BCACC602 - Programming with ASP.NET Page 54 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Advantages of using control state are:
• By default, control state is stored in hidden fields on the page.
• Because control state cannot be turned off like view state, control state is a more
reliable method for managing the state of controls.
• Custom adapters can be written to control how and where control-state data is
stored.
• Disadvantage of using control state are:
• Some programming is required While the ASP.NET page framework provides a
foundation for control state, control state is a custom state-persistence mechanism.
To fully utilize control state, you must write code to save and load control state.
4. Query String State Management
• Query string is a simple way to pass some information from one page to another.
The information cab be easily pass to one page to another or to same page. With
query string method the information passed in url of page request.
• This method many browsers supports only 255 character length of url in query
string. The value passed will be visible so some time it cause security issue.
• For send information to other page Response.Redirect() method used and for
retrieve information from url use Request.QueryString() method used.
• In Query String method we can sent value to only desired page, and value will be
temporarily. So Query string increase the overall performance of web application.
• Syntax of Query String
• Send information to other page
• Response.Redirect(“nextpage.aspx?name=value”);
• Retrieve information from other page
• Request.QueryString[“name”].ToString();
5. Hidden field State Management
• ASP.NET provides a server control called "Hidden Field" which can be used to store a
value at a page level, which is similar to a View State.
• The value of the Hidden Field is sent along in the HTTP Form Collection along with
the value of other controls.
• Setting Value to a Hidden Field
Retrieving Value from a Hidden Field
21BCACC602 - Programming with ASP.NET Page 55 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Advantages
• Very simple to use.
• Hidden Fields store the value in the page itself, hence do not use server resources.
• Disadvantages
• Will make a page heavy, if too many Hidden Fields are used to store data.
• Cannot store sensitive data, as the value that is stored is neither hashed, nor
encrypted.
• Server Side State Management
• ASP.NET provides facility to save information on server side as well as in client side.
The following options are available in Server Side State Management.
1. Session State Management
• Session state is a period of time to visit a website for a particular user. Session can
store the client data on a server. Session is a best state management features to
store the client data on server separately for each user.
• Session can store value across on multiple pages of website.
• Viewstate can store value on single page.
• In simple word we can say, At the same time more than one users login to system, all
user identification name store separately until they logout. session can store
username or any unique identification of user for a login period time.
• Session value can be accessible from all pages from website. We can store some
information in session in one page and can access same information on rest of all
page by using session.
• By default, Session state is enabled for all ASP.NET applications.
• When you login to any website with username and password. your username shows
on all other pages.The username will be stored in session and on page we access
session value to display username.
• Syntax of session
• Session[“session_name”] = “session value”;
• Declare session in asp.net
• Session[“name”]=”Meera Academy”;
Response.Redirect(“nextpage.aspx”);
• Above we create session with name parameter and assign value “Meera Academy”
to session[“name”] and redirect user to other page “nextpage.aspx” using
response.redirect method.
• Retrieve session value on other page
21BCACC602 - Programming with ASP.NET Page 56 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• string myvalue= Session[“name”].ToString();
Response.Write(“Name = ” + myvalue);
• Here, we retrieve session[“name”] value and store session value in string variable
“myvalue”.
• Session Timeout
• Session is a length/period of time that a particular browser instances spends
accessing a website. The Session object is used to persist data across a user session
during the user’s visit to a website.
• In asp.net by default session timeout = 20 minutes, but in some cases we need to
change session time increment or decrement by changing web.config file setting.
We can also set manually by write c# code at code behind .aspx page in asp.net.
• Session.Clear() and Session.Abandon()
• we learnt about session object and session timeout properties from our previous
asp.net post. Now, in this asp.net tutorial we learn about session.clear and
session.abandon method in detail.
• Session.Abandon()
• Session.Abandon() method used to destroys the session by generating a Session_End
event
• Session.Abandon() method used to destroy the current session.
• It is same things to dispose of an object.
• It trigger Session_End event Global.asax.
• Session.Abandon() method clear occupied memory location.
• Session.Clear()
• Session.Clear() used to just clears all values of session without destroying it.
• It is same things to assigning null value to a variable.
• It doesn’t trigger Session_End in Global.asax.
• Session.Clear() method just clear session values.
2. Application State Management
• Application state is a global storage mechanism that used to stored data on the
server and shared for all users, means data stored in Application state is common for
all user. Data from Application state can be accessible anywhere in the application.
Application state is based on the System.Web.HttpApplicationState class.
• The application state used same way as session state, but session state is specific for
a single user session, where as application state common for all users of asp.net
application.
• Syntax of Application State
• Store information in application state
• Application[“name”] = “Atmiya”;
• Retrieve information from application state
• string str = Application[“name”].ToString();
3. Cache State Management
• This is stored on the server-side, and it is used to implement page caching and data
caching.
• A cache is primarily used to set expiration policies.
• Example:
21BCACC602 - Programming with ASP.NET Page 57 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1));
21BCACC602 - Programming with ASP.NET Page 58 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Unit - 4 ADO.NET & Database
● ADO.NET Architecture
o ADO stands for ActiveX Data Objects.
o ADO.NET is one of Microsoft’s Data Access Technologies using which we can
communicate with different data sources.
o It is a part of the .NET Framework which is used to establish a connection between
the .NET Application and different data sources.
o Data access is the main part of any application that you develop. Any web base
application or window base applications stores the data for accessing the data for
different purpose.
o Database programming is important aspect for any language that we use for our
development.
o ADO.NET is a group of libraries provided by .NET framework which are used to create
powerful databases using various source such as MS SQL, Microsoft Access, Oracle,
XML etc.
o It provides classes for connecting with a data source, submitting queries and
processing results.
o Thus ADO.NET is a large set of .NET classes which enables us to retrieve and
manipulate data and update data sources in many different ways.
21BCACC602 - Programming with ASP.NET Page 59 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Class Description
SqlConnection It is used to create SQL Server connection. This class cannot be
inherited.
SqlCommand It is used to execute database queries. This class cannot be inherited.
SqlDataAdapter It represents a set of data commands and a database connection that
are used to fill the DataSet. This class cannot be inherited.
SqlDataReader It is used to read rows from a SQL Server database. This class cannot be
inherited.
SqlException This class is used to throw SQL exceptions. It throws an exception when
an error is occurred. This class cannot be inherited.
• Advantages of ADO.NET
o ADO.NET can be used to connect with any type of database such as SQL Server,
Oracle, Access, MySql etc.
o It can also connect with any third party database.
o It supports both connected and disconnected architecture.
o Using ADO.NET , you can easily convert data from Dataset to XML and perform
operations in secure and fast way.
o ADO.NET is quite fast than other applications.
o ADO.NET provides cross language supports for many languages like C#, VB# or J# etc.
ADO ADO.NET
It is based on COM (Component Object It is a CLR (Common Language Runtime)
Modelling). based library.
It works only when data store is It does not needs active connection to access
connected. data from data store.
It has feature of locking. It does not have feature of locking.
21BCACC602 - Programming with ASP.NET Page 60 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
It access and store data from data It access and store data from data source by
source by recordset object. dataset object.
XML integration is not feasible in ADO. XML integration is feasible in ADO.NET.
In ADO, data is stored in binary form. While in this, data is stored in XML.
It allow us to create client side cursors It give us the choice of using weather client
only. side and server side cursors.
It requires SQL JOINs and UNIONs to It uses DataRelational objects, for combining
combine data from multiple tables in a data from multiple tables without requiring
single result table. JOINs and UNIONs.
It allows completely non-sequential data
It supports sequential access of rows in
access in DataSet through collection based
a RecordSet.
hierarchy
o ADO.NET provides two types of architecture for accessing data via database.
o Connected Architecture
o Disconnected Architecture
1) Connected Architecture:
o The architecture of ADO.NET, in which connection to the database must be opened
21BCACC602 - Programming with ASP.NET Page 61 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
to access and retrieved data from database is called connected architecture.
o It is built on the classes called connection, command, datareader and transaction.
o Components of Connected Architecture
o Connection:
o The connection object is the first important component of your application.
o It is required to connect to a backend database that may be SQL Server, Oracle,
MySQL, etc.
o Its main purpose is to establish a connection to database.
o This connection should remain open each time any transaction occurs.
o App.Config
o <configuration>
o <connectionStrings>
o <add name="Master" connectionString ="Data Source=“path" />
o </connectionStrings>
o </configuration>
21BCACC602 - Programming with ASP.NET Page 62 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o C# Code
o string conSting = ConfigurationManager.ConnectionStrings["Master"].ConnectionStri
ng ;
o SqlConnection Conn = new SqlConnection(conSting);
o Methods:
o Open ( ):
o It is used to open the connection with database.
o Close ( ):
o It is used to close the connection with database.
o For connected architecture you need to specify the open and close method.
o For disconnected architecture you do not need to specify the open or close method.
o
o Command:
o The second important component is the command object.
o When we discuss databases such as SQL Server, Oracle, MySQL, then speak SQL, it is
the command object that we use to create SQL queries.
o After you create your SQL queries, you can execute them over the connection using
the command object.
o This object is used to execute SQL queries on the database.
o Using command object you can execute select, insert, update and delete SQL
command.
o // Query to retrieve records
o string query = "select * from Customer";
o
o //Command Class definition
o SqlCommand sc = new SqlCommand(query, Conn);
o Property:
o Connection:
o CommandText:
o It provides the sql queries that will be fired such as insert, update, delete or select
commands.
o CommandType:
o It is used to set or get the type of command.
o It can be either text or stored procedure.
o CommandTimeout:
o Default Time for Execution of Command is 30 Seconds.
o Parameters:
o It used to specify the parameters that would be passed in the parameterized query.
o It can set by using @ symbol.
21BCACC602 - Programming with ASP.NET Page 63 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o Example:
o sqlCommand cmd= new sqlCommand(“insert into emp values(@title)” ,con);
o cmd.Parameters.AddWithValue(“@title” , txtTitle.Text);
o cmd.ExecuteNonQuery();
o con.Close();
o Methods:
o ExecuteNonQuery:
o This method executes the command like insert, update, delete and returns the
number of rows affected.
o ExecuteReader:
o This method is used to read data from table using Select query.
o It helps you to read all records from table.
o ExecuteScalar:
o This method executes the command specified and returns the first column of first
row of the result set.
o The remaining rows and column are ignored.
o
o DataReader:
o It is used to store the data retrieved by command object and make it available for
.NET application.
o Data available in the DataReader is read only and can navigate only in forward
direction.
o It can also read only one record at a time.
o cmd=new SqlCommand("insert into Atmiyac4
values('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"')",con);
o SqlDataReader dr1 = cmd.ExecuteReader();
o Property:
o HasRows:
o It is used to find out whether the data reader contains some rows or not.
o FieldCount:
o It gives you the total number of field count which are loaded under SqlDataReader.
o IsClosed:
o It is used to check whether the data reader is closed or not after reading the data.
o Methods:
o Read:
o This is used to read a record from SqlDataReader class.
o It point to the first record and returns true or false to indicate whether a next record
exists or not.
o Close:
21BCACC602 - Programming with ASP.NET Page 64 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o It is used to close DataReader pointer which is connected to database table.
o 2) Disconnected Architecture
o Disconnected architecture of ADO.NET is one in which data retrieved from database
can be access when the connection to the database is close.
o It is built on connection, dataadapter, commandbuilder and dataset classes.
o In this architecture, the copy of the data is loaded from database and kept in local
memory of client.
o Database is only connected during the copying of the database.
o After copying the database the connection to the database is lost.
o You can perform insert, update, delete or select operations on the local of the
database.
o The updated database is in our local memory only.
o Now when you connect to database again then the local copy of the database is
copied into the final database.
o In this way data consistency is maintained.
21BCACC602 - Programming with ASP.NET Page 65 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o Components of Disconnected Architecture:
o Connection:
o Connection object is used to established between the data source and database.
o DataAdapter:
o This object is used to transfer the data between database and dataset.
o It provides commands like select, insert, update and delete.
o It needs an open connection to transfer the data.
o DataSet:
o It is collection of table that is used to store the data retrieved from database into
local memory.
o You can load single or multiple tables into DataSet.
o DataTable:
o It is used when you want to use or load only one table into local memory.
o DataRow:
o It is used to add or remove one or multiple rows into DataSet or DataTables.
o DataColumn:
o It is used incase if you want to modify any column or add new column into DataSet
or DataTable.
o DataView:
o It is a view of table available in DataSet.
o It is used for many purposes such as to find a record, sort the records, and filter the
records.
o You can also perform insert, update and delete operations on the table as in the case
of a DataSet.
o Data provider are the one which does the work of communication between
application and database.
o They are responsible for maintaining the connection to the database.
o A data provider is a set of classes provided by ADO.NET that allows you to access the
specific database, execute SQL commands and retrieve data.
o ADO.NET provides different types of data provider for different types of database.
o Data Provider
o There are 4 types of data providers provided by Microsoft:
o SQL Server Provider:
o This provider is designed specially to work with SQL server Database.
o It provides data access for Microsoft SQL Server. It requires
the System.Data.SqlClient namespace
o Oracle Provider:
o This providers deals with Oracle database.
o It is used for Oracle data sources. It uses the System.Data.OracleClient namespace.
21BCACC602 - Programming with ASP.NET Page 66 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o OLEDB Provider:
o Object Linking and Embedding, Database.
o This provider works with any database that has OLE DB driver.
o It can access any data from any type of database.
o It is used to connect with OLE DB. It requires the System.Data.OleDb namespace.
o OLEDB is a Windows-only database API.
o ODBC Provider:
o Microsoft Open Database Connectivity (ODBC).
o Almost all the database today comes with ODBC driver inbuilt.
o So you can connect with any database even though drivers are not provided.
o It is used to connect to data sources by using ODBC. It requires
the System.Data.Odbc namespace.
o ODBC is supported on Windows, Linux, Mac, and UNIX.
o ODBC is an SQL-based Application Programming Interface (API) created by Microsoft
that is used by Windows software applications to access databases via SQL.
● Three Tier Architecture in Asp.net
o Three-layer architecture is dividing the project into three layers that are User
interface layer, business layer and data(database) layer where we separate UI,
logic, and data in three divisions. Suppose the user wants to change the UI from
windows to the phone than he has to only make change in UI layer, other layers
are not affected by this change.
o Similarly, if the user wants to change the database then he has to only make a
change in the data layer, rest everything
remains the same.
21BCACC602 - Programming with ASP.NET Page 67 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o What is a Layer?
o A layer is a reusable portion of code that performs a specific function.
o In the .NET environment, a layer is usually set up as a project that represents this
specific function. This specific layer is in charge of working with other layers to
perform some specific goal.
o 1. Presentation Layer
o This is the top layer of architecture. The topmost level of application is the user
interface.
o It is related to the user interface that is what the user sees. The main
function of this layer is to translate tasks and results in something which the
user can understand.
o It contains pages like web forms, windows form where data is presented to the user
and use to take input from the user.
o The presentation layer is the most important layer because it is the one that the user
sees and good UI attracts the user and this layer should be designed properly.
o 2. Business Layer
o This is the middle layer of architecture. This layer involves C# classes and
logical calculations and operations are performed under this layer.
o It processes the command, makes logical decisions and perform calculations. It also
acts as a middleware between two surrounded layers that is presentation and data
layer.
o It processes data between these two layers.
o This layer implements business logic and calculations.
o This layer also validates the input conditions before calling a method from the data
layer. This ensures the data input is correct before proceeding, and can often ensure
that the outputs are correct as well.
o This validation of input is called business rules.
o 3. Data Layer
o This layer is used to connect the business layer to the database or data source.
o It contains methods which are used to perform operations on database like
insert, delete, update, etc.
o This layer contains stored procedures which are used to query database. Hence this
layer establishes a connection with the database and performs functions on the
database.
● GridView Control
o GridView is a powerful and versatile data presentation control in C# that allows
developers to display data in a tabular format with sorting, paging, and editing
capabilities.
o Data from a database or other information sources can be shown using this method
21BCACC602 - Programming with ASP.NET Page 68 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
frequently in online applications. In this article, we will explore GridView in C# in
detail, including its features, properties, and how to use it to display data.
o What is GridView in C#?
o Data can be displayed in a tabular manner with sorting, paging, and editing options
using the C# data presentation control GridView. The
namespace Web.UI.WebControls is frequently used in web
applications. GridView can be bound to various data sources like databases, XML,
and other data sources.
o Features of GridView in C#:
o GridView in C# has several features that make it a popular choice for displaying data
in web applications. Some of the key features of GridView are:
o Sorting:
o GridView allows the sorting of data in ascending or descending order. By pressing
and holding down the shift key while clicking on the column headers, you can sort
across several columns.
o Paging:
o GridView supports the paging of data, which allows you to display a subset of data at
a time. This helps to increase the application's performance when dealing with large
amounts of data.
o Editing:
o GridView provides editing capabilities, which allow users to edit the data directly in
control. This feature is useful when the user needs to make changes to the data
displayed in the control.
o Selection:
o GridView allows the selection of data rows, which can be utilized to perform various
tasks on the selected rows, like deletion, updating, or exporting.
o Formatting:
o GridView provides formatting options for data displayed in the control. You can
manipulate the font, size, color, and other formatting options for the data.
● Repeater Control
o The Repeater control is used to display a repeated list of items that are bound to the
control. The Repeater control may be bound to a database table, an XML file, or
another list of items.
o Repeater is a Data Bind Control. Data Bind Controls are container controls. Data
Binding is the process of creating a link between the data source and the
presentation UI to display the data. ASP .Net provides rich and wide variety of
controls, which can be bound to the data.
o Repeater has 5 inline template to format it:
21BCACC602 - Programming with ASP.NET Page 69 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
1. <HeaderTemplate>
2. <FooterTemplate>
3. <ItemTemplate>
4. <AlternatingItemTemplate>
5. <SeperatorTemplate>
6. <AlternatingItemTemplate>
o HeaderTemplate: This template is used for elements that you want to render once
before your ItemTemplate section.
o FooterTemplate: - This template is used for elements that you want to render once
after your ItemTemplate section.
o ItemTemplate: This template is used for elements that are rendered once per row
of data. It is used to display records
o AlternatingItemTemplate: This template is used for elements that are rendered
every second row of data. This allows you to alternate background colors. It works
on even number of records only.
o SeperatorTemplate: It is used for elements to render between each row, such as
line breaks.
o Some point about Repeater Control
o It is used to display backend result set. It is used to display multiple tuple.
o It is an unformatted control. The Repeater control is a basic templated data-bound
list. It has no built-in layout or styles, so you must explicitly declare all layout,
formatting, and style tags within the control's templates.
o The Repeater control is the only Web control that allows you to split markup tags
across the templates. To create a table using templates, include the begin table tag
(<table>) in the HeaderTemplate, a single table row tag (<tr>) in the ItemTemplate,
and the end table tag (</table>) in the FooterTemplate.
o The Repeater control has no built-in selection capabilities or editing support. You can
use the ItemCommand event to process control events that are raised from the
templates to the control.
o For ex:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table class="tblcolor">
<tr>
<b>
<td>
Roll No
</td>
<td>
Student Name
</td>
</b>
</tr>
21BCACC602 - Programming with ASP.NET Page 70 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
</HeaderTemplate>
<ItemTemplate>
<tr class="tblrowcolor">
<td>
<%#DataBinder.Eval(Container,"DataItem.Id")%>
</td>
<td>
<%#DataBinder.Eval(Container,"DataItem.Name")%>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
o CS file
protected void Page_Load(object sender, EventArgs e)
{
SqlCommand command = new SqlCommand("SELECT * FROM std;", con);
con.Open();
SqlDataReader reader = command.ExecuteReader();
Repeater1.DataSource = reader;
Repeater1.DataBind();
con.Close();
}
● DataList Controls
o DataList is a Databound control to display and manipulate data in a web application.
It is a composite control that can combine other ASP.Net controls and it is present in
the form. The DataList appearance is controlled by its template fields.
The following template fields are supported by the DataList control:
o Itemtemplate: It specifies the Items present in the Datasource, it renders itself in the
browser as many rows present in the data source collection.
o EditItemTemplate: Used to provide edit permissions to the user.
o HeaderTemplate: Used to display header text to the data source collection.
o FooterTemplate: Used to display footer text to the data source collection.
o ItemStyle: Used to apply styles to an ItemTemplate.
o EditStyle: Used to apply styles to an EditItemTemplate
o HeaderStyle: Used to apply styles to a HeaderTemplate
o FooterStyle: Used to apply styles to a FooterTemplate.
o For Ex: aspx file
<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width:
300px; height: 100px;
border: dashed 2px #04AFEF; background-color: #FFFFFF">
<tr>
<td>
<b>ID: </b><span class="city"><%# Eval("ID")
%></span><br />
<b>Name: </b><span class="postal"><%# Eval("Name")
%></span><br />
<b>Email: </b><span class="country"><%#
Eval("Email")%></span><br />
21BCACC602 - Programming with ASP.NET Page 71 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
CS file
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID");
table.Columns.Add("Name");
table.Columns.Add("Email");
table.Rows.Add("101", "Sachin Kumar", "[email protected]");
table.Rows.Add("102", "Peter", "[email protected]");
table.Rows.Add("103", "Ravi Kumar", "[email protected]");
table.Rows.Add("104", "Irfan", "[email protected]");
DataList1.DataSource = table;
DataList1.DataBind();
}
● DetailsView Controls
o The DetailsView Control enable us to work with a single data item at a time. This
control enable us to display, edit, insert, and delete data items such as database
records. Furthermore, it also enable us to page forward and backward through a set
of data items. The DetailsView control always renders each field in a separate HTML
table row.
o Ex:
● Step 1 – Open the Visual Studio –> Create a new empty Web
application.
● Step 2 – Create a New web page.
● Step 3 – Drag and drop DetailsView Control on web page from toolbox.
● Step 4 – Create New Database in SQL Server
● Step 5 – Make connection between Database and web application.
● Step 6 – Bind and Display data to DetailsView.
<asp:DetailsView ID="DetailsView1" runat="server"
BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
CellPadding="2" DataKeyNames="ID" ForeColor="Black" GridLines="None"
Height="50px" onitemdeleting="DetailsView1_ItemDeleting"
onitemupdating="DetailsView1_ItemUpdating"
onmodechanging="DetailsView1_ModeChanging"
onpageindexchanging="DetailsView1_PageIndexChanging" Width="125px">
21BCACC602 - Programming with ASP.NET Page 72 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
<FooterStyle BackColor="Tan" />
<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
HorizontalAlign="Center" />
<HeaderStyle BackColor="Tan" Font-Bold="True" />
<EditRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
<AlternatingRowStyle BackColor="PaleGoldenrod" />
</asp:DetailsView>
● FormView Controls
o The FormView control is used to display a single record at a time from a data source.
When you use the FormView control, you create templates to display and edit data-
bound values.
o The templates contain controls, binding expressions, and formatting that define the
look and functionality of the form.
o The Form View control supports the following features:
o Binding to data source controls, such as SqlDataSource and ObjectDataSource.
o Built-in inserting capabilities.
o Built-in updating and deleting capabilities.
o Built-in paging capabilities.
o Programmatic access to the Form View object model to dynamically set properties,
handle events, and so on.
o Customizable appearance through user-defined templates, themes, and styles.
21BCACC602 - Programming with ASP.NET Page 73 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
Unit - 5 Web service, Configuration &
Deployment
• Overview of XML
o Extensible Markup Language (XML) strores and transports data. If we use a XML
file to store the data then we can do operations with the XML file directly without
using the database.
o The XML format is supported for all applications. It is independent of all software
applications and it is accessible by all applications.
o Here is an example that shows how to insert the data into the XML file and how to
retrieve the data from the XML file; also how to bind the data into tha DataList
using ASP.NET
• Creating /Reading/Inserting XML Files
Step 1: First start Visual Studio 2010 by clicking "File" -> "New" -> "Web Site..."
then click on "ASP.NET Web Site". Now write the following inline code that will
design your web page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 40%;
border-style: solid;
border-width: 1px;
background-color:Silver;
height: 152px;
}
.style2
{
width: 295px;
}
.style3
{
width: 754px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td class="style2">
21BCACC602 - Programming with ASP.NET Page 74 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
</td>
<td class="style3">
Employ
ee_Information</td>
</tr>
<tr>
<td class="style2">
Name:</td>
<td class="style3">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Emp_Id:</td>
<td class="style3">
<asp:TextBox ID="TextBox2"runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Qualification:</td>
<td class="style3">
<asp:DropDownList ID="DropDownList1" runat="server" Height="22px
" Width="132px">
<asp:ListItem>--SELECT--</asp:ListItem>
<asp:ListItem>MCA</asp:ListItem>
<asp:ListItem>BCA</asp:ListItem>
<asp:ListItem>MBA</asp:ListItem>
<asp:ListItem>BBA</asp:ListItem>
<asp:ListItem>BTech</asp:ListItem>
<asp:ListItem>MTech</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3">
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Butto
n1_Click"/>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text
="Show"/>
</td>
</tr>
</table>
21BCACC602 - Programming with ASP.NET Page 75 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
<asp:DataList ID="DataList1" runat="server" BackColor="#DEBA84" BorderCo
lor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" GridLin
es="Both" RepeatDirection="Horizontal"
style="margin-right: 32px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510"/>
<HeaderStyle BackColor="#A55129" Font-
Bold="True"ForeColor="White"/>
<ItemStyle BackColor="#FFF7E7" ForeColor="#8C4510"/>
<SelectedItemStyle BackColor="#738A9C" Font-
Bold="True" ForeColor="White"/>
<ItemTemplate>
<hrsize=0 />
Name:<%#DataBinder.Eval(Container.DataItem,"name")%><br/>
Emp_id:<%#DataBinder.Eval(Container.DataItem,"Emp_id")%></a><br/>
Qualification:<%#DataBinder.Eval(Container.DataItem,"Qualification")%><
br/>
</ItemTemplate>
</asp:DataList>
<br />
</div>
</form>
</body>
</html>
The design will look as in the following image:
Step 2: Add a XML file by clicking "File" -> "Add new item" then click on "XML file".
Name this XML file Sample.xml. Put the following code in the XML file:
<?xml version="1.0"encoding="utf-8"?>
<EmployeeInformation>
21BCACC602 - Programming with ASP.NET Page 76 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
</EmployeeInformation>
Step 3: After that add the following namespaces in the code behind:
using System.Data;
using System.Xml;
Step 4: Now write the following code in the code behind file:
public partial classDefault2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Bind xml data to datalist
BindDatalist();
}
}
private void BindDatalist()
{
XmlTextReader xmlreader
=new XmlTextReader(Server.MapPath("Employee.xml"));
DataSet ds = newDataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
DataList1.DataSource = ds;
DataList1.DataBind();
}
else
{
DataList1.DataSource = null;
DataList1.DataBind();
}
}
}
Step 5: Write the following code in the click event of the submit button, so that the
data that is entered is stored in the XML File:
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xmldoc =new XmlDocument();
21BCACC602 - Programming with ASP.NET Page 77 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
xmldoc.Load(Server.MapPath("Employee.xml"));
BindDatalist();
}
Step 6: Write the following code in the click event of the show button. Now the
data stored in the XML file can be shown.
protected void Button2_Click(object sender, EventArgs e)
{
XmlDocument xmldoc =new XmlDocument();
xmldoc.Load(Server.MapPath("Employee.xml"));
XmlElement parentelement = xmldoc.CreateElement("Details");
XmlElement name = xmldoc.CreateElement("Name");
name.InnerText = TextBox1.Text;
XmlElement Emp_id = xmldoc.CreateElement("Emp_id");
Emp_id.InnerText = TextBox2.Text;
XmlElement Qualification = xmldoc.CreateElement("Qualification");
Qualification.InnerText = DropDownList1.SelectedItem.Text;
parentelement.AppendChild(name);
parentelement.AppendChild(Emp_id);
parentelement.AppendChild(Qualification);
xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("Employee.xml"));
BindDatalist();
}
Step 7: Run your application by pressing F5. The output is:
Step 8 : See your sample.xml file, it will include the data that I entered at the run
time like this:
<?xmlversion="1.0"encoding="utf-8"?>
<EmployeeInformation>
<Details>
21BCACC602 - Programming with ASP.NET Page 78 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
<Name>Richa</Name>
<Emp_id>1</Emp_id>
<Qualification>MCA</Qualification>
</Details>
</EmployeeInformation>
• Web Services (Introduction, HTTP, SOAP, UDDI, XML)
o A web service is an XML-based information exchange system that creates direct
interaction between the two applications over the internet or network in order
to exchange data or information.
o It enables us to communicate and exchange data or information between the
two different applications created in the same or different languages over the
internet or network.
o For example, if we use multiple software systems and we need to transfer data
from one application to another application then a web service is the best
source to accomplish this task.
o The software system that sends requests for data is called a service requester
whereas the software system that would process the request and provide the
data is called a service provider.
o A web service works between all types of applications software and it does not
matter if both the service requester software and service provider software are
written in different programming languages because web services use XML files
for data exchange and most software applications, however, interpret XML tags.
Components of Web Services
o The basic web service platform is XML + HTTP. Web service elements are –
1. SOAP – Simple Object Access Protocol
2. UDDI – Universal Description, Discovery and Integration
3. WSDL – Web Service Description Language
o With ASP.net, you do not have to write SOAP and WSDL documents. ASP.net
automatically creates SOAP and WSDL documents.
1. SOAP
o The HTTP protocol is the most used Internet protocol. SOAP is an XML-based
protocol to let applications exchange information over HTTP. Or, more simple:
SOAP is a protocol for accessing a Web Service.
o SOAP stands for Simple Object Access Protocol
o SOAP is a communication protocol
o SOAP is a format for sending messages
o SOAP is designed to communicate via Internet
o SOAP is platform independent
o SOAP is language independent
21BCACC602 - Programming with ASP.NET Page 79 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o SOAP is based on XML
o SOAP is simple and extensible
o SOAP allows you to get around firewalls
o SOAP is a W3C standard
2. WSDL:
o WSDL is an XML-based language for locating and describing Web services.
o WSDL stands for Web Services Description Language
o WSDL is based on XML
o WSDL is used to describe Web services
o WSDL is used to locate Web services
o WSDL is a W3C standard
3.UDDI:
o UDDI is a directory service where companies can register and search for Web
services.
o UDDI stands for Universal Description, Discovery and Integration
o UDDI is a directory for storing information about web services
o UDDI is a directory of web service interfaces described by WSDL
o UDDI communicates via SOAP
o UDDI is built into the Microsoft .NET platform
• Introduction to Web.config & Global.asax
o What is Web.Config File?
o A configuration file (web.config) is used to manage various settings that define
a website.
o The settings are stored in XML files that are separate from your application
code. In this way you can configure settings independently from your code.
o Generally a website contains a single Web.config file stored inside the
application root directory.
o However there can be many configuration files that manage settings at various
levels within an application.
o Usage of configuration file
o ASP.NET Configuration system is used to describe the properties and behaviors
of various aspects of ASP.NET applications. Configuration files help you to
manage the many settings related to your website. Each file is an XML file (with
the extension .config) that contains a set of configuration elements.
Configuration information is stored in XML-based text files.
o Benefits of XML-based Configuration files
o ASP.NET Configuration system is extensible and application specific
information can be stored and retrieved easily. It is human readable.
o You need not restart the web server when the settings are changed in
configuration file. ASP.NET automatically detects the changes and applies them
21BCACC602 - Programming with ASP.NET Page 80 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
to the running ASP.NET application.
o You can use any standard text editor or XML parser to create and edit ASP.NET
configuration files.
o What Web.config file contains?
o 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:
o Database connections
o Caching settings
o Session States
o Error Handling
o Security
o Configuration file looks like this
<configuration>
<connectionStrings>
<add name="myCon" connectionString="CONSTRING" />
</connectionStrings>
</configuration/>
o What is Global.asax file:
o global.asax allows us to write event handlers that react to global events in web
applications.
o How it gets called:
o Global.asax files are never called directly by the user, rather they are called
automatically in response to application events.
o Point to remember about global.asax:
o They do not contain any HTML or ASP.NET tags.
o Contain methods with specific predefined names.
o They defined methods for a single class, application class.
o They are optional, but a web application has no more than one global.asax file.
o How to add global.asax file:
o Select Website >>Add New Item (or Project >> Add New Item if you're using the
Visual Studio web project model) and choose the Global Application Class
template.
21BCACC602 - Programming with ASP.NET Page 81 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o After you have added the global.asax file, you will find that Visual Studio has
added Application Event handlers:
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
21BCACC602 - Programming with ASP.NET Page 82 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
}
</script>
o Purpose of these application event handlers: To reach and handle any
HttpApplication event.
o If you want to know about HttpApplication events, see the MSDN article.
o How these handler reach to HttpApplication Events
o global.asax file aren't attached in the same way as the event handlers for
ordinary control events
o Way to attach them is to use the recognized method name, i.e. for event handler
Application_OnEndRequest(), ASP.NET automatically calls this method when
the HttpApplication.EndRequest event occurs.
o What kind of application event global.asax can handle:
o Global.asax can handle 2 types of applications events
o 1) Events that occurs only under specific conditions, i.e. request / response
related events.
o Order in which application event handler executes;
Order Application Events What they do
1 Application_BeginRequest() This method is called at the start
of every request.
2 Application_AuthenticateRequest() This method is called just before
authentication is performed.
This is time and place where we
can write our own
authentication codes.
3 Application_AuthorizeRequest() After the user is authenticated
(identified), it's time to
determine the user's
permissions. Here we can assign
user with special privileges
4 Application_ResolveRequestCache() This method is commonly used
in conjunction with output
caching.
21BCACC602 - Programming with ASP.NET Page 83 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
5 Application_AcquireRequestState() This method is cal006Ced just
before session-specific
information is retrieved for the
client and used to populate the
Session collection.
6 Application_PreRequestHandlerExecute() This method is called before the
appropriate HTTP handler
executes the request.
7 Application_PostRequestHandlerExecute() This method is called just after
the request is handled.
8 Application_ReleaseRequestState() This method is called when the
session-specific information is
about to be serialized from the
Session collection so that it's
available for the next request.
9 Application_UpdateRequestCache() This method is called just before
information is added to the
output cache.
10 Application_EndRequest() This method is called at the end
of the request, just before the
objects are released and
reclaimed. It's a suitable point
for cleanup code.
2) Events that don't get fired with every request.
Order Application Events What they do
1 Application_Start() This method is invoked when the application first
starts up and the application domain is created.
This event handler is a useful place to provide
application-wide initialization code. For example, at
this point you might load and cache data that will
not change throughout the lifetime of an
application, such as navigation trees, static product
catalogs, and so on.
2 Session_Start() This method is invoked each time a new session
begins. This is often used to initialize user-specific
information.
3 Application_Error() This method is invoked whenever an unhandled
exception occurs in the application.
4 Session_End() This method is invoked whenever the user's session
ends. A session ends when your code explicitly
21BCACC602 - Programming with ASP.NET Page 84 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
releases it or when it times out after there have been no
more requests received within a given timeout period
(typically 20 minutes).
5 Application_End() This method is invoked just before an application ends.
The end of an application can occur because IIS is
being restarted or because the application is
transitioning to a new application domain in response
to updated files or the process recycling settings.
6 Application_Disposed() This method is invoked some time after the application
has been shut down and the .NET garbage collector is
about to reclaim the memory it occupies. This point is
too late to perform critical cleanup, but you can use it
as a last-ditch failsafe to verify that critical resources
are released.
• Tracing
o ASP.NET tracing enables you to view diagnostic information about a single
request for an ASP.NET page. ASP.NET tracing enables you to follow a page's
execution path, display diagnostic information at run time, and debug your
application. ASP.NET tracing can be integrated with system-level tracing to
provide multiple levels of tracing output in distributed and multi-tier
applications.
o There are two ways:
o Page Level Tracing
o Application Level Tracing
o Page Level Tracing
o We can control whether tracing is enabled or disabled for individual pages. If
tracing is enabled, when the page is requested, ASP.NET appends to the page a
series of tables containing execution details about the page request. Tracing is
disabled by default in an ASP.NET application.
o To enable Page Level Tracing follow the steps:
o i) Include Trace="true" in <%@ Page Title="" Language="C#"...%> directive, for
example:
o ii) Optionally, we can use TraceMode attribute in above <%@ Page Title=""
Language="C#"...%> directive, for example:
o
o SortByCategory: Set TraceMode to SortByTime to sort trace messages in the
order in which they are processed.
o SortByTime: Set TraceMode to SortByCategory to sort trace messages by the
categories.
o iii) Now press F5 to run the application, you will see the immediate trace record
21BCACC602 - Programming with ASP.NET Page 85 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
on an existing page that you have set Trace and TraceMode.
o Application Level Tracing
o Instead of enabling tracing for individual pages, you can enable it for your
entire application. In that case, every page in your application displays trace
information. Application tracing is useful when you are developing an
application because you can easily enable it and disable it without editing
individual pages. When your application is complete, you can turn off tracing
for all pages at once.
o To enable Application Level Tracing follow the steps:
o i) Delete your Page Level Tracking for better result.
o ii) Open the Web.config file and add the following information to it; if there is
not a Web.config file available then add a new one in the root.
o
• Authentication, Authorization
o Authentication and Authorization
o Authentication is the process for checking the identity of a user based on the
user’s credentials. Generally, user’s credentials are in the form of user ID and
password, and we check their credentials from database or equivalent
alternative, if it exists then user is a valid candidate for next process -
authorization.
o Authorization also known as “Permission Control” will come after
authentication. Authorization is the process of deciding what kind of resource a
user can access based on their identity and checking whether the authenticated
user has sufficient rights to access the requested resources. Typically a
resource can be an ASP.NET web page, media files (MP4, GIF, JPEG etc),
compressed file (ZIP, RAR) etc.
o ASP.NET default authentication Providers
o 1. Form Authentication
o Normally, form authentication is based on cookies, the authentication and
permission settings are stored in cookies.
o 2. Passport Authentication
o Passport authentication is a centralized authentication service provided by
Microsoft. The .NET Passport single sign-in service. When we use passport
authentication then user authentication in your application is managed by
Microsoft's passport service. Passport authentication uses encrypted cookies to
manage the authentication.
o How Password authentication works Users do not need to retype their sign-in
name and password when moving from site to site. Those .NET Passport–
enabled sites will issue a set of encrypted cookies in the .NET Passport central
servers' domain to facilitate silent and seamless sign-in across sites.
o 3. Windows Authentication
21BCACC602 - Programming with ASP.NET Page 86 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
o We use windows authentication when we are creating a web application for a
limited number of users who already have Windows account and this type of
authentication is quite useful in an intranet environment.
• Custom Error handling
o When a run-time or design-time error occurs in an application, ASP.NET shows
a default Yellowish-Red error page that gives a brief description of the error
along with some status code. If this page is viewed by the developer, then he
can analyse the actual reason by its status code, but if a user or anyone other
than the developer is viewing this error page, they won't get the actual idea of
why this error is coming. So to provide a friendly error message page we need
to set custom error in web.config.
o Some of the basic common errors with status codes are:
Error
Description
Code
400 Bad Request The request cannot be fulfilled due to bad syntax
Forbidden The request was a legal request, but the server is refusing to respond
403
to it
404 Not Found Page Not Found
Method not allowed A request was made of a page using a request method not
405
supported by that page
408 Timeout server time out
o When we are using custom error mode we have the following 3 options:
o OFF: ASP.NET uses its default error page for both local and remote users in case
of an error.
o ON: Custom error will be enabled for both local as well as remote client.
o REMOTE ONLY: The custom error page will be shown to a remote user only, the
local user will get the built-in error page.
21BCACC602 - Programming with ASP.NET Page 87 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
• How to Host a Website on IIS: Setup & Deploy Web Application
21BCACC602 - Programming with ASP.NET Page 88 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 89 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 90 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 91 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 92 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 93 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 94 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 95 of 96
ATMIYA University
Faculty of Science
Department of Computer Application & Department of Computer Science
21BCACC602 – Programming with ASP.NET Rev. No: 001/Dec-2023
21BCACC602 - Programming with ASP.NET Page 96 of 96