0% found this document useful (0 votes)
24 views77 pages

Net Notes

Uploaded by

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

Net Notes

Uploaded by

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

AVS

COLLEGE OF ARTS & SCIENCE


(AUTONOMOUS)
Attur Main Road, Ramalingapuram, Salem - 106. (Recognized
under section 2(f) & 12(B) of UGC Act 1956 and Accredited by
NAAC with 'A' Grade
[email protected]|www.avscollege.ac.in
Ph : 98426 29322, 94427 00205.

Study Material

Paper Name : .NET PROGRAMMING


Paper Code : 23UCSCC08

Batch : 2025 – 2026

Semester : EVEN SEMESTER


Staff In charge : S. ATHULYA RAJ M.Sc.,

PRINCIPAL
SYLLABUS

Semester: VI Course Code: 23 Hours/Week: 4 Credit: 3


COURSE TITLE: .Net Programming

Unit - I OVERVIEW OF .NET 12 Hours


Overview of .NET framework: Common Language Runtime (CLR), Framework Class
Library- C# Fundamentals: Primitive types and Variables – Operators - Conditional
statements -Looping statements – Creating and using Objects – Arrays – Stringoperations.
Unit - II INTRODUCTION TO ASP.NET 12 Hours
Introduction to ASP.NET - IDE-Languages supported Components Working with Web Forms
– Web form standard controls: Properties and its events – HTML controls -List Controls:
Properties and its events.
Unit - III RICH CONTROLS 12 Hours
Rich Controls: Properties and its events – validation controls: Properties and its events– File
Stream classes - File Modes – File Share – Reading and Writing to files – Creating, Moving,
Copying and Deletingfiles – File uploading.
Unit - IV ADO.NET 12 Hours
ADO.NET Overview – Database Connections – Commands – Data Reader - Data Adapter -
Data Sets - Data Controlsand its Properties – DataBinding
Unit - V GRID VIEW CONTROL 12 Hours
Grid View control: Deleting, editing, Sorting and Paging. XML classes – Web form to
manipulate XML files - Website Security - Authentication - Authorization – Creating aWeb
application.
UNIT I

Overview of .NET Framework

The .NET Framework is a comprehensive and consistent programming


model developed by Microsoft for building applications that have visually
stunning user experiences, seamless and secure communication, and the ability
to model a wide range of business processes. It is a platform that provides tools,
libraries, and runtime support to develop, run, and deploy applications on
Windows operating systems.
Introduction
The .NET Framework was introduced by Microsoft in the early 2000s as part of
its vision for the Next Generation Windows Services (NGWS).
It provides a managed environment for application execution, where the
runtime automatically handles memory management, security, and other
system-level services.
Unlike earlier development platforms that were language-specific, .NET
Framework supports multiple programming languages such as C#, Visual
Basic .NET, F#, and C++/CLI, allowing developers to choose the language
that best suits their project while maintaining full interoperability among them.
Main Components of .NET Framework

1. Common Language Runtime (CLR)

The CLR is the core runtime environment of the .NET Framework. It


acts as a virtual machine that manages the execution of .NET programs.
o It handles memory allocation and garbage collection, ensuring
efficient resource usage.
o It performs Just-In-Time (JIT) compilation, converting
Intermediate Language (IL) code into native machine code just
before execution.
o It also manages exception handling, threading, security, and
type safety, ensuring that programs run safely and efficiently.
Thus, the CLR provides a managed execution environment,
relieving developers from the complexity of manual memory and
resource management.
2. .NET Framework Class Library (FCL)

The FCL is a vast collection of reusable classes, interfaces, and value


types.
It provides a consistent, object-oriented way to access system
functionality such as file operations, database connectivity, networking,
collections, XML manipulation, and web development.
Developers can use these prebuilt classes to quickly build powerful
applications without writing low-level code.
3. Common Type System (CTS)

The CTS defines how data types are declared, used, and managed in the
runtime.
It ensures that objects written in different .NET languages can interact
seamlessly.
For example, an int in C# and an Integer in VB.NET are represented as
the same type under the CTS.
4. Common Language Specification (CLS)
The CLS defines a set of language features and rules that all .NET
languages must follow.
This guarantees language interoperability, meaning a class written in
C# can be inherited and used in VB.NET or any other CLS-compliant
language.
5. Assemblies

Assemblies are the building blocks of .NET applications.


An assembly contains the compiled code, metadata, and resources needed
to run the application.
Assemblies are stored as .dll (Dynamic Link Library) or .exe
(Executable) files and form the unit of versioning, deployment, and
security in .NET.
6. Metadata and Managed Code

Metadata provides detailed information about the program, such as


classes, methods, and data types.
Managed code refers to code that runs under the control of the CLR,
ensuring memory safety and security.
This is in contrast to unmanaged code, which executes directly on the
operating system without CLR supervision.
Languages Supported
The .NET Framework supports a variety of programming languages, including:
• C#
• VB.NET
• F#
• C++/CLI
• JScript.NET
All these languages compile their code into Microsoft Intermediate Language
(MSIL), which is then executed by the CLR.

Types of Applications Built Using .NET Framework


Developers can create a wide range of applications using .NET, such as:
• Console Applications
• Windows Forms Applications (GUI)
• Web Applications (ASP.NET)
• Web Services
• WPF (Windows Presentation Foundation) Applications
• Enterprise and Database Applications
• Distributed Applications

Key Features of .NET Framework


1. Cross-language Interoperability – Programs written in different .NET
languages can work together.
2. Automatic Memory Management – The CLR automatically performs
garbage collection.
3. Security – Provides built-in support for role-based security and code
access permissions.
4. Version Control – Supports side-by-side execution of multiple versions
of the same application.
5. Portability – Applications can be easily deployed on any Windows
machine with .NET installed.
6. Extensive Base Class Library – Offers a rich set of prebuilt functions
and classes.
7. Error Handling and Debugging Support – Provides structured
exception handling and powerful debugging tools.
8. Scalability and Performance – Optimized runtime and JIT compilation
ensure high performance.
Architecture of .NET Framework
+-------------------------------------------------------+
| Application Programs (C#, VB.NET, etc.) |
+-------------------------------------------------------+
| .NET Framework Class Library (FCL) |
+-------------------------------------------------------+
| Common Language Runtime (CLR) |
+-------------------------------------------------------+
| Operating System (Windows) |
+-------------------------------------------------------+

Advantages of .NET Framework


• Simplifies application development through a unified programming
model.
• Reduces development time with reusable code and components.
• Ensures application reliability and security.
• Supports modern application development like web, desktop, and
distributed systems.
• Provides backward compatibility with earlier versions of Windows.

Common Language Runtime (CLR)


The Common Language Runtime (CLR) is the core component of the
.NET Framework.
It is often called the heart of .NET architecture because it provides the
environment in which all .NET programs execute.
The CLR is responsible for managing the execution of .NET applications,
including memory management, security, exception handling, and more.
It acts like a virtual machine (similar to the Java Virtual Machine for Java),
providing a managed execution environment for .NET code.
Definition
The Common Language Runtime (CLR) is the execution engine for .NET
applications that converts Intermediate Language (IL) code into native machine
code and manages the execution of that code at runtime.
Role of CLR in .NET
When a program written in any .NET language (like C#, VB.NET, or F#) is
compiled, it is not converted directly into machine code.
Instead, it is compiled into an Intermediate Language (IL) code.
When the program is executed, the CLR takes this IL code and uses a Just-In-
Time (JIT) Compiler to convert it into native machine code for execution.
Thus, the CLR provides services that make the execution of .NET applications
safe, efficient, and language-independent.
Key Functions of CLR
1. Just-In-Time (JIT) Compilation
o Converts Intermediate Language (IL) code into native machine
code at runtime.
o Improves performance by optimizing the execution of code.
2. Memory Management
o CLR automatically allocates and deallocates memory for objects.
o Uses Garbage Collection (GC) to free memory occupied by unused
objects, preventing memory leaks.
3. Exception Handling
o Provides a structured and uniform mechanism for handling runtime
errors and exceptions across all .NET languages.
4. Security Management
o Enforces code access security (CAS) and role-based security to
protect the system from malicious code.
o Ensures that only authorized code can access certain resources.
5. Thread Management
o Handles multithreading, allowing multiple tasks to run
simultaneously.
o Manages synchronization between threads.
6. Code Verification
o Before executing, CLR verifies the IL code to ensure type safety
and code security, preventing unsafe operations.
7. Interoperability
o Allows .NET applications to interact with unmanaged code (such
as COM components or native C/C++ libraries).
8. Debugging and Profiling Support
o Provides tools and APIs that help developers debug and monitor
applications effectively.

CLR Execution Process


Source Code (C#, VB.NET, etc.)

Compiler (Language Compiler)

Intermediate Language (IL) Code + Metadata

Common Language Runtime (CLR)
↓ JIT Compiler converts IL → Machine Code

Program Executes

Features of CLR
• Language Interoperability
• Automatic Memory Management
• Code Access Security
• Type Safety
• Cross-language Exception Handling
• Enhanced Performance through JIT
• Platform Independence (within Windows ecosystem)
Advantages of CLR
• Simplifies application development by handling low-level system
operations.
• Ensures better security and stability.
• Provides efficient memory management and garbage collection.
• Allows programs written in different languages to work together
seamlessly.
• Reduces runtime errors by verifying code before execution.

FIG : CLR

Framework Class Library (FCL)


Introduction
The Framework Class Library (FCL) is an integral part of the .NET Framework.
It is a comprehensive collection of reusable classes, interfaces, and value types that are tightly
integrated with the Common Language Runtime (CLR).
The FCL provides ready-to-use components that help developers quickly build applications
without writing code from scratch.
It serves as the foundation of application development in .NET, supporting tasks such as file
handling, data access, database connectivity, input/output operations, XML manipulation,
web development, and more.
Definition
The Framework Class Library (FCL) is a set of object-oriented class libraries that provide
reusable code for common programming tasks such as file reading and writing, database
interaction, XML processing, string manipulation, and graphical user interface design.
Main Features of FCL
1. Object-Oriented Design
o All FCL components are based on classes and objects, making it easy to
understand and extend.
2. Language Interoperability
o The FCL is common for all .NET languages (C#, VB.NET, F#, etc.), ensuring
code reuse across languages.
3. Extensive Library
o It provides thousands of prebuilt classes and namespaces for almost every task
in application development.
4. Consistency
o Offers a consistent programming interface, reducing complexity and errors in
code.
5. Base Class Library (BCL)
o The BCL is a subset of FCL and contains the most fundamental classes (e.g.,
System, System.IO, System.Collections, System.Threading, etc.).
6. Integration with CLR
o The FCL works closely with the CLR to provide managed code execution and
runtime services.

Functions of the Framework Class Library


The FCL provides classes for the following tasks:

Category Description / Example Namespaces

System Classes Core data types, exceptions, arrays, strings (System, System.Text)
Category Description / Example Namespaces

Managing lists, queues, stacks, and dictionaries


Collections
(System.Collections, System.Collections.Generic)

Input/Output File and stream handling (System.IO)

Data Access
Database connectivity (System.Data, System.Data.SqlClient)
(ADO.NET)

XML Processing Reading and writing XML documents (System.Xml)

Web requests and socket programming (System.Net,


Networking
System.Net.Sockets)

Web Development Building web applications and services (System.Web,


(ASP.NET) System.Web.UI)

Windows Forms Desktop application interfaces (System.Windows.Forms)

Threading Managing multiple threads of execution (System.Threading)

Security Authentication, encryption, and permissions (System.Security)

Architecture of FCL
+--------------------------------------------------------------+
| Application Programs (C#, VB.NET, etc.) |
+--------------------------------------------------------------+
| Framework Class Library (FCL) |
| - System |
| - System.IO |
| - System.Data |
| - System.Web |
| - System.Xml |
| - System.Windows.Forms |
| - System.Threading |
+--------------------------------------------------------------+
| Common Language Runtime (CLR) |
+--------------------------------------------------------------+
| Operating System (Windows) |
+--------------------------------------------------------------+

Relationship between FCL and BCL

Aspect Base Class Library (BCL) Framework Class Library (FCL)

Core subset of FCL that contains Complete collection of libraries


Definition
essential system classes available in .NET

Limited (basic data types, I/O, Broad (includes web, data, XML,
Scope
collections, etc.) GUI, etc.)

Example System, System.IO, System.Web, System.Data,


Namespaces System.Collections System.Windows.Forms

Superset including BCL and other


Dependency Part of FCL
libraries

Advantages of FCL
• Reduces development time through reusable components.
• Provides consistent and standard APIs for different applications.
• Enhances productivity by offering tested and optimized classes.
• Encourages code reusability and maintenance.
• Supports language independence and type safety.

Primitive Types and Variables


Primitive types are the basic data types in C#. They are defined in the System namespace
and are part of the .NET Framework Class Library (FCL).They store simple values like
numbers, characters, or true/false values.
Category Type Description

int, short, long, byte, sbyte, ushort, uint,


Integer Store whole numbers
ulong

Floating-
float, double, decimal Store fractional numbers
point

Stores a single Unicode


Character char
character

Boolean bool Stores true or false

Others string, object Special reference types

Example:
int age = 25;
float price = 99.99f;
char grade = 'A';
bool isPassed = true;
string name = "Athulya";

Variables
A variable is a named storage location in memory that holds a value.
Syntax:
data_type variable_name = value;
Example:
int age = 21;
float temperature = 36.6f;
string name = "Athulya";
• All variables must be declared before use.
• Variables are case-sensitive.
• C# is strongly typed, so each variable has a specific type.
2. Operators
C# supports several types of operators:

Type Examples Description

Arithmetic +, -, *, /, % Perform basic math

Relational ==, !=, >, <, >=, <= Compare values

Logical &&, ` Logical AND

Assignment =, +=, -=, *=, /= Assign or modify values

Increment/Decrement ++, -- Increase or decrease values

Conditional (Ternary) ?: Shorthand for if-else

Example:
Arithmetic Operators
int a = 10, b = 3;
Console.WriteLine(a + b); // 13
Console.WriteLine(a % b); // 1

Relational Operators
Console.WriteLine(a > b); // true
Logical Operators
bool x = true, y = false;
Console.WriteLine(x && y); // false
Assignment Operators
int num = 10;
num += 5; // num = num + 5
Console.WriteLine(num); // 15
Increment/Decrement
int i = 5;
i++; // i = 6
Ternary (Conditional) Operator
int marks = 80;
string result = (marks >= 50) ? "Pass" : "Fail";
Console.WriteLine(result);

Conditional Statements
Conditional statements allow your program to make decisions and execute code selectively.
a) if statement
Executes code only if a condition is true.
if (score > 50)
Console.WriteLine("Passed!");
b) if...else
Executes one block if condition is true, another if false.
if (num % 2 == 0)
Console.WriteLine("Even");
else
Console.WriteLine("Odd");

c) else if Ladder
Used for multiple conditions.
if (marks >= 90)
Console.WriteLine("A Grade");
else if (marks >= 75)
Console.WriteLine("B Grade");
else
Console.WriteLine("C Grade");
d) switch statement
Best when there are multiple discrete values to check.
int day = 3;
switch (day)
{
case 1: Console.WriteLine("Sunday"); break;
case 2: Console.WriteLine("Monday"); break;
case 3: Console.WriteLine("Tuesday"); break;
default: Console.WriteLine("Invalid day"); break;
}

Looping Statements
Loops execute a block repeatedly until a condition becomes false.
a) for loop
Used when number of iterations is known.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}

b) while loop
Checks the condition first, then runs the loop.
int i = 1;
while (i <= 5)
{
Console.WriteLine(i);
i++;
}
c) do...while loop
Executes the loop at least once, even if condition is false.
int i = 1;
do
{
Console.WriteLine(i);
i++;
} while (i <= 5);
d) foreach loop
Used for iterating over arrays, lists, or collections.
string[] names = {"Asha", "Binu", "Chitra"};
foreach (string n in names)
{
Console.WriteLine(n);
}

Creating and Using Objects


An object is an instance of a class.
A class is a blueprint or template.
Example:
class Student
{
public string Name;
public int Age;

public void Display()


{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}

Student s1 = new Student(); // Creating object


s1.Name = "Athulya";
s1.Age = 20;
s1.Display();
Creating Object:
Student s1 = new Student(); // Create object
s1.Name = "Athulya";
s1.Age = 20;
s1.Display();
Explanation:
• Student is the class.
• s1 is the object.
• new keyword dynamically allocates memory for the object.

Arrays
An array stores multiple values of the same data type in contiguous memory.
Declaration and Initialization:
int[] numbers = {10, 20, 30, 40, 50};
Accessing Elements:
Console.WriteLine(numbers[0]); // Output: 10
Traversing using for loop:
for(int i = 0; i < numbers.Length; i++)
Console.WriteLine(numbers[i]);
Traversing using foreach:
foreach(int n in numbers)
Console.WriteLine(n);
Multidimensional Array
A multi-dimensional array in C# is an array that contains multiple rows and columns, forming
a table-like (matrix) structure.
It can be two-dimensional, three-dimensional, or even more, depending on the number of
indices used.
Example:
int[,] matrix = { {1,2}, {3,4} };
Console.WriteLine(matrix[0,1]); // Output: 2

String Operations
A string is a sequence of characters enclosed in double quotes (" ") and the sequences of
characters defined by System.String.
Strings in C# are immutable, meaning once created, they cannot be changed.
Example:
string str1 = "Hello";
string str2 = "World";

Console.WriteLine(str1 + " " + str2); // Concatenation


Console.WriteLine(str1.Length); // Length
Console.WriteLine(str1.ToUpper()); // Uppercase
Console.WriteLine(str1.Replace("H", "J")); // Replace
Console.WriteLine(str1.Contains("lo")); // True
Console.WriteLine(str1.Substring(1,3)); // "ell"

String Concatenation
Concatenation is the process of joining two or more strings together to form a single
string.
In C#, you can concatenate strings in several ways — using the + operator, String.Concat(),
String.Join()

string fullName = "Athulya" + " " + "Raj";


String Interpolation
String Interpolation in C# is a feature that allows you to insert variables, expressions, or
values directly inside a string using curly braces {}, preceded by the $ symbol.
It provides a cleaner, easier, and more readable way to build formatted strings compared to
concatenation (+) or String.Format().

int age = 21;


Console.WriteLine($"Name: {name}, Age: {age}");

IMPORTANT QUESTIONS
1 MARK
1. .NET Framework is developed by:
a) Sun Microsystems
b) Microsoft
c) Oracle
d) IBM

2. .NET Framework is mainly used for developing:


a) Hardware
b) Web and Windows applications
c) Operating Systems
d) Databases

3. Which of the following is the heart of the .NET Framework?


a) Common Type System
b) Common Language Runtime (CLR)
c) Framework Class Library
d) Visual Studio

4. The extension of a .NET executable file is:


a) .exe
b) .java
c) .dllx
d) .html
5. Which component of .NET provides reusable classes and interfaces?
a) Common Language Runtime
b) Framework Class Library (FCL)
c) Common Type System
d) ASP.NET

6. The .NET Framework supports interoperability among languages using:


a) JIT Compilation
b) Common Language Specification (CLS)
c) CLR
d) CTS

7. The main function of CLR is to:


a) Store data
b) Execute code and manage memory
c) Format strings
d) Debug applications

8. Which of the following is NOT a feature of .NET Framework?


a) Garbage collection
b) Memory management
c) Platform independence
d) Exception handling

9. CLR stands for:


a) Common Language Routine
b) Common Language Runtime
c) Common Library Runtime
d) Common Logical Runtime

10. The CLR converts MSIL code into machine code using:
a) Compiler
b) Just-In-Time Compiler (JIT)
c) Linker
d) Assembler

11. CLR provides which of the following services?


a) Memory Management
b) Security
c) Exception Handling
d) All of the above

12. The process of automatic memory management by CLR is called:


a) Compilation
b) Garbage Collection
c) Type Safety
d) Serialization

13. FCL stands for:


a) Framework Code Library
b) Framework Class Library
c) Functional Class Library
d) File Control Library

14. FCL contains:


a) Only Data Types
b) Only Classes
c) Classes, Interfaces, and Namespaces
d) Only Functions

15. Which namespace is the root of all namespaces in .NET?


a) System
b) Microsoft
c) Windows
d) CSharp

16. Which of the following is a value type in C#?


a) String
b) Object
c) int
d) Array

17. The default v alue of a bool variable in C# is:


a) 1
b) 0
c) false
d) true
18. Which keyword can automatically determine the type of variable?
a) var
b) dim
c) int
d) declare

19. C# is a:
a) Weakly typed language
b) Dynamically typed language
c) Strongly typed language
d) Unstructured language

20. Which operator is used for addition in C#?


a) *
b) /
c) +
d) %

21. Which operator is known as the conditional (ternary) operator?


a) ? :
b) &&
c) ||
d) ==

22. The logical AND operator in C# is:


a) ||
b) &&
c) ==
d) !

23. Which operator is used to compare two values?


a) =
b) ==
c) +=
d) :=

24. Which statement is used for decision-making in C#?


a) for
b) if
c) while
d) foreach

25. Which statement is best suited for multiple constant conditions?


a) if-else
b) switch
c) do-while
d) continue

26. In a switch statement, each case should end with:


a) return
b) end
c) break
d) stop

27. Which loop is executed at least once even if condition is false?


a) for
b) while
c) do...while
d) foreach

28. Which loop is used when number of iterations is known?


a) for
b) while
c) do...while
d) goto

29. Which keyword is used to exit a loop immediately?


a) stop
b) break
c) end
d) quit

30. Which loop is used to iterate through a collection or array?


a) for
b) while
c) do
d) foreach
31. An object is:
a) A blueprint
b) A function
c) An instance of a class
d) A namespace

32. Which keyword is used to create an object?


a) make
b) create
c) new
d) this

33. A class in C# is a:
a) Function
b) Variable
c) User-defined data type
d) Namespace

34. An array stores:


a) Heterogeneous data
b) Multiple values of same data type
c) Only characters
d) Only objects

35. The first index of an array in C# is:


a) 1
b) -1
c) 0
d) 2

36. Which property gives the size of an array?


a) count
b) Length
c) size
d) num

37. A 2D array is also known as a:


a) Matrix
b) List
c) Tuple
d) Stack

38. Strings in C# are:


a) Mutable
b) Immutable
c) Dynamic
d) Non-primitive

39. Which operator is used for string concatenation?


a) &
b) %
c) *
d) +

40. Which method converts a string to uppercase?


a) toUpperCase()
b) upper()
c) ToUpper()
d) Uppercase()

41. Which method finds the length of a string?


a) Length
b) Size()
c) Count()
d) Length()

42. Which symbol is used in string interpolation?


a) &
b) #
c) %
d) $

43. Which method replaces characters in a string?


a) Change()
b) Modify()
c) Replace()
d) Alter()
5 MARK QUESTIONS

1. Explain the architecture of the .NET Framework.


2. Describe the role and features of the Common Language Runtime (CLR).
3. What is the Framework Class Library (FCL)? Explain its components.
4. Explain primitive data types and variables in C#.
5. Explain the different operators used in C#.

10 MARK QUESTIONS

1. Differentiate between conditional and looping statements with examples.


2. Explain the steps to create and use objects in C#.
3. Explain arrays in C# and their types.
4. Explain string operations in C# with examples.
5. Explain the difference between concatenation and interpolation with examples.

UNIT II

Introduction to ASP.NET

ASP.NET stands for Active Server Pages .NET.


It is a web application framework developed by Microsoft for building dynamic web pages,
web applications, and web services in early 2002,as a part of the .NET Framework
It runs on IIS(internet information servicesin microsoft’s web server
ASP.NET allows developers to create web applications using .NET-supported languages such
as C# or VB.NET.
ASP.NET is a powerful, secure, and flexible web framework used for building modern web
applications and services.
It simplifies development through rich libraries, server controls, event-driven programming,
and integration with databases — making it a backbone for Microsoft’s web technology
ecosystem.
Features of ASP.NET
1. Server-Side Technology:
o Code executes on the server, not the client.
o Generates dynamic HTML that is sent to the browser.
2. Language Independence:
o Supports multiple languages like C#, VB.NET, F#, etc.
3. Rich Framework Library:
o Provides built-in classes, controls, and functions for web development.
4. State Management:
o Supports mechanisms like Session, Cookies, ViewState, and Application to
maintain user data.
5. Security:
o Built-in authentication (Forms, Windows, etc.) and authorization features.
6. Scalability and Performance:
o Compiled code and caching improve performance and scalability.
7. Event-driven Programming Model:
o Similar to Windows Forms – supports events like button click, page load, etc.
8. Integration with ADO.NET:
o Allows database connectivity using SQL Server, Oracle, etc.

ASP.NET Architecture
ASP.NET is built on top of the .NET Framework and follows a layered architecture:
1. Browser / Client
o Sends HTTP requests to the web server.
2. Internet Information Services (IIS):
o Web server that hosts and manages ASP.NET applications.
3. ASP.NET Runtime:
o Converts code into MSIL and executes it using the CLR.
4. Framework Class Library (FCL):
o Provides reusable classes and components.
5. Database Server:
o Stores application data (e.g., SQL Server).
ASP.NET Components
1. Web Forms:
o Used for developing event-driven web applications.
o Files with extension .aspx.
2. MVC (Model-View-Controller):
o Provides a clean separation between business logic, UI, and data.
o Extension: .cshtml.
3. Web API:
o Used for creating RESTful services.
4. Razor Pages:
o Simplified web page model introduced in ASP.NET Core.
ASP.NET Page Life Cycle
1. Page Request

2. Start

3. Initialization

4. Load

5. Validation

6. Event Handling

7. Rendering

8. Unload
Each phase allows developers to write code that executes at a specific time.

Advantages of ASP.NET

Advantage Description

Fast Performance Compiled code runs faster than interpreted scripts.

Code Reusability Supports components and user controls.

Security Built-in authentication and authorization.

Easy Maintenance Code-behind model separates design and logic.

Cross-language support Multiple .NET languages supported.

Rich Toolbox Visual Studio provides drag-and-drop controls.


ASP.NET File Extensions

File Type Extension Description

Web Form .aspx Contains HTML and server-side controls

Code-behind file .cs / .vb Contains C# or VB.NET logic

Configuration file web.config Stores application settings

Master Page .master Used for consistent page layouts

User Control .ascx Reusable web component

Difference Between ASP and ASP.NET

ASP (Classic ASP) ASP.NET

Uses interpreted VBScript Uses compiled .NET languages (C#, VB.NET)

No object-oriented support Fully object-oriented

Limited error handling Strong error handling

Manual memory management Automatic via CLR

HTML and code mixed Code-behind model separates design and logic

Integrated Development Environment (IDE)

An IDE is a software application that provides tools to design, develop, debug, and deploy
ASP.NET applications efficiently. Common IDE for ASP.NET is Microsoft Visual Studio
Features of Visual Studio IDE:
1. Code Editor (C#, VB.NET, HTML, CSS, JavaScript)
2. Toolbox with Web Controls
3. Solution Explorer (Project management)
4. Property Window (to modify control properties)
5. Debugger (to identify and fix errors)
6. Designer View (Drag and drop interface)
7. Integration with IIS and SQL Server

Languages Supported by ASP.NET


ASP.NET supports all languages compatible with the .NET Framework.
Commonly used languages:

Language Description

C# (C Sharp) Object-oriented, modern, widely used

VB.NET Derived from Visual Basic

JScript.NET Similar to JavaScript

J# Java-like syntax

F# Functional programming language

All these languages compile into MSIL (Microsoft Intermediate Language) and run on the
CLR (Common Language Runtime).
Components of ASP.NET
ASP.NET components are the building blocks used to create dynamic web applications.

Component Description

Web Forms Used to design user interfaces using drag-and-drop controls

Web Services Allow data exchange between applications over the internet

Master Pages Provide consistent layout for all pages

User Controls Reusable components similar to mini web pages

Global.asax Defines global application events

Web.config Configuration file (security, connection strings, etc.)

Assemblies (.dll) Contain compiled reusable classes

ADO.NET Components Used for database connectivity


Working with Web Forms

A Web Form is an ASP.NET page with the extension .aspx that allows you to create
dynamic, data-driven web applications.
Example :
Home.aspx
Structure of a Web Form:

1. HTML Section (Frontend UI)


Contains the design layout.
2. Code-behind File (.cs or .vb)
Contains server-side logic.
Example:
<asp:Button ID="btnClick" runat="server" Text="Click Me" OnClick="btnClick_Click" />
protected void btnClick_Click(object sender, EventArgs e)
{
lblMessage.Text = "Hello ASP.NET!";
}

Web Form Standard Controls


Standard controls are server-side controls that perform basic input/output operations.
They are prefixed with <asp: and require runat="server".

Common Web Form Controls:

Control Description

Label Displays text on a web page

TextBox Accepts user input

Button Triggers actions/events

CheckBox Allows selection of true/false

RadioButton Allows single selection from group

Image Displays images

HyperLink Redirects to another page

Panel Groups multiple controls

Properties and Events of Standard Controls

Control Important Properties Common Events

Label Text, ForeColor, Font, Visible (No events)

TextBox Text, MaxLength, ReadOnly, TextMode TextChanged

Button Text, Enabled, CommandName Click, Command

CheckBox Checked, Text, Enabled CheckedChanged

RadioButton Checked, GroupName, Text CheckedChanged


Control Important Properties Common Events

Image ImageUrl, Height, Width (No events)

HyperLink NavigateUrl, Text, Target (No events)

HTML Controls
HTML Controls are standard HTML elements (like <input>, <button>, etc.) that can be
converted into server controls using the attribute runat="server".
Example:
<input type="text" id="txtName" runat="server" />
<input type="submit" id="btnSubmit" runat="server" value="Submit" />
Difference Between HTML and Web Controls:

HTML Controls Web Controls

Based on HTML tags Based on .NET Framework classes

Limited functionality Rich functionality

Browser-dependent Browser-independent

Example: <input> Example: <asp:TextBox>

List Controls: Properties and Events


Definition:
List controls display lists of items such as names, categories, or data from a database.
Common List Controls:
1. DropDownList
2. ListBox
3. CheckBoxList
4. RadioButtonList
5. BulletedList
Control Description Common Properties Common Events

Displays a dropdown Items, SelectedItem,


DropDownList SelectedIndexChanged
list SelectedValue

Displays multiple Items, SelectionMode,


ListBox SelectedIndexChanged
selectable items Rows

CheckBoxList List of checkboxes Items, RepeatColumns SelectedIndexChanged

RadioButtonList List of radio buttons Items, RepeatDirection SelectedIndexChanged

Displays items as a BulletStyle,


BulletedList Click
bullet list DisplayMode

Example:
<asp:DropDownList ID="ddlCity" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">
<asp:ListItem>Chennai</asp:ListItem>
<asp:ListItem>Coimbatore</asp:ListItem>
<asp:ListItem>Madurai</asp:ListItem>
</asp:DropDownList>
protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)
{
lblResult.Text = "You selected: " + ddlCity.SelectedItem.Text;
}

IMPORTANT QUESTIONS

1 MARK
1. ASP.NET is mainly used for developing:
a) Desktop Applications
b) Mobile Applications
c) Web Applications
d) Database Applications

2. ASP.NET is a part of which framework?


a) Java Framework
b) .NET Framework
c) Spring Framework
d) PHP Framework

3. ASP.NET pages have which file extension?


a) .html
b) .aspx
c) .cs
d) .exe

4. ASP.NET applications are executed on which server?


a) Apache
b) Tomcat
c) IIS
d) XAMPP

5. Which of the following is true about ASP.NET?


a) It is client-side scripting
b) It is server-side scripting
c) It is both client and server side
d) It is a desktop application language

6. The most commonly used IDE for ASP.NET is:


a) Eclipse
b) NetBeans
c) Visual Studio
d) PyCharm

7. Which window in Visual Studio is used to manage project files?


a) Properties Window
b) Solution Explorer
c) Server Explorer
d) Output Window
8. Which feature of Visual Studio allows drag-and-drop web design?
a) Code View
b) Design View
c) Object Browser
d) Debugger

9. Which key is used to run a web application in Visual Studio?


a) F1
b) F5
c) Ctrl + S
d) Shift + F9

10. Which window is used to modify the appearance and behavior of a control?
a) Solution Explorer
b) Properties Window
c) Server Explorer
d) Toolbox

11. Which of the following is NOT a language supported by ASP.NET?


a) C#
b) VB.NET
c) Python
d) JScript.NET

12. All .NET languages compile into which intermediate code?


a) Bytecode
b) MSIL
c) Java code
d) Native code

13. Which runtime executes ASP.NET applications?


a) JVM
b) CLR
c) JRE
d) Python Runtime

14. Which ASP.NET file stores configuration settings?


a) App.config
b) Global.asax
c) Web.config
d) Settings.json
15. Which ASP.NET component provides reusable layout for web pages?
a) Web Services
b) Master Pages
c) User Controls
d) Themes

16. Which file contains application-level event handlers?


a) Web.config
b) Global.asax
c) Default.aspx
d) AppSettings.xml

17. Which attribute makes an HTML control a server control?


a) id
b) runat="server"
c) name
d) type

18. Which control is used to accept input from the user?


a) Label
b) TextBox
c) HyperLink
d) Image

19. Which event of a Button control executes when it is clicked?


a) Load
b) TextChanged
c) Click
d) Submit
20. Which List control allows multiple selections?
a) DropDownList
b) ListBox
c) RadioButtonList
d) BulletedList

5 MARK QUESTIONS

1. Explain the features and advantages of ASP.NET.


2. Describe the architecture and components of ASP.NET.
3. Explain the role of Visual Studio IDE in ASP.NET development.
4. What are Web Forms? Explain their structure and use.
5. Write short notes on Standard Web Controls and their events.

10 MARK QUESTIONS

1. Explain in detail the ASP.NET architecture with a neat diagram.


2. Explain in detail the ASP.NET IDE, supported languages, and its components.
3. Explain Web Forms in ASP.NET. Discuss their standard controls, properties, and
events with examples.
4. Differentiate between HTML controls and Web server controls with examples.
5. Explain List Controls in ASP.NET with properties, events, and examples.

UNIT III
Introduction to Rich Controls
Rich Controls in ASP.NET are advanced web server controls that provide enhanced
functionality compared to standard controls.
They allow developers to display data dynamically, collect input, and improve user
interaction with minimal coding.
Examples of Rich Controls:
1. Calendar
2. AdRotator
3. FileUpload
4. Wizard
5. TreeView
6. Menu
7. MultiView and View

Commonly Used Rich Controls


(a) Calendar Control
Purpose:
Used to display a calendar and allow users to select dates.
Syntax:
<asp:Calendar ID="Calendar1" runat="server"
OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
Important Properties:

Property Description

SelectedDate Gets or sets the selected date

VisibleDate Gets or sets the month currently visible

DayStyle Sets style for all days

NextPrevFormat Sets format for navigation buttons

Important Events:
Event Description

SelectionChanged Triggered when the user selects a date

VisibleMonthChanged Triggered when the visible month changes

Example:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
lblDate.Text = "Selected Date: " + Calendar1.SelectedDate.ToShortDateString();
}

(b) AdRotator Control


Purpose:
Used to display a sequence of advertisements (images with links) from an XML file.
Syntax:
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/Ads.xml" />
Important Properties:

Property Description

AdvertisementFile Path to the XML file containing ads

KeywordFilter Displays ads matching specific keywords

Target Sets where the ad should open (_blank, _self)

Important Events:

Event Description

AdCreated Occurs when an ad is created or displayed

Example XML File (Ads.xml):


<Advertisements>
<Ad>
<ImageUrl>~/Images/ad1.jpg</ImageUrl>
<NavigateUrl>https://www.microsoft.com</NavigateUrl>
<AlternateText>Microsoft Ad</AlternateText>
</Ad>
</Advertisements>
(c) FileUpload Control
Purpose:
Allows users to browse and upload files to the server.
Syntax:
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
Important Properties:

Property Description

FileName Gets the name of the file to be uploaded

HasFile Checks whether a file is selected

PostedFile Returns the uploaded file object

Important Event:

Event Description

Click (from Button) Handles the upload process

Example:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName));
lblMsg.Text = "File uploaded successfully!";
}
else
lblMsg.Text = "Please select a file.";
}

(d) Wizard Control


Purpose:
Used to create step-by-step user input forms (like registration wizards).
Syntax:
<asp:Wizard ID="Wizard1" runat="server">
<WizardSteps>
<asp:WizardStep Title="Step 1">Enter Name:</asp:WizardStep>
<asp:WizardStep Title="Step 2">Enter Email:</asp:WizardStep>
</WizardSteps>
</asp:Wizard>
Important Properties:

Property Description

ActiveStepIndex Index of the current step

WizardSteps Collection of all steps

FinishCompleteButtonText Text for finish button

Important Events:

Event Description

NextButtonClick Occurs when the Next button is clicked

FinishButtonClick Occurs when the Finish button is clicked

(e) TreeView Control


Purpose:
Displays hierarchical data (like folders and files) in a tree structure.

Syntax:
<asp:TreeView ID="TreeView1" runat="server">
<Nodes>
<asp:TreeNode Text="Fruits">
<asp:TreeNode Text="Apple" />
<asp:TreeNode Text="Mango" />
</asp:TreeNode>
</Nodes>
</asp:TreeView>
Important Properties:

Property Description

Nodes Collection of tree nodes

SelectedNode Currently selected node

ExpandDepth Number of levels to expand

Important Events:

Event Description

SelectedNodeChanged Triggered when a node is selected

(f) Menu Control


Purpose:
Displays a hierarchical menu bar for navigation.
Syntax:
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
<Items>
<asp:MenuItem Text="Home" NavigateUrl="~/Home.aspx" />
<asp:MenuItem Text="About" NavigateUrl="~/About.aspx" />
</Items>
</asp:Menu>

Important Properties:
Property Description

Items Represents menu items

Orientation Horizontal or Vertical layout

StaticDisplayLevels Number of menu levels visible

Important Event:

Event Description

MenuItemClick Occurs when a menu item is clicked

(g) MultiView and View Controls


Purpose:
Used to show multiple views within a single page.
Syntax:
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">View 1 Content</asp:View>
<asp:View ID="View2" runat="server">View 2 Content</asp:View>
</asp:MultiView>
Important Properties:

Property Description

ActiveViewIndex Sets or gets the active view index

Views Collection of all views

Important Events:

Event Description

ActiveViewChanged Occurs when the active view changes

Example:
protected void btnNext_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 1; // Switch to next view
}

Validation Controls
Validation controls in ASP.NET are used to validate user input on a web form before it is
submitted to the server.
They ensure that the data entered by the user meets the required criteria such as format,
range, and presence.

Types of Validation Controls

Important
Validation Control Description Common Properties
Events

Ensures that a
ControlToValidate,
RequiredFieldValidator field is not left ServerValidate
ErrorMessage, Display
empty

Compares input
in one control ControlToValidate,
CompareValidator with another ControlToCompare, ServerValidate
control or a Operator, Type
fixed value

Ensures that
input value falls MinimumValue,
RangeValidator ServerValidate
within a MaximumValue, Type
specified range

Ensures input
matches a
ValidationExpression,
RegularExpressionValidator pattern (like ServerValidate
ErrorMessage
email or phone
number)

Allows user-
ControlToValidate,
CustomValidator defined ServerValidate
ClientValidationFunction
validation logic

Displays all ShowMessageBox,


ValidationSummary —
validation errors ShowSummary
Important
Validation Control Description Common Properties
Events

together in one
place

Example: Using Validation Controls


<form runat="server">
Name: <asp:TextBox ID="txtName" runat="server" />
<asp:RequiredFieldValidator ID="reqName" runat="server"
ControlToValidate="txtName" ErrorMessage="Name is required!" ForeColor="Red" />

Age: <asp:TextBox ID="txtAge" runat="server" />


<asp:RangeValidator ID="rangeAge" runat="server"
ControlToValidate="txtAge" MinimumValue="18" MaximumValue="60"
Type="Integer" ErrorMessage="Age must be between 18 and 60" ForeColor="Red" />

Email: <asp:TextBox ID="txtEmail" runat="server" />


<asp:RegularExpressionValidator ID="regexEmail" runat="server"
ControlToValidate="txtEmail"
ValidationExpression="\w+@\w+\.\w+"
ErrorMessage="Invalid email format" ForeColor="Red" />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" />


</form>

Client-Side vs Server-Side Validation


Type Executed On Example

Client-Side Validation Browser JavaScript-based (faster)

Server-Side Validation Server Occurs after form submission

File Stream Classes (System.IO Namespace)


File Stream classes in C# provide a way to read and write data to files.
They are part of the System.IO namespace.

Common File Stream Classes

Class Description

FileStream Used for reading/writing bytes to files

StreamReader Used for reading characters from a file

StreamWriter Used for writing characters to a file

BinaryReader Reads binary data

BinaryWriter Writes binary data

FileInfo Provides methods to manipulate files (create, copy, delete, move)

DirectoryInfo Used to manipulate directories

File Modes
The FileMode enumeration specifies how a file is to be opened by a FileStream.

FileMode Description

CreateNew Creates a new file; throws error if it exists

Create Creates a new file or overwrites if it exists

Open Opens an existing file

OpenOrCreate Opens file if it exists, otherwise creates a new one

Append Opens file and moves to the end for writing only

Truncate Opens file and clears all contents


File Share
FileShare determines how a file will be shared with other processes while it is open.

FileShare Description

None No other process can access the file

Read Other processes can read the file

Write Other processes can write to the file

ReadWrite Other processes can read/write

Delete Other processes can delete the file

Reading and Writing Files


Example 1: Writing to a Text File
using System.IO;

FileStream fs = new FileStream("sample.txt", FileMode.Create);


StreamWriter sw = new StreamWriter(fs);

sw.WriteLine("Welcome to ASP.NET File Handling!");


sw.Close();
fs.Close();

Example 2: Reading from a Text File


using System.IO;

FileStream fs = new FileStream("sample.txt", FileMode.Open);


StreamReader sr = new StreamReader(fs);

string content = sr.ReadToEnd();


Console.WriteLine(content);
sr.Close();
fs.Close();

Creating, Moving, Copying, and Deleting Files

Operation Method Example

Create File.Create(path) File.Create("data.txt");

Copy File.Copy(source, destination) File.Copy("a.txt", "b.txt");

Move File.Move(source, destination) File.Move("a.txt", "folder/a.txt");

Delete File.Delete(path) File.Delete("data.txt");

Example: FileInfo Class


FileInfo fi = new FileInfo("data.txt");
fi.CopyTo("backup.txt");
fi.MoveTo("newfolder/data.txt");
fi.Delete();

File Uploading in ASP.NET


File uploading allows users to select files from their local system and upload them to the
web server.
ASP.NET FileUpload Control Example
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload File"
OnClick="btnUpload_Click" />
<asp:Label ID="lblMessage" runat="server" />
Code-behind:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string path = Server.MapPath("~/Uploads/" + FileUpload1.FileName);
FileUpload1.SaveAs(path);
lblMessage.Text = "File uploaded successfully!";
}
else
{
lblMessage.Text = "Please select a file to upload.";
}
}

IMPORTANT QUESTIONS

1 MARK

1.Which of the following is a Rich Control in ASP.NET?


a) TextBox
b) Calendar
c) Label
d) Button

2. The AdRotator control in ASP.NET is used for __________.


a) Displaying multiple images dynamically
b) Rotating text messages
c) Animating background color
d) Showing data from a database
3. Which property of the Calendar control sets the currently selected date?
a) CurrentDate
b) SelectedDate
c) ActiveDate
d) TodayDate

4. Which Rich Control is used to display data in tabular format?


a) DataGrid
b) TreeView
c) Menu
d) Panel

5. Which validation control ensures that a required field is not left blank?
a) CompareValidator
b) RequiredFieldValidator
c) RangeValidator
d) RegularExpressionValidator

6. The RangeValidator control is used to __________.


a) Compare two values
b) Check if value lies within a range
c) Validate using regular expressions
d) Check required field

7. Which property of the RegularExpressionValidator specifies the validation pattern?


a) Expression
b) ValidationExpression
c) Pattern
d) MatchText

8. The FileStream class belongs to which namespace?


a) System.IO
b) System.Data
c) System.Web
d) System.File

9. Which of the following is not a valid FileMode in C#?


a) Append
b) Create
c) Replace
d) OpenOrCreate

10. The FileShare.Read option allows __________.


a) No other process to access the file
b) Only reading by other processes
c) Both reading and writing by other processes
d) File deletion by other processes

11. Which method of File class is used to copy a file?


a) File.Copy()
b) File.Duplicate()
c) File.Move()
d) File.Replace()

12. The File.Move() method is used to __________.


a) Move or rename a file
b) Delete a file
c) Copy file contents
d) Create a new file

13. Which method is used to delete a file permanently in C#?


a) File.Destroy()
b) File.Remove()
c) File.Delete()
d) File.Clear()

14. Which control is used for uploading files in ASP.NET?


a) FileUpload
b) UploadBox
c) InputFile
d) FileControl

15. Which property of the FileUpload control gives the uploaded file’s name?
a) FileName
b) UploadName
c) SelectedFile
d) FileTitle

16.Which event of the Calendar control occurs when a date is selected by the user?
a) DateClick
b) SelectionChanged
c) DateSelected
d) ClickedDate

17. The CompareValidator control is used to __________.


a) Compare values of two controls
b) Validate required fields
c) Check value range
d) Validate file type

18. Which FileMode opens the file if it exists, otherwise creates a new one?
a) Open
b) Create
c) Append
d) OpenOrCreate

19. The File.Exists(path) method returns __________.


a) True if the file is open
b) True if the file exists
c) False if the file is empty
d) False if the file is hidden

20. Which property of the FileUpload control indicates whether a file has been selected?
a) FileSelected
b) IsFile
c) HasFile
d) Uploaded

5 MARK QUESTIONS
1. Explain any five Rich Controls in ASP.NET with their properties and events.
2. What are Validation Controls? Explain different types with examples.
3. Write a short note on FileStream class and its usage in C#.
4. List and explain different File Modes in C#.
5. Explain the steps to upload a file using the FileUpload control in ASP.NET.

10 MARK QUESTIONS
1. Describe Rich Controls in ASP.NET in detail with suitable examples.
2. Explain various Validation Controls in ASP.NET and their properties with an example
for each.
3. Explain FileStream classes in C#. Write a program to read and write data to a text file.
4. Discuss File Handling in C#. Explain how to create, move, copy, and delete files with
suitable examples.
5. What is File Uploading in ASP.NET? Explain the process with example code and
explain related properties and methods.

UNIT IV
Introduction
ADO.NET (ActiveX Data Objects .NET) is a part of the .NET Framework used to access and
manage data from different data sources such as SQL Server, Oracle, XML, and others.It
provides a bridge between front-end controls and back-end databases.ADO.NET is found in
the System.Data namespace.

Features of ADO.NET
1. Disconnected Data Architecture – Uses datasets that can work offline, reducing
database connections.
2. Scalability – Supports disconnected access, allowing large numbers of users.
3. XML Integration – DataSet can read/write XML data easily.
4. Data Binding Support – Easy to bind data to UI controls like GridView, DataGrid, etc.
5. Interoperability – Can interact with various databases using data providers.
6. Security – Provides secure data connections and command execution.

ADO.NET Architecture

ADO.NET consists of two main components:


1. Data Providers
Used for connecting to a data source, executing commands, and retrieving results.
• Key Components of Data Provider:
o Connection – Establishes a link to the database.
(e.g., SqlConnection, OleDbConnection)
o Command – Executes SQL queries or stored procedures.
(e.g., SqlCommand, OleDbCommand)
o DataReader – Provides fast, forward-only access to data.
(e.g., SqlDataReader, OleDbDataReader)
o DataAdapter – Fills DataSet/DataTable and updates the database.
2. DataSet
• A memory-resident representation of data.
• Can hold multiple tables and relationships.
• Works in disconnected mode (no continuous connection to the database).
• Data can be read, modified, and updated without keeping a live connection.

Types of ADO.NET Objects

Object Description

SqlConnection Establishes a connection to SQL Server database

SqlCommand Executes SQL commands

SqlDataReader Reads data in a forward-only manner

SqlDataAdapter Acts as a bridge between DataSet and data source

DataSet In-memory representation of data

DataTable Represents a single table of in-memory data

DataRelation Defines relationship between DataTables

DataView Provides customized view of DataTable data

Connected vs Disconnected Architecture

Aspect Connected Architecture Disconnected Architecture

Connection Continuous connection required Connection closed after data retrieval

Example DataReader DataSet

Speed Faster (real-time) Slightly slower


Aspect Connected Architecture Disconnected Architecture

Resource Usage High Low

Use Case Real-time operations Offline data manipulation

Typical ADO.NET Workflow


1. Create and open a Connection.
2. Create a Command to execute SQL query.
3. Use a DataReader or DataAdapter to fetch data.
4. Fill a DataSet/DataTable if working in disconnected mode.
5. Bind data to UI controls.
6. Perform Insert, Update, Delete operations.
7. Close the connection.

Example Code (C#)


using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = "Data Source=SERVER;Initial Catalog=SampleDB;Integrated
Security=True";

using (SqlConnection con = new SqlConnection(connectionString))


{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Students", con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["Name"].ToString());
}
reader.Close();
}
}
}
Advantages of ADO.NET
• High performance through connected/disconnected modes.
• XML integration for data sharing.
• Strongly typed DataSets.
• Easy to work with multiple data sources.
• Secure and reliable.
Disadvantages
• Requires more coding compared to older ADO.
• Data synchronization (in disconnected mode) can be complex.
• Some performance overhead in DataSets.

ADO.NET Components and Concepts


Database Connections
Used to establish a link between an application and a data source
(like SQL Server, Oracle, or Access).Represented by classes such as:
o SqlConnection – for SQL Server
o OleDbConnection – for OLE DB data sources
o OdbcConnection – for ODBC data sources
Properties:
o ConnectionString – defines data source, database name, credentials, etc.
o State – shows the current state (Open, Closed).
Methods:
o Open() – opens the connection
o Close() – closes the connection
Example:
SqlConnection con = new SqlConnection("Data Source=Server;Initial
Catalog=DB;Integrated Security=True");
con.Open();

Commands
Used to execute SQL queries, stored procedures, or DDL statements.Represented by
SqlCommand, OleDbCommand, etc.Can execute:
o ExecuteReader() – returns data using a DataReader
o ExecuteNonQuery() – executes commands like INSERT, UPDATE, DELETE
o ExecuteScalar() – returns a single value
Example:
SqlCommand cmd = new SqlCommand("SELECT * FROM Students", con);

Data Reader
Provides fast, forward-only, read-only access to data.Connected architecture: needs an open
connection to the database.Very efficient for reading large datasets.Represented by
SqlDataReader or OleDbDataReader.
Example:
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Console.WriteLine(dr["Name"]);
}
dr.Close();
Data Adapter
Acts as a bridge between DataSet and data source.Fills DataSet with data and updates the
database from DataSet.Works in disconnected mode.Represented by SqlDataAdapter or
OleDbDataAdapter.Contains four important Command objects:
o SelectCommand
o InsertCommand
o UpdateCommand
o DeleteCommand
Example:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Students", con);
DataSet ds = new DataSet();
da.Fill(ds);

Data Sets
A memory-resident representation of data.Works independently of the database
connection.Can hold multiple DataTables and their relationships.Supports XML for data
exchange.
Common classes: DataSet, DataTable, DataRow, DataColumn.
Example:
DataSet ds = new DataSet();
da.Fill(ds, "Students");

Data Controls and Their Properties


These are ASP.NET Web Form controls used to display, manipulate, and manage data
from ADO.NET objects.

Control Description Common Properties

Displays data in tabular DataSource, AutoGenerateColumns,


GridView
format AllowPaging, AllowSorting

DetailsView Displays one record at a time DataSource, DefaultMode, AutoGenerateRows

DataSource, EditItemTemplate,
FormView Displays and edits one record
InsertItemTemplate
Control Description Common Properties

Displays data using custom


Repeater DataSource, ItemTemplate
templates

Displays data in flexible DataSource, DataKeyNames,


ListView
layout InsertItemTemplate

Displays data in a list with


DataList DataSource, RepeatColumns, RepeatDirection
custom layout

Data Binding
DataBinding is the process of linking data from ADO.NET objects (like DataSet,
DataTable) to UI controls.Allows automatic synchronization between the UI and data source.
Types of Data Binding:
1. Simple Data Binding – binds a control to a single data value.
Example: TextBox1.Text = ds.Tables[0].Rows[0]["Name"].ToString();
2. Complex Data Binding – binds a control to a list or table.
Example: GridView1.DataSource = ds.Tables["Students"]; GridView1.DataBind();
Example:
GridView1.DataSource = ds.Tables["Students"];
GridView1.DataBind();

IMPORTANT QUESTIONS

1 MARK

1. ADO.NET stands for:


A) ActiveX Data Objects Network
B) ActiveX Data Objects .NET
C) Advanced Data Objects Network
D) Application Data Objects Network
2. ADO.NET is used for:
A) Image processing
B) File management
C) Data access and manipulation
D) GUI design

3. The namespace that contains ADO.NET classes is:


A) System.IO
B) System.Data
C) System.Text
D) System.Xml

4. Which object is used to establish a connection to a database?


A) SqlCommand
B) SqlConnection
C) SqlDataAdapter
D) DataSet

5. The property used to specify the database connection details is:


A) CommandText
B) ConnectionString
C) DataSource
D) SqlCommand

6. The method used to open a database connection is:


A) Connect()
B) Open()
C) Start()
D) Begin()

7. Which ADO.NET object is used to execute SQL statements?


A) SqlReader
B) SqlCommand
C) SqlAdapter
D) SqlDataset
8. Which method of SqlCommand is used to execute queries that return data?
A) ExecuteReader()
B) ExecuteNonQuery()
C) ExecuteScalar()
D) ExecuteDataSet()

9. Which method of SqlCommand is used for INSERT, UPDATE, DELETE operations?


A) ExecuteReader()
B) ExecuteScalar()
C) ExecuteNonQuery()
D) ExecuteData()

10. The DataReader object provides ______ access to data.


A) Random and Read-only
B) Forward-only and Read-only
C) Random and Editable
D) Backward and Editable

11. Which object acts as a bridge between DataSet and Data Source?
A) DataReader
B) DataAdapter
C) DataConnection
D) DataBinder

12. The Fill() method is used with which ADO.NET object?


A) DataReader
B) DataSet
C) DataAdapter
D) Command

13. The DataSet object works in which mode?


A) Connected
B) Disconnected
C) Semi-connected
D) Linked
14. The DataSet can store data in which format for easy sharing?
A) HTML
B) JSON
C) XML
D) Binary

15. Which ADO.NET object represents an in-memory cache of data?


A) SqlCommand
B) SqlConnection
C) DataSet
D) DataAdapter

16. Which ASP.NET control is used to display data in tabular form?


A) ListBox
B) GridView
C) DropDownList
D) TextBox

17. Which property of GridView is used to specify the source of data?


A) DataBind()
B) DataSource
C) AutoGenerateColumns
D) DataTable

18. The method used to bind data to a control is:


A) DataLink()
B) BindData()
C) DataBind()
D) Connect()

19. Simple Data Binding binds a control to:


A) Multiple values
B) Single value
C) XML document
D) DataSet only
20. Complex Data Binding binds a control to:
A) Single value
B) List or table of data
C) Command object
D) String value

5MARK QUESTIONS

1.Explain the architecture of ADO.NET with a neat diagram.


2. Differentiate between Connected and Disconnected architectures in ADO.NET.
3. Explain the role of SqlDataAdapter and its key methods.
4. Write a short note on DataBinding and its types in ASP.NET.
5. Describe any four ADO.NET Data Controls with their properties.

10 MARK QUESTIONS

1. Explain in detail the ADO.NET architecture with a labeled diagram and suitable
example.
2. Discuss all ADO.NET objects with their purpose and methods.
3. Explain DataSet in ADO.NET. Discuss its structure, properties, and advantages.
4. Explain DataBinding in ASP.NET. Differentiate between Simple and Complex
DataBinding with examples.
5. Describe in detail the working of ADO.NET components: Connection, Command,
DataReader, DataAdapter, and DataSet with examples.
UNIT V

GridView Control
The GridView control in ASP.NET is used to display, edit, sort, and delete tabular data from a
data source such as a database or DataSet.

Properties:
• DataSource – sets the data source.
• AutoGenerateColumns – automatically creates columns.
• AllowSorting – enables sorting feature.
• AllowPaging – enables paging feature.
• AutoGenerateEditButton – adds an Edit button.
• AutoGenerateDeleteButton – adds a Delete button.
(a) Deleting Records
Enable the Delete button using the property AutoGenerateDeleteButton="True".
Handle the RowDeleting event to remove data.
Example:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True"
AutoGenerateDeleteButton="True"
OnRowDeleting="GridView1_RowDeleting">
</asp:GridView>
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// code to delete record from database
}

(b) Editing Records


Enable Edit button using AutoGenerateEditButton="True".
Use RowEditing, RowUpdating, and RowCancelingEdit events to edit data.
Example:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateEditButton="True"
OnRowEditing="GridView1_RowEditing"
OnRowUpdating="GridView1_RowUpdating"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
</asp:GridView>

(c) Sorting
Enable sorting by setting AllowSorting="True".
Handle the Sorting event to rebind data in sorted order.
Example:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
OnSorting="GridView1_Sorting">
</asp:GridView>

(d) Paging
Used to divide large data into pages for better readability.
Enable by setting AllowPaging="True" and handle PageIndexChanging event.
Example:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
XML Classes in .NET
ADO.NET provides several XML-related classes in the System.Xml namespace to read,
write, and manipulate XML files.

Class Description

XmlReader Reads XML data in a forward-only, read-only way

XmlWriter Writes XML data to a stream or file

XmlDocument Represents an entire XML document (DOM-based)

XmlTextReader Reads XML text directly from a file or stream

XmlTextWriter Writes XML text directly

XPathDocument Provides fast read-only access for XPath queries

XmlNode Represents a single node in the XML tree

Example: Reading XML File


XmlDocument doc = new XmlDocument();
doc.Load("students.xml");
XmlNodeList list = doc.GetElementsByTagName("student");
foreach (XmlNode node in list)
{
Console.WriteLine(node["name"].InnerText);
}

Web Form to Manipulate XML Files


ASP.NET Web Forms can read, display, and update XML files using XML classes.
Example Workflow:
1. Load XML file using XmlDocument.
2. Display XML data using GridView or TextBox.
3. Modify XML nodes or attributes.
4. Save changes using Save() method.
Code Example:
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("data.xml"));
XmlNode node = doc.SelectSingleNode("//student[@id='1']/name");
node.InnerText = "Updated Name";
doc.Save(Server.MapPath("data.xml"));

Website Security
Website security ensures that only authorized users can access the website and data.
1. Authentication – verifies who the user is.
2. Authorization – determines what the user can do after login.

Authentication
Authentication is the process of identifying the user.
Types of Authentication in ASP.NET

Type Description

Windows Authentication Uses Windows user accounts.

Forms Authentication Uses custom login form and database.

Passport Authentication Uses Microsoft account for authentication.

Token-based Authentication Uses tokens like JWT for API/web apps.

Example (Forms Authentication in Web.config):


<authentication mode="Forms">
<forms loginUrl="Login.aspx" timeout="30" />
</authentication>
Authorization
Authorization controls access to resources after successful authentication.
Example (Web.config):
<authorization>
<allow users="admin" />
<deny users="?" />
</authorization>
• ? → anonymous users
• * → all users

Creating a Web Application in ASP.NET


Steps:
1. Open Visual Studio → Create New Project → “ASP.NET Web Application”.
2. Choose Empty, Web Forms, or MVC template.
3. Add Web Form (Default.aspx).
4. Design the page using controls (e.g., TextBox, Button, GridView).
5. Write code in code-behind (C#) for logic.
6. Configure Web.config for authentication, connection strings, etc.
7. Run the app using IIS Express or local server.

Example (Simple Web Form Code):


<asp:Label ID="Label1" runat="server" Text="Enter Name:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Welcome, " + TextBox1.Text;
}
IMPORTANT QUESTIONS

1 MARK QUESTIONS

1. Which ASP.NET control is used to display data in a tabular format?


a) DataList
b) GridView
c) Repeater
d) FormView

2. Which property enables sorting in GridView?


a) AllowEdit
b) AllowDelete
c) AllowSorting
d) SortExpression

3. Which event is fired when a user edits a GridView row?


a) RowDeleting
b) RowEditing
c) RowUpdating
d) RowCommand
4. Which method is used to bind data to a GridView control?
a) LoadData()
b) BindData()
c) DataBind()
d) Execute()

5. Which property allows paging in a GridView control?


a) AllowPaging
b) AllowPage
c) EnablePaging
d) PagingEnabled

6. In XML, what does the acronym stand for?


a) Extra Markup Language
b) Extended Markup Language
c) Extensible Markup Language
d) External Markup Language

7. Which class in .NET is used to read XML documents?


a) XmlReader
b) XmlWriter
c) XmlDocument
d) XmlTextReader

8. Which class is used to write data into an XML file?


a) XmlWriter
b) XmlDocument
c) XmlTextWriter
d) XmlReader

9. Which control allows XML data to be displayed in a Web Form?


a) XmlControl
b) XmlDataSource
c) XmlView
d) XmlBind

10. Which ASP.NET object provides user authentication information?


a) Request
b) Response
c) User
d) Session

11. Which type of authentication uses Windows user accounts?


a) Forms Authentication
b) Passport Authentication
c) Windows Authentication
d) Basic Authentication

12. Which file is used to configure authentication and authorization in ASP.NET?


a) WebConfig.xml
b) Config.aspx
c) Web.config
d) App.config

13. Which tag in Web.config is used to define authentication mode?


a) <authorization>
b) <authentication>
c) <identity>
d) <security>

14. Which authentication type requires users to log in using a form?


a) Forms Authentication
b) Windows Authentication
c) Anonymous Authentication
d) Token Authentication

15. What is the main purpose of authorization?


a) Identifies users
b) Validates passwords
c) Grants access to resources
d) Logs user activity

16. Which method is used to create a new XML node in the DOM model?
a) CreateNode()
b) AppendChild()
c) CreateElement()
d) AddNode()

17. Which event handles the deletion of a record in GridView?


a) RowDeleting
b) RowRemoved
c) RowDeleted
d) DataDelete

18. Which class provides a fast, forward-only, read-only cursor for XML data?
a) XmlTextReader
b) XmlDocument
c) XmlReader
d) XmlDataReader

19. Which component of a Web application handles security configuration?


a) Global.asax
b) Web.config
c) AppSettings
d) Security.xml

20. Which ASP.NET tool is used to create a new web application?


a) IIS
b) Visual Studio
c) SQL Server
d) Notepad++

5 MARK QUESTIONS
1. Explain the features of GridView control in ASP.NET.
2. Write short notes on XML classes in .NET.
3. Explain the concept of Authentication and Authorization in ASP.NET.
4. Write a short note on Paging and Sorting in GridView.
5. List and explain the steps to create a simple Web Application in ASP.NET.

10 MARK QUESTIONS
1. Explain GridView control with properties and methods for Editing, Deleting, Sorting,
and Paging.
2. Describe the XML classes in ASP.NET with examples for reading and writing XML
files.
3. Explain website security in ASP.NET — Authentication and Authorization with
Web.config examples.
4. Explain how to manipulate XML files using Web Forms with proper C# code
examples.
5. Explain the steps involved in creating an ASP.NET Web Application and discuss its
core components.

You might also like