UNIT-I
Introduction to .NET
The .NET Framework is a software development platform developed by Microsoft. It is used
for building and running Windows applications, web services, web applications, mobile apps,
and cloud-based apps.
Key Points:
Introduced by Microsoft in the early 2000s.
Supports multiple programming languages like C#, VB.NET, F#.
Provides a Common Language Runtime (CLR) for execution and a rich class library
called the Base Class Library (BCL).
Applications developed using .NET can be secure, scalable, and high-performing.
.NET Platform Includes:
.NET Framework – for Windows apps.
.NET Core – cross-platform, open-source (merged into .NET 5+).
ASP.NET – for web applications.
Xamarin/MAUI – for mobile development.
Entity Framework – for data access.
What is the .NET Framework?
The .NET Framework is a software development platform developed by Microsoft,
primarily for building and running Windows applications. It provides a runtime environment
(called the Common Language Runtime or CLR) and a class library for building applications.
🧱 Key Components
1. CLR (Common Language Runtime):
o Manages execution of .NET programs.
o Provides memory management, security, exception handling, etc.
2. BCL (Base Class Library):
o A rich collection of pre-built classes and functions for tasks like file handling,
database access, XML parsing, etc.
3. Languages Supported:
o C#, VB.NET, F#, and more (all compiled to Intermediate Language — IL).
4. Assemblies and Metadata:
o Code in .NET is compiled into assemblies (DLLs or EXEs), which include
metadata used by the CLR.
🧰 What You Can Build with It
Desktop apps (Windows Forms, WPF)
Web apps and services (ASP.NET)
Web APIs
Enterprise applications
🔄 .NET Framework vs .NET Core / .NET (modern .NET)
Feature .NET Framework .NET Core / .NET (latest)
Platform Windows-only Cross-platform (Windows, Linux, macOS)
Maintenance Still supported, no major updates Actively developed
Ideal for Legacy Windows apps Modern applications
📅 Current Status (as of 2025)
The .NET Framework is still maintained (latest version is 4.8.1), but no major future
enhancements are planned.
Microsoft recommends .NET 8 or later for new projects (cross-platform, faster, more
modern).
Benefits of .NET
1. Language Interoperability
You can write code in multiple languages (e.g., C#, VB.NET, F#) and have them work
together seamlessly.
This is possible due to the Common Language Runtime (CLR).
2. Rich Class Library
Comes with the Base Class Library (BCL) that simplifies tasks like file I/O,
networking, XML handling, and data access.
3. Automatic Memory Management
.NET uses a Garbage Collector (GC) to automatically manage memory allocation and
deallocation, reducing memory leaks.
4. Platform Independence (in .NET Core/.NET 5+)
While the .NET Framework runs only on Windows, modern .NET (Core and beyond)
runs on Windows, macOS, and Linux.
5. Security
.NET has built-in security features such as:
o Code access security (CAS)
o Role-based security
o Cryptography libraries
6. Integrated Development Environment (IDE) Support
Supported by Visual Studio, a powerful IDE offering:
o IntelliSense (code suggestions)
o Debugging tools
o Designer support for GUI development
7. Simplified Deployment
Assemblies and components can be deployed with applications — often with xcopy
deployment (just copy the files).
In .NET Core and newer, you can even publish as self-contained apps.
8. Robust Performance and Scalability
Just-in-Time (JIT) compilation, caching, and native optimization improve performance.
Ideal for small desktop tools and large-scale enterprise systems.
9. Web Development with ASP.NET
ASP.NET allows fast, secure, and scalable web applications and APIs.
Includes server controls, MVC architecture, and Razor pages.
10. Support for Modern Architecture
Microservices, containerization (via Docker), and cloud deployment are fully supported
in newer .NET versions.
11. Large Community and Ecosystem
Extensive documentation, tutorials, NuGet package ecosystem, and a strong developer
community.
Common Language Runtime (CLR) — Explained
The Common Language Runtime (CLR) is the core runtime engine of the .NET
Framework. It manages the execution of all .NET programs.
Think of it as the brain behind any .NET application — handling memory, security, execution,
and more.
🔧 Key Responsibilities of CLR
Function Description
Code Execution Executes the compiled code (MSIL → machine code).
Manages memory allocation and garbage collection (automatic
Memory Management
cleanup of unused objects).
Security Enforces code access security and type safety.
Provides a structured approach for catching and handling runtime
Exception Handling
errors.
Thread Management Supports multithreading — allowing efficient concurrent execution.
Just-In-Time Compilation Converts Intermediate Language (IL) to native machine code at
(JIT) runtime.
Allows interaction with COM components and native code (e.g.,
Interoperability
C/C++ libraries).
Type Safety and Ensures that code uses objects correctly to prevent memory
Verification violations or type mismatches.
🔁 CLR Execution Flow
1. Source Code (C#, VB.NET, etc.)
↓
2. Compiled to MSIL (Microsoft Intermediate Language) by language compiler
↓
3. CLR + JIT compile MSIL to native code at runtime
↓
4. Program runs on OS
🔍 Important Components of CLR
JIT Compiler – Converts IL to machine code.
Garbage Collector (GC) – Frees unused memory.
Class Loader – Loads classes as needed during execution.
Security Engine – Manages permissions and secure code execution.
Exception Manager – Manages and handles exceptions at runtime.
Features of CLR (Common Language Runtime)
The CLR is the execution engine of .NET and provides essential services for running
applications. Its key features include:
Feature Description
CLR automatically handles memory allocation and garbage
1. Memory Management
collection (freeing unused memory).
Provides code access security (CAS) and role-based security.
2. Security
Ensures safe execution of code.
Centralized handling of runtime errors using try-catch-finally
3. Exception Handling
blocks.
Ensures code only accesses memory it’s authorized to, preventing
4. Type Safety
type mismatches.
5. Just-In-Time Converts IL (Intermediate Language) to native machine code at
Compilation (JIT) runtime.
6. Thread Management Supports multithreaded applications with proper thread control.
7. Language Allows multiple languages (like C#, VB.NET, F#) to work together
Feature Description
Interoperability seamlessly.
8. Cross-Language CLR allows reuse of code written in different languages by
Integration compiling to a common IL.
⚙️Compilation Process in .NET
The compilation in .NET happens in two main stages:
1 Source Code → MSIL (Managed Code)
1️⃣
The .NET language compiler (e.g., C# compiler) compiles your source code into
Microsoft Intermediate Language (MSIL).
Output is a .dll or .exe file containing:
o MSIL code
o Metadata (info about classes, methods, properties, etc.)
2️⃣MSIL → Native Code
When the program runs, the JIT (Just-In-Time) compiler inside the CLR converts
MSIL to native machine code specific to the platform (Windows, x64, etc.)
MSIL (Microsoft Intermediate Language)
Also known as IL or CIL (Common Intermediate Language), it is the low-level, CPU-
independent code that all .NET languages compile to.
🔍 Key Points:
Feature Description
Platform-
Allows the same MSIL to run on different hardware via the CLR.
independent
Object-oriented Supports classes, interfaces, inheritance, etc.
Type-safe Enforces strict type checking at runtime.
Easy to inspect Tools like ILDASM (IL Disassembler) can view MSIL for debugging or
Feature Description
learning.
The .NET Framework Libraries
The .NET Framework Class Library (FCL) is a vast collection of reusable classes,
interfaces, and value types provided by Microsoft. These libraries make development faster by
providing ready-to-use functionality for common programming needs.
It’s a core part of the .NET Framework, and it works closely with the Common Language
Runtime (CLR).
🔍 Main Categories of .NET Framework Libraries
Library Description
Core functionalities like data types, arrays, math
System functions, date/time, etc. (System.String,
System.DateTime)
Reading and writing to files, file streams, directories (File,
System.IO
StreamReader)
System.Collections /
Data structures like lists, dictionaries, queues, stacks
System.Collections.Generic
Working with data, databases, and ADO.NET for SQL
System.Data
operations
System.Xml XML processing and manipulation
Networking, internet protocols (HTTP, FTP, SMTP), web
System.Net
requests
System.Threading Multithreading, task management, synchronization
System.Windows.Forms Building Windows desktop GUI applications
System.Web Creating web applications and services using ASP.NET
System.Drawing Graphics, images, fonts, and GDI+ for drawing on
Library Description
Windows Forms
Managing app configuration files (app.config,
System.Configuration
web.config)
Security features like cryptography, authentication, and
System.Security
permissions
🎯 Benefits of Using .NET Libraries
Productivity: Built-in functionality reduces time writing common code.
Consistency: Standard naming and structure across libraries.
Extensibility: You can build on or customize these libraries in your own applications.
Integration: Libraries work seamlessly with Visual Studio and the CLR.
🧠 Example: Using Some Libraries
vb.net
CopyEdit
Imports System
Imports System.IO
Module Example
Sub Main()
Dim path As String = "example.txt"
File.WriteAllText(path, "Hello from .NET!")
Dim content As String = File.ReadAllText(path)
Console.WriteLine(content)
End Sub
End Module
🔹 Uses:
System for base types
System.IO for file operations
The Visual Studio Integrated Development Environment (IDE)
Visual Studio is Microsoft’s flagship IDE (Integrated Development Environment) designed
for building .NET applications and many others. It’s one of the most powerful tools for software
development on Windows.
🎯 Key Features of Visual Studio IDE
Feature Description
Multi-language Support Supports C#, VB.NET, F#, C++, Python, JavaScript, etc.
IntelliSense Smart code completion, syntax suggestions, and parameter hints.
Set breakpoints, step through code, inspect variables, watch
Debugging Tools
expressions.
Drag-and-drop interface for Windows Forms, WPF, and Web Forms
GUI Designer
design.
Integrated Compiler Builds and compiles applications with a single click (or shortcut).
Built-in templates for Console Apps, Web Apps, Class Libraries,
Project Templates
APIs, etc.
NuGet Package Manager Easy integration of third-party libraries and tools.
Version Control
Git, Azure DevOps, and other version control systems are built in.
Integration
Testing Tools Unit test frameworks, test runners, and live testing support.
Real-time collaboration and pair programming with other
Live Share
developers.
📦 Editions of Visual Studio
Edition Purpose
Community
For students, open-source projects, and small teams.
(Free)
Edition Purpose
Professional For small to medium teams; includes more tools and support.
For large-scale teams and enterprises; includes advanced testing, architecture,
Enterprise
and diagnostics tools.
Types of Projects You Can Build
Console Applications
Windows Forms Applications
ASP.NET Web Applications
Web APIs
Class Libraries (DLLs)
WPF and UWP apps
Xamarin Mobile Apps
Azure Cloud Solutions
⚙️Example Workflow in Visual Studio
1. Create a New Project
File → New → Project → Choose "Console App" or "Windows Form App"
2. Write Code
Use editor with IntelliSense for fast development.
3. Build
Use Build → Build Solution (Ctrl + Shift + B) to compile code.
4. Debug
Set breakpoints → Start Debugging (F5)
5. Deploy
Publish using click-once, MSI, or package for web/cloud deployment.
UNIT-II
Introduction to VB.NET
VB.NET (Visual Basic .NET) is an object-oriented programming language developed by
Microsoft as part of the .NET framework. It is designed to be easy to learn and use, and it
supports modern programming concepts.
VB.NET Fundamentals
Syntax similar to classic Visual Basic but enhanced for .NET.
Supports object-oriented programming.
Programs are compiled into Microsoft Intermediate Language (MSIL).
Can build Windows apps, Web apps, and services.
Branching and Looping Statements
Branching (Decision Making)
If...Then...Else
Select Case (switch case)
Example:
vb.net
If score >= 50 Then
Console.WriteLine("Pass")
Else
Console.WriteLine("Fail")
End If
Looping (Repeating Blocks)
For...Next
While...End While
Do...Loop
Example:
vb.net
For i As Integer = 1 To 5
Console.WriteLine(i)
Next
Classes and Objects
Class: Blueprint for creating objects.
Object: Instance of a class.
Example:
vb.net
Public Class Car
Public Property Model As String
End Class
Dim myCar As New Car()
myCar.Model = "Toyota"
Constructors
Special method to initialize new objects.
Runs automatically when an object is created.
Example:
vb.net
Public Class Car
Public Property Model As String
Public Sub New(ByVal modelName As String)
Model = modelName
End Sub
End Class
Dim myCar As New Car("Honda")
Overloading
Defining multiple methods with the same name but different parameters.
Example:
vb.net
Public Sub Display(value As Integer)
Console.WriteLine(value)
End Sub
Public Sub Display(value As String)
Console.WriteLine(value)
End Sub
Inheritance and Polymorphism
Inheritance
Derived class inherits members from base class.
Example:
vb.net
Public Class Vehicle
Public Sub Drive()
Console.WriteLine("Driving")
End Sub
End Class
Public Class Car
Inherits Vehicle
End Class
Polymorphism
Ability to use derived class objects as base class type.
Methods can be overridden.
Interfaces
Defines a contract that classes must implement.
Example:
vb.net
Public Interface IEngine
Sub Start()
End Interface
Public Class Car
Implements IEngine
Public Sub Start() Implements IEngine.Start
Console.WriteLine("Engine Started")
End Sub
End Class
Arrays
Collection of elements of the same type.
Example:
vb.net
Dim numbers(4) As Integer ' Array of 5 elements (0 to 4)
numbers(0) = 10
Strings
Text data type.
Supports many methods like Length, Substring, Replace.
Exceptions
Error handling using Try...Catch...Finally.
Example:
vb.net
Try
Dim x = 5 / 0
Catch ex As DivideByZeroException
Console.WriteLine("Cannot divide by zero")
Finally
Console.WriteLine("Cleanup code")
End Try
Delegates and Events
Delegate: Type-safe function pointer.
Event: Message sent by an object to signal something happened.
Example:
vb.net
Public Delegate Sub NotifyEventHandler(message As String)
Public Class Process
Public Event Notify As NotifyEventHandler
Public Sub StartProcess()
RaiseEvent Notify("Process Started")
End Sub
End Class
UNIT-III
Building Windows Applications with Windows Forms
Windows Forms is a graphical (GUI) class library within .NET used to create rich desktop
applications for Windows.
It provides a visual designer in Visual Studio, letting you drag and drop controls onto forms.
🔧 Common Window Controls in Windows Forms
1. TextBox
Used for user input (single line).
Properties: Text, Multiline (to allow multiple lines).
vb.net
CopyEdit
Dim txtName As New TextBox()
txtName.Text = "Enter your name"
txtName.Location = New Point(20, 20)
2. RichTextBox
Like TextBox but supports rich formatting (bold, colors, fonts).
Suitable for editing formatted text.
3. Label
Displays static text.
Cannot be edited by the user.
vb.net
CopyEdit
Dim lblTitle As New Label()
lblTitle.Text = "User Registration"
lblTitle.Location = New Point(20, 5)
4. LinkLabel
Like Label but shows clickable hyperlinks.
vb.net
CopyEdit
Dim link As New LinkLabel()
link.Text = "Visit Website"
link.Location = New Point(20, 50)
AddHandler link.LinkClicked, AddressOf LinkClickedHandler
5. Button
Used to trigger actions when clicked.
vb.net
CopyEdit
Dim btnSubmit As New Button()
btnSubmit.Text = "Submit"
btnSubmit.Location = New Point(20, 80)
AddHandler btnSubmit.Click, AddressOf BtnSubmit_Click
6. CheckBox
Allows user to select/deselect an option (multiple selections allowed).
vb.net
CopyEdit
Dim chkAgree As New CheckBox()
chkAgree.Text = "I agree to terms"
chkAgree.Location = New Point(20, 110)
7. RadioButton
Allows user to select one option from a group (mutually exclusive).
vb.net
CopyEdit
Dim rbMale As New RadioButton()
rbMale.Text = "Male"
rbMale.Location = New Point(20, 140)
Dim rbFemale As New RadioButton()
rbFemale.Text = "Female"
rbFemale.Location = New Point(100, 140)
Basic Example: Simple Windows Form with Controls
vb.net
CopyEdit
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Label
Dim lblName As New Label()
lblName.Text = "Name:"
lblName.Location = New Point(10, 10)
Me.Controls.Add(lblName)
' TextBox
Dim txtName As New TextBox()
txtName.Location = New Point(60, 10)
Me.Controls.Add(txtName)
' Button
Dim btnSubmit As New Button()
btnSubmit.Text = "Submit"
btnSubmit.Location = New Point(60, 40)
AddHandler btnSubmit.Click, AddressOf btnSubmit_Click
Me.Controls.Add(btnSubmit)
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs)
MessageBox.Show("Hello, " & CType(Me.Controls("txtName"), TextBox).Text)
End Sub
End Class
Visual Studio Tips:
Drag controls from the Toolbox to the Form designer.
Set properties (like Name, Text, Location) via Properties window.
Double-click controls to auto-generate event handlers (like Button Click).
Windows Forms Controls and Concepts
1. Panels and GroupBoxes
Panel: A container control to group other controls; supports scrolling and acts as a
section on the form.
GroupBox: Also a container, but with a visible border and optional title; used to group
related controls visually.
vb.net
CopyEdit
Dim panel As New Panel()
panel.Size = New Size(200, 100)
panel.Location = New Point(10, 10)
Me.Controls.Add(panel)
Dim groupBox As New GroupBox()
groupBox.Text = "Options"
groupBox.Size = New Size(200, 100)
groupBox.Location = New Point(220, 10)
Me.Controls.Add(groupBox)
2. List Boxes
Displays a list of items where users can select one or multiple items.
vb.net
CopyEdit
Dim listBox As New ListBox()
listBox.Items.AddRange(New String() {"Apple", "Banana", "Cherry"})
listBox.Location = New Point(10, 120)
Me.Controls.Add(listBox)
3. Checked List Boxes
Like ListBox but each item has a checkbox.
vb.net
CopyEdit
Dim checkedListBox As New CheckedListBox()
checkedListBox.Items.AddRange(New String() {"Option 1", "Option 2", "Option 3"})
checkedListBox.Location = New Point(150, 120)
Me.Controls.Add(checkedListBox)
4. Combo Boxes
Dropdown list allowing the user to select from options or enter new text.
vb.net
CopyEdit
Dim comboBox As New ComboBox()
comboBox.Items.AddRange(New String() {"Red", "Green", "Blue"})
comboBox.Location = New Point(300, 120)
Me.Controls.Add(comboBox)
5. Picture Boxes
Displays images.
vb.net
CopyEdit
Dim pictureBox As New PictureBox()
pictureBox.Image = Image.FromFile("C:\image.jpg")
pictureBox.SizeMode = PictureBoxSizeMode.StretchImage
pictureBox.Size = New Size(100, 100)
pictureBox.Location = New Point(450, 10)
Me.Controls.Add(pictureBox)
6. Scroll Bars
Add scroll functionality to panels or custom controls.
vb.net
CopyEdit
Dim vScrollBar As New VScrollBar()
vScrollBar.Location = New Point(560, 10)
vScrollBar.Height = 100
Me.Controls.Add(vScrollBar)
7. Calendar Control
Displays a calendar to select dates.
vb.net
CopyEdit
Dim monthCalendar As New MonthCalendar()
monthCalendar.Location = New Point(10, 250)
Me.Controls.Add(monthCalendar)
8. Timer Control
Generates recurring events at set intervals, useful for animations or periodic tasks.
vb.net
CopyEdit
Dim timer As New Timer()
timer.Interval = 1000 ' 1 second
AddHandler timer.Tick, AddressOf Timer_Tick
timer.Start()
Private Sub Timer_Tick(sender As Object, e As EventArgs)
' Code to execute every second
End Sub
9. Handling Menus
Use MenuStrip for creating menus like File, Edit, etc.
vb.net
CopyEdit
Dim menuStrip As New MenuStrip()
Dim fileMenu As New ToolStripMenuItem("File")
Dim exitItem As New ToolStripMenuItem("Exit")
AddHandler exitItem.Click, Sub(sender, e) Me.Close()
fileMenu.DropDownItems.Add(exitItem)
menuStrip.Items.Add(fileMenu)
Me.MainMenuStrip = menuStrip
Me.Controls.Add(menuStrip)
10. Dialog Boxes
Common dialogs like OpenFileDialog, SaveFileDialog, MessageBox.
vb.net
CopyEdit
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
Dim filePath = OpenFileDialog1.FileName
MessageBox.Show("Selected: " & filePath)
End If
11. Report Viewer
Used to display reports inside your application (requires adding Microsoft Report Viewer
control).
12. Graphics
Drawing shapes, text, images using the Graphics class.
vb.net
CopyEdit
Protected Overrides Sub OnPaint(e As PaintEventArgs)
Dim g As Graphics = e.Graphics
g.DrawRectangle(Pens.Blue, 10, 10, 100, 50)
g.DrawString("Hello", New Font("Arial", 16), Brushes.Red, 20, 20)
End Sub
13. Deploying an Application
Publishing your Windows Forms app can be done using:
o ClickOnce Deployment: Easy way to publish and update apps via the web or
network.
o MSI Installer: Traditional setup package.
o Self-contained Executables: Package app with .NET runtime for target machine.
Use Visual Studio Publish Wizard to guide through deployment steps.
UNIT-IV
ASP.NET Basics
ASP.NET is a powerful framework by Microsoft for building dynamic web applications and
services. It runs on the server and generates HTML to send to the client's browser.
Features of ASP.NET
Server-Side Technology: Code runs on the server, not on the client browser.
Rich Web Controls: Ready-to-use controls (buttons, textboxes, grids) that render as
HTML.
Event-Driven Programming Model: Like Windows Forms, supports events (click,
load).
State Management: Handles state (ViewState, Session, Cookies) in the inherently
stateless web.
Security: Built-in authentication and authorization features.
Multiple Languages: Supports VB.NET, C#, and others.
Rich Data Access: Integration with ADO.NET for database operations.
Caching: Improves performance by storing pages, data, or objects.
Master Pages and Themes: For consistent look and feel across pages.
Extensible: Supports custom controls and components.
AJAX Support: Easily build partial page updates for responsive UI.
ASP.NET Page Directives
Page directives give instructions to the ASP.NET compiler about the page.
Common page directives include:
<%@ Page %>: Defines page attributes like language, code-behind file, inherits, etc.
Example:
aspx
CopyEdit
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb"
Inherits="_Default" %>
Attributes:
Language: Programming language used (VB, C#).
AutoEventWireup: Automatically connects page events like Page_Load.
CodeFile: File containing the code-behind.
Inherits: Class the page inherits from.
Other directives:
<%@ Import %>: Imports namespaces.
<%@ Register %>: Registers custom controls.
Building Forms with Web Server Controls
What are Web Server Controls?
Controls that run on the server and render HTML markup dynamically. They provide rich
functionality like automatic state management and event handling.
Common Web Server Controls:
Control Tag Example Description
TextBox <asp:TextBox ID="txtName" runat="server" /> Input text box
<asp:Button ID="btnSubmit" runat="server" Button with click
Button
Text="Submit" /> event
Label <asp:Label ID="lblMessage" runat="server" /> Displays text
Dropdown selection
DropDownList <asp:DropDownList ID="ddlOptions" runat="server" />
list
<asp:CheckBox ID="chkAgree" runat="server" Text="I
CheckBox Checkbox control
Agree" />
Example: Simple ASP.NET Web Form
Default.aspx
aspx
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Sample Form</title></head>
<body>
<form id="form1" runat="server">
<asp:Label ID="lblName" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" ForeColor="Blue"></asp:Label>
</form>
</body>
</html>
Default.aspx.vb
vb.net
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs)
lblMessage.Text = "Hello, " & txtName.Text & "!"
End Sub
End Class
How it works:
The form and controls are defined in the .aspx page.
Controls have runat="server" so they’re accessible in server-side code.
The Button control triggers a server-side event (btnSubmit_Click).
Server-side code processes input and updates the UI dynamically.
Validation Server Controls
Used to validate user input on both client and server side, ensuring data correctness before
processing.
Common Validation Controls:
RequiredFieldValidator
Ensures a field is not left empty.
CompareValidator
Compares values between controls or validates data types.
RangeValidator
Checks if input falls within a specified range.
RegularExpressionValidator
Validates input against a regex pattern.
CustomValidator
Allows custom validation logic with server and client code.
ValidationSummary
Displays all validation errors in one place.
Example:
aspx
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server" ControlToValidate="txtEmail"
ErrorMessage="Email is required." ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="revEmail" runat="server" ControlToValidate="txtEmail"
ErrorMessage="Invalid email format." ForeColor="Red"
ValidationExpression="^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"></asp:RegularExpressionValidato
r>
Rich Web Controls
These are enhanced server controls that provide advanced UI and functionality beyond basic
controls:
GridView: Displays tabular data with sorting, paging, editing.
DetailsView: Displays one record at a time with editing capabilities.
FormView: Customizable template-driven data display.
Calendar: Date selection control.
TreeView: Hierarchical tree structure.
Menu: Navigation menus.
These controls simplify building interactive, data-driven web pages.
Custom Controls
Controls you create to encapsulate reusable UI and behavior.
Types:
User Controls (.ascx files)
Composed of existing controls, easier to build, reusable UI parts.
Custom Server Controls
Compiled controls created by inheriting from base control classes, offering more
flexibility and can be packaged as DLLs.
Example:
Create a User Control (MyControl.ascx):
aspx
<%@ Control Language="VB" AutoEventWireup="true" CodeFile="MyControl.ascx.vb"
Inherits="MyControl" %>
<asp:Label ID="lblMessage" runat="server" Text="Hello from custom control"></asp:Label>
Use in page:
asp
<%@ Register Src="~/MyControl.ascx" TagName="MyControl" TagPrefix="uc1" %>
<uc1:MyControl ID="MyControl1" runat="server" />
Collections and Lists
Used to store groups of objects or values.
Common Types in .NET:
ArrayList (non-generic, older)
List(Of T) (generic, type-safe and preferred)
Dictionary(Of TKey, TValue) (key-value pairs)
Queue(Of T) (FIFO collection)
Stack(Of T) (LIFO collection)
Example: Using List(Of String)
vb.net
Dim fruits As New List(Of String)
fruits.Add("Apple")
fruits.Add("Banana")
fruits.Add("Cherry")
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
UNIT-V
Data Management with ADO.NET
ADO.NET is a set of classes in the .NET Framework used for data access and manipulation. It
provides a bridge between your application and data sources like databases.
Introducing ADO.NET
ADO.NET enables communication with data sources such as SQL Server, Oracle, XML
files, etc.
It works with connected and disconnected data models.
Main namespaces: System.Data, System.Data.SqlClient for SQL Server.
Key Features of ADO.NET
1. Disconnected Data Architecture
Uses DataSet and DataTable to work with data offline, reducing database load.
2. Data Providers
Optimized classes for each data source (e.g., SqlClient for SQL Server).
3. Strongly Typed Data
Supports typed datasets and data binding for type safety.
4. XML Integration
Data can be read and written in XML format.
5. Command Execution
Supports executing SQL queries, stored procedures.
6. Transaction Management
Supports transactions to maintain data integrity.
Using SQL Server with VB.NET
Basic Steps:
1. Import Namespace
vb.net
Imports System.Data.SqlClient
2. Create Connection
vb.net
Dim connectionString As String = "Data Source=SERVERNAME;Initial
Catalog=DatabaseName;Integrated Security=True"
Dim con As New SqlConnection(connectionString)
3. Open Connection and Execute Command
vb.net
con.Open()
Dim cmd As New SqlCommand("SELECT * FROM Students", con)
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("StudentName").ToString())
End While
reader.Close()
con.Close()
4. Using DataAdapter and DataSet
vb.net
Dim da As New SqlDataAdapter("SELECT * FROM Students", con)
Dim ds As New DataSet()
da.Fill(ds, "Students")
For Each row As DataRow In ds.Tables("Students").Rows
Console.WriteLine(row("StudentName"))
Next
Using SQL Server with ASP.NET
1. Add Connection String to Web.config
xml
<connectionStrings>
<add name="MyConn" connectionString="Data Source=SERVERNAME;Initial
Catalog=DatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
2. Access Database in Code-Behind
vb.net
Imports System.Data.SqlClient
Dim conStr As String = ConfigurationManager.ConnectionStrings("MyConn").ConnectionString
Dim con As New SqlConnection(conStr)
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
con.Open()
Dim cmd As New SqlCommand("SELECT * FROM Students", con)
Dim reader As SqlDataReader = cmd.ExecuteReader()
GridView1.DataSource = reader
GridView1.DataBind()
reader.Close()
con.Close()
End Sub
3. Binding Data to Controls
Use controls like GridView, Repeater, or DataList for displaying data.