You are on page 1of 8

Introduction to .

NET Framework Common Language Runtime


The .NET Framework is a software development platform developed by Microsoft. It provides a To run a .NET application, the developer writes the code using supported programming languages like
comprehensive programming infrastructure and a class library for building various types of applications, C#, VB, J#. The code is then compiled by a language-specific compiler (CSC for C#, VBC for VB) to
including web, desktop, and mobile applications. It supports multiple programming languages and allows generate Intermediate Language (IL) code. The IL code is a partially compiled code that can't be directly
developers to create Windows applications, web services, and more. executed by the Operating System. To execute the IL code, the .NET Framework uses the Common
Applications and services that can be developed using the .NET Framework include: Language Runtime (CLR).
Desktop Applications: You can create Windows desktop applications, such as graphical user interface The CLR takes the IL code and passes it to the Just-in-Time (JIT) Compiler, which is part of the CLR. The
(GUI) applications, using technologies like Windows Forms or Windows Presentation Foundation (WPF). JIT Compiler converts each line of the IL code into machine-specific instructions (binary format) that can
Web Applications: ASP.NET allows you to build web applications, both for traditional web browsers and be executed by the Operating System. The CLR provides the runtime environment for running .NET
more modern single-page applications (SPAs). applications.
Web Services: You can develop web services using ASP.NET to provide data and functionality over the What is Intermediate Language (IL) Code in .NET Framework?
internet, often in the form of APIs (Application Programming Interfaces). The Intermediate Language (IL code) in .NET Framework is a partially compiled code that is not
Mobile Applications: Using Xamarin, which is part of the .NET ecosystem, you can build cross-platform executable by the Operating System.
mobile applications for iOS and Android. Why Partial Compiled Code or Why Not Fully Compiled Code?
Cloud Services: .NET can be used to create cloud-native applications and services that run on platforms As a developer, you might wonder why the language compiler in .NET Framework only generates
like Microsoft Azure. partially compiled code instead of fully compiled code like machine or binary code. The reason is simple.
Game Development: The Unity game engine supports C# scripting, making it possible to create games We don't know the specific environment where the .NET code will run, such as the operating system
using the .NET Framework. (Windows XP, Windows 7, Windows 10, Windows 11, Windows Server, etc.).
IoT (Internet of Things) Applications: .NET Core and .NET 5+ have been used in developing software for In other words, we don't know the operating system, CPU configuration, machine configuration, security
IoT devices and services. configuration, and so on of the target system where we want to run our .NET applications. That's why
Machine Learning and AI: The .NET ecosystem includes libraries and frameworks for machine learning the Microsoft Intermediate Language (MSIL) or Intermediate Language (IL) code is only partially
and artificial intelligence, such as ML.NET. compiled. At runtime, the CLR (Common Language Runtime) in .NET Framework compiles this MSIL or IL
Types of .NET Frameworks code into machine-specific instructions or binary code based on the underlying operating system, CPU,
.NET is a platform for developers that consists of tools, programming languages, and libraries used to machine configuration, and so on.
build different applications like Desktop, Web, Mobile, and more. There are different versions of .NET Common Language Runtime (CLR) in .NET Framework:
available, each allowing .NET code to run on various operating systems such as Linux, macOS, Windows, CLR is the heart of the .NET Framework and it contains the following components.
iOS, Android, and others. 1.Security Manager 2.JIT Compiler 3.Memory Manager 4.Garbage Collector 5.Exception Manager
.NET Framework: This is the original implementation of the .NET platform, primarily for Windows. It 6.Common Language Specification (CLS) 7.Common Type System (CTS)
includes Windows Forms, WPF, ASP.NET, and various libraries. It’s commonly used for developing 1. Security Manager: There are basically two components to managing security. They are as follows: 1.
Windows desktop applications and traditional web applications. CAS (Code Access Security) 2. CV (Code Verification)
.NET Core: .NET Core was introduced as a cross-platform, open-source framework that could be used on These two components are used to determine if the current user has permission to access the assembly.
Windows, Linux, and macOS. It was designed to be modular and lightweight. .NET Core has since evolved The Security Manager also assesses the code's rights and whether it's safe to run on the Operating
into .NET 5 and later into “.NET 6” as a unifying platform. System. In a .NET Application, the Security Manager Component handles these security checks.
.NET 5 and .NET 6: These versions of the .NET platform are part of Microsoft’s effort to unify the .NET 2. JIT Compiler: The JIT (Just-In-Time) Compiler is responsible for Converting the MSIL code into Native
ecosystem. They provide cross-platform support and can be used to develop a wide range of Code (Machine Code or Binary code) that is going to be executed by the Operating System. The Native
applications, including web, desktop, cloud, and more. .NET 6 is a long-term support (LTS) release. Code (Machine Code or Binary code) is directly understandable by the system hardware. JIT compiles
Xamarin: Xamarin is a part of the .NET ecosystem that focuses on mobile app development. It allows the code just before the execution and then saves this translation in memory.
developers to create cross-platform mobile applications for iOS and Android using C# and the .NET 3. Memory Manager: The Memory Manager component of CLR in the .NET Framework allocates the
framework. necessary memory for the variables and objects that are to be used by the application.
Mono: Mono is an open-source implementation of the .NET framework that allows .NET applications to 4. Garbage Collector: When a dot net application runs, lots of objects are created. At a given point in
run on various platforms, including Linux and macOS. It’s often used for porting .NET applications to non- time, it is possible that some of those objects are not used by the application. So, Garbage Collector in
Windows environments. .NET Framework is nothing but a Small Routine or you can say it’s a Background Process Thread that
Blazor: Blazor is a web framework that’s part of the .NET ecosystem. It enables the development of web runs periodically and try to identify what objects are not being used currently by the application and de-
applications using C# and .NET technologies. Blazor WebAssembly allows running C# code in the allocates the memory of those objects.
browser, while Blazor Server runs on the server. 5. Exception Manager: The Exception Manager component of CLR in the .NET Framework redirects the
ML.NET: ML.NET is a cross-platform, open-source machine learning framework for .NET. It enables control to execute the catch or finally blocks whenever an exception has occurred at runtime. If we have
developers to build custom machine learning models using C# without requiring expertise in machine not handled the Runtime Exception, then the Exception Manager with throw the exception and
learning. abnormally terminate the program execution at the line where the exception has occurred.
ASP.NET: ASP.NET is a web application framework within the .NET ecosystem. It includes technologies 6. Common Type System (CTS) in .NET Framework: The .NET Framework supports many programming
like ASP.NET Web Forms, ASP.NET MVC, and ASP.NET Core for building web applications and services. languages such as C#, VB.NET, J#, etc. Every programming language has its own data type. One
Components of .NET Framework programming language data type cannot be understood by other programming languages. But, there
The two major components of the .NET Framework are the Common Language Runtime and the .NET can be situations where we need to communicate between two different programming languages. For
Framework Class Library. example, we need to write code in the VB.NET language and that code may be called from C# language.
.NET Framework Class Libraries: In order to ensure smooth communication between these languages, the most important thing is that
The .NET Framework Class Libraries are created by Microsoft. They are essential for writing code in .NET. they should have a Common Type System (CTS) which ensures that data types defined in two different
Class Libraries are like the foundation of .NET Programs. They are automatically installed when we install languages get compiled to a common data type. CLR in .NET Framework will execute all programming
the .NET framework. Class Libraries consist of pre-defined classes and interfaces that are used for language’s data types. This is possible because CLR has its own data types which are common to all
developing applications. They also offer a range of APIs and types for common functionality. These programming languages. At the time of compilation, all language-specific data types are converted into
include types for working with strings, dates, numbers, and more. CLR’s data type. This data type system of CLR is common to all .NET Supported Programming languages
Starting with the .NET Framework 4, the default location for the Global Assembly Cache and this is known as the Common Type System (CTS).
is %windir%\Microsoft.NET\assembly. In earlier versions of the .NET Framework, the default location 7. CLS (Common Language Specification) in .NET Framework:
is %windir%\assembly. CLS (Common Language Specification) is a part of CLR in the .NET Framework. The .NET Framework
Common Language Runtime (CLR): supports many programming languages such as C#, VB.NET, J#, etc. Every programming language has its
CLR stands for Common Language Runtime. It is the core component of the .NET framework. CLR own syntactical rules for writing the code which is known as language specification. One programming
converts MSIL code into native code and provides the runtime environment to execute the code. In language’s syntactical rules (language specification) cannot be understood by other programming
simple terms, CLR is the engine that runs applications. It handles tasks like managing threads, garbage languages. But, there can be situations where we need to communicate between two different
collection, type safety, exception handling, and more. programming languages. In order to ensure smooth communication between different .NET Supported
In the .NET framework, the Code is Compiled Twice: Programming Languages, the most important thing is that they should have Common Language
In the first compilation, the source code is compiled by the language compiler and generates the Specifications which ensures that language specifications defined in two different languages get
intermediate code known as MSIL (Microsoft Intermediate Language) or IL (Intermediate language compiled into a Common Language Specification. CLR in .NET Framework will execute all programming
code) or Managed Code. In the 2nd compilation, MSIL code is converted into Native code (native code language’s code. This is possible because CLR has its own language specification (syntactical rules) which
means code specific to the Operating system so that the code is executed by the Operating System) and are common to all .NET Supported Programming Languages. At the time of compilation, every language
this is done by CLR. compiler should follow this language specification of CLR and generate the MSIL code. This language
Always 1 compilation is slow and 2 compilation is fast. specification of CLR is common for all programming languages and this is known as Common Language
What is JIT? JIT stands for the Just-in-Time compiler. It is the component of CLR that is responsible for Specifications (CLS).
converting MSIL code into Native Code. Native code is the code that is directly understandable by the Visual Studio.NET IDE
operating system. Visual Studio .NET is Microsoft’s Integrated Development Environment (IDE) for creating, running and
What is not .NET? 1. .NET is not an Operating system. 2. It is not an application or package. 3. .NET is not debugging programs (also called applications) written in a variety of .NET programming languages. This
a database 4. It is not an ERP application. 5. .NET is not a Testing Tool. 6. It is not a programming IDE is a powerful and sophisticated tool that is used to create business-critical and mission-critical
language. applications.
What is exactly DOTNET? .NET is a framework tool that supports numerous programming languages and First Version: The first version of Visual Studio .NET was released in 2002.
technologies. It supports over 60 programming languages, 9 of which are designed by Microsoft, while Current Version: The current version may vary depending on the year, but as of my last update in 2022,
the rest are designed by non-Microsoft entities. The programming languages designed by Microsoft are Visual Studio 2022 was the latest version.
listed below: Editions: Visual Studio comes in different editions, such as Community, Professional, and Enterprise.
VB.NET, C#.NET, VC++.NET, J#.NET, F#.NET, Jscript.NET, WindowsPowerShell, Iron python, Iron Ruby Community is free for individual developers and small teams, while Professional and Enterprise editions
Technologies supported by the .NET framework are as follows: ASP.NET (Active Server Pages.NET), offer more advanced features and are typically used in larger organizations.
ADO.NET (Active Data Object.NET), WCF (Windows Communication Foundation), WPF (Windows Benefits:
Presentation Foundation), WWF (Windows Workflow Foundation), AJAX (Asynchronous JavaScript and User-Friendly: It provides a user-friendly interface with tools and features that make coding easier.
XML), LINQ (Language Integrated Query) Code Assistance: It offers code suggestions, error checking, and debugging tools to help you write better
code.
Menu Bar & Toolbar Compatibility: Supports various programming languages, making it versatile for different types of
Commands for managing the IDE and for developing, maintaining and executing programs are contained projects.
in the menus, which are located on the menu bar. Menus contain groups of related commands (also Team Collaboration: It includes tools for team collaboration and version control, so multiple developers
called menu items) that, when selected, cause the IDE to perform specific actions (e.g., open a window, can work on the same project.
save a file, print a file and execute a pro- gram). For example, new projects are created by selecting File Extensions: You can extend its functionality by adding extensions for specific tasks or programming
> New > Project.… languages.
Rather than having to navigate the menus for certain commonly used commands, the programmer can Debugging: Powerful debugging tools help find and fix errors in your code.
access them from the toolbar, which contains pictures, called icons, that graphically represent Integrated Development: It integrates with other Microsoft services like Azure for cloud development
commands. To execute a command via the toolbar, click its icon. Some icons contain a down arrow and SQL Server for database management.
that, when clicked, displays additional options.
Positioning the mouse pointer over an icon highlights the icon and, after a few seconds, displays a
description called a tool tip. Tool tips help novice programmers become familiar with the IDE’s
features. Common buttons often found on the toolbar include commands for actions like saving,
opening files, starting debugging sessions, stopping execution, and building projects.
Solution Explorer .NET Program Execution Process
In VB.NET's workspace, the Solution Explorer is like a side window that helps you organize your project. Non-.NET Program Execution (C, VB6, C++):
It's usually on the right side of the screen. Source Code Compilation: 1. Write code in C, VB6, or C++. 2.Compiler converts the code into machine-
Here's what it does: level code (binary code/native code).
1.Project Hierarchy: It shows the structure of your VB.NET project, like folders and files. This makes it Platform Dependency: 1. The generated native code is specific to the operating system. 2. Not portable
easier to move around your project. between different platforms.
2.File Management: You can add, remove, and organize files right from the Solution Explorer. This .NET Program Execution:
includes adding new things like classes or forms. Step 1: Compilation
3.References: It displays the references used in your project, like links to other libraries or parts of Source Code Compilation: 1. Write code in any .NET-supported language (C#, VB, J#, C++). 2. Compiler
your project. converts code into Intermediate Language (IL/MSIL/CIL).
4.Build and Debug: You can use the Solution Explorer to build and debug your project. Just right-click Assembly Generation: 1. .NET compiler creates an assembly (DLL or EXE) containing IL code. 2.
on the project or specific files to find these options. Assemblies are platform-independent and have a .DLL or .EXE extension.
5.Search and Navigation: It helps you quickly find files in your project and move around your code. Step 2: Execution
6.Properties: You can see and change properties of your project and files directly from the Solution CLR Execution: 1. .NET applications run on Common Language Runtime (CLR). 2. CLR is like a virtual
Explorer. environment for .NET programs.
Toolbox Just-In-Time Compilation (JIT): 1. CLR includes a Just-In-Time Compiler (JIT). 2. JIT converts IL code into
In Visual Basic .NET (VB.NET) Integrated Development Environment (IDE), the Toolbox is like a virtual native code when the program runs.
toolbox that holds various tools or controls you can use to build your application. It's usually located on Execution on the Operating System: The native code is executed by the underlying operating system.
the left side of the IDE. Key Points:
Here's what the Toolbox does: Portability: 1. .NET assemblies are in IL format, making them portable. 2. They can run on any platform
1.Drag-and-Drop Controls: You can find different controls, like buttons, text boxes, and labels, in the with CLR.
Toolbox. To use them in your application, you simply drag and drop them from the Toolbox onto your Managed Code: 1. IL code is managed by CLR. 2. Automatic memory management (garbage collection)
forms or user interface. is provided by CLR.
2.Building Blocks: The controls in the Toolbox act as building blocks for your application's user Language Support: 1. .NET supports languages like C#, VB, J#, and C++. 2. C# and VB generate managed
interface. Instead of coding these elements from scratch, you can select and place them using the code, while C++ can generate both managed and unmanaged code.
Toolbox. Execution Similarity to Java: 1. .NET program execution is similar to Java. 2. IL code and CLR in .NET are
3.Custom Controls: You can also add custom or third-party controls to the Toolbox, expanding the analogous to bytecode and JVM in Java.
range of tools available for your application development. In summary, .NET program execution involves compiling source code into IL, generating portable
4.Design Time Actions: The Toolbox is mainly used during the design phase of your application. It assemblies, and executing them on the CLR, which converts IL into native code for the operating system
provides a convenient way to visually design the layout of your forms. to understand. This process enables platform independence and automatic memory management in
Different controls of toolbox and their commonly used properties and methods .NET applications.
Commonly used controls from the Visual Basic .NET (VB.NET) Toolbox along with their commonly used
properties and methods: Basics of VB.NET
Button Control Program Structure
• Properties: 1. Text: Gets or sets the text on the button. 2. Name: Gets or sets the name of the A Visual Basic program is built up from standard building blocks. A solution comprises one or more projects.
button. 3. Enabled: Gets or sets whether the button is enabled or disabled. • A project in turn can contain one or more assemblies.
• Each assembly is compiled from one or more source files.
• Methods: 1. PerformClick(): Programmatically performs a click on the button.
• A source file provides the definition and implementation of classes, structures, modules, and interfaces, which
TextBox Control ultimately contain all your code.
•Properties: 1. Text: Gets or sets the text within the TextBox. 2. Name: Gets or sets the name of the Programming Elements
TextBox. 3. Enabled: Gets or sets whether the TextBox is enabled or disabled. When you create a project or file, you will see that some code is available in a particular order. Any code that you write
•Methods: 1. Clear(): Clears the text in the TextBox. 2. Select(): Selects all the text in the TextBox. should follow the following sequence.
• Option statements
Label Control
• Imports statements
•Properties: 1. Text: Gets or sets the text displayed by the label. 2. Name: Gets or sets the name of the • Namespace statements and namespace-level elements
label. 3. ForeColor: Gets or sets the foreground color of the label. If you enter statements in a different order, you will get a compilation error.
•Methods: 1. BringToFront(): Brings the label to the front of the z-order. A program can also contain conditional compilation statements. You can intersperse these in the source file among the
ComboBox Control statements of the preceding sequence.
Option Statements
•Properties: 1.Items: Gets the collection of items in the ComboBox. 2. SelectedIndex: Gets or sets the
Option statements establish ground rules for subsequent code, helping prevent syntax and logic errors.
index specifying the currently selected item. 3. Name: Gets or sets the name of the ComboBox. • The Option Explicit Statement ensures that all variables are declared and spelled correctly, which reduces debugging
•Methods: 1. Add(): Adds an item to the ComboBox. 2. Remove(): Removes an item from the time.
ComboBox. • The Option Strict Statement helps to minimize logic errors and data loss that can occur when you work between
CheckBox Control variables of different data types.
• The Option Compare Statement specifies the way strings are compared to each other, based on either theirBinary or
•Properties: 1. Checked: Gets or sets whether the CheckBox is checked. 2. Text: Gets or sets the text
Text values.
associated with the CheckBox. 3. Name: Gets or sets the name of the CheckBox. Imports Statements
•Methods: 1. Toggle(): Toggles the state of the CheckBox. You can include an Imports Statement (.NET Namespace and Type) to import names defined outside your project.
RadioButton Control • An Imports statement allows your code to refer to classes and other types defined within the imported namespace,
•Properties: 1. Checked: Gets or sets whether the RadioButton is checked. 2. Text: Gets or sets the text without having to qualify them.
• You can use as many Imports statements as appropriate.
associated with the RadioButton. 3. Name: Gets or sets the name of the RadioButton.
Namespace Statements
•Methods: 1. PerformClick(): Programmatically performs a click on the RadioButton. • Namespaces help you organise and classify your programming elements for ease of grouping and accessing.
• You use the Namespace statement to classify the following statements within a particular namespace.
MENU DESCRIPTION Conditional Compilation Statements
Conditional compilation statements can appear almost anywhere in your source file.
• They cause parts of your code to be included or excluded at compile time depending on certain conditions.
Contains commands for opening projects, closing projects, printing • You can also use them for debugging your application because conditional code runs in debugging mode only.
File
project data, etc. Namespace-Level Programming Elements
Classes, structures, and modules contain all the code in your source file. They are namespace-level elements, which can
Edit Contains commands such as cut, paste, find, undo, etc. appear within a namespace or at the source file level.
• They hold the declarations of all other programming elements.
• Interfaces, which define element signatures but provide no implementation, also appear at the module level.
View Contains commands for displaying IDE windows and toolbars. • Data elements at the namespace level are enumerations and delegates.
Module-Level Programming Elements
Project Contains commands for managing a project and its files. Procedures, operators, properties, and events are the only programming elements that can hold executable code
(statements that perform actions at run time).
Build Contains commands for compiling a program. The following module-level elements of your program.
• Function Statement
• Sub Statement
Contains commands for debugging (i.e., identifying and correcting Declare Statement
Debug •
problems in a program) and running a program. • Operator Statement
• Property Statement
Data Contains commands for interacting with databases. • Event Statement
Data elements at the module level are variables, constants, enumerations, and delegates.
Procedure-Level Programming Elements
Contains commands for arranging and changing the appearance of a
Format Most of the contents of procedure-level elements are executable statements, which constitute the run-time code of your
form’s controls. program.
• All executable code must be in some procedure (Function, Sub, Operator, Get, Set, AddHandler, RemoveHandler,
Contains commands for accessing additional IDE tools and options RaiseEvent).
Tools
that enable customisation of the IDE. • Data elements at the procedure level are limited to local variables and constants.
The Main Procedure
The Main procedure is the first code to run when your application has been loaded. Main serves as the starting point and
Window Contains commands for arranging and displaying windows. overall control for your application.
There are four variations of the Main
Help Contains commands for accessing the IDE’s help features. 1. Sub Main()
2. Sub Main(ByVal cmdArgs() As String)
3. Function Main() As Integer
4. Function Main(ByVal cmdArgs() As String) As Integer
The most common variety of this procedure is Sub Main().
VB.Net Hello World Example
Let's have a look at a simple code that would print the string "Welcome to VB.NET Tutorial."
Imports System
Module Program
'It will display a string on the console
Sub Main(args As String())
Console.WriteLine("Welcome to VB.NET Tutorial.")
End Sub End Module
Let's discuss various parts of the above program.
• The first line of the program Imports System is used to include the System namespace in the program.
• The next line has a Module declaration, the module Program.
• VB.Net is completely object-oriented, so every program must contain a module of a class that contains the data and
procedures that your program uses.
• Classes or Modules generally would contain more than one procedure.
• Procedures contain the executable code, or in other words, they define the behavior of the class.
• The next line starts with ' will be ignored by the compiler because it a comment.
• The next line defines the Main procedure, which is the entry point for all VB.Net programs.
• The Main procedure states what the module or class will do when executed.
• The Console.WriteLine("Welcome to VB.NET Tutorial.") in the Main procedure print the string on the screen.
Basic Syntax Variables
Visual Basic has a very simple programming syntax. The language is not case-sensitive, and it is easy In VB.NET, a variable is used to hold the value that can be used further in the programming.
even for beginners to start coding. • A variable is a simple name used to store the value of a specific data type in computer memory.
• It is an object-oriented programming language and is based on .NET Framework. • Each variable has a particular data type that determines the size, range, and fixed space in
• It is more easy, simple, and powerful than C or C++, and we also don't need to add semicolons computer memory.
after each statement. • Using variables, you can perform various operations and manipulate their values.
VB.Net program is defined as a collection of objects that communicate via invoking each other's Variable Declaration
methods. The Visual Basic compiler uses the Dim statement to determine the variable's data type and other
Object: Objects have states and behaviors. Example: A dog has states - color, name, breed as well as information, such as what code can access the variable.
behaviors - wagging, barking, eating, etc. An object is an instance of a class. In VB.NET, the declaration of a variable involves giving the variable a name and defining the data type to
Class: A class can be defined as a template/blueprint that describes the behaviors/states that objects of which it belongs. We use the following syntax:
its type support. Dim VarName as DataType
Methods: A method is behavior, and a class can contain many methods. It is in methods where the logic In the above syntax, VarName is the variable name while DataType is the name to which the variable
is written, data is manipulated, and all the actions are executed. belongs.
Instance Variables: Each object has its unique set of instance variables. An object's state is created by The following example declares a variable to hold an Integer value.
the values assigned to these instance variables. Dim numberOfCustomers As Integer
Let's have a look at a simple code that would print the string "Welcome to VB.NET Tutorial." In the above example, numberOfCustomers is the variable name while Integer is the data type to which
Imports System Module Program variable numberOfCustomers belongs.
'It will display a string on the console You can specify any data type or the name of an enumeration, structure, class, or interface.
Sub Main(args As String()) Dim finished As Boolean
Console.WriteLine("Welcome to VB.NET Tutorial.") Dim monitorBox As System.Windows.Forms.Form
End Sub End Module For a reference type, you use the New keyword to create a new instance of the class or structure that is
Method syntax specified by the data type.
The Sub Main indicates the entry point of the VB.Net program. Dim bottomLabel As New System.Windows.Forms.Label
Sub Main(args As String()) If you use New, you do not use an initializer expression. Instead, you supply arguments, if they are
Console.WriteLine("Welcome to VB.NET Tutorial.") required, to the constructor of the class from which you are creating the variable.
End Sub Variable Initialization
The following procedure activates the second window in the active document. You can assign a value to a variable when it is created. For a value type, you use an initializer to supply
Sub MakeActive() an expression to be assigned to the variable. The expression must evaluate to a constant that can be
Windows(2).Activate calculated at compile time.
End Sub Dim quantity As Integer = 10
Comments Dim message As String = "Just started"
In VB.NET, single-line comments start with an apostrophe ('). If an initializer is specified and a data type is not specified in an As clause, type inference is used to infer
There are no block comments in VB.NET. the data type from the initializer.
XML comments start with three apostrophes that are useful for documentation purposes. ' Use explicit typing.
Option Compare Statement Dim num1 As Integer = 3
In the Option Compare statement syntax, the braces and vertical bar indicate a mandatory choice ' Use local type inference.
between three items. Dim num2 = 3
Option Compare { Binary | Text | Database } In the above example, both num1 and num2 are strongly typed as integers. In the second declaration,
The following statement specifies that strings will be compared in a sort order that is not case-sensitive type inference infers the type from the value 3.
within the module. You can use an object initializer to declare instances of named and anonymous types. The following code
Option Compare Text creates an instance of a Student class and uses an object initializer to initialize properties.
Dim Statement syntax Dim author As New Author With {.First = "Michael", .Last = "Tucker"}
In the Dim statement syntax, the word Dim is a required keyword. The only required element is varname Declaring Multiple Variables
(the variable name). You can declare several variables in one declaration statement, specifying the variable name for each
The following statement creates three variables, myVar1, myVar2, and myVar3. one, and following each array name with parentheses. Multiple variables are separated by commas.
Dim myVar1, myVar2, myVar3 Dim num1, num2, numbers() As Integer
These are automatically declared as Variant variables. If you declare more than one variable with one As clause, you cannot supply an initializer for that group
The following example declares a variable as a String. of variables.
Dim myStr As String You can specify different data types for different variables by using a separate As clause for each
To declare several variables in one statement, include the data type for each variable. variable you declare. Each variable takes the data type specified in the first As clause encountered after
Dim x As Integer, y As Integer, z As Integer its variable name part.
Variables declared without a data type are automatically declared as Variant. Dim a, b, c As Single, x, y As Double, i As Integer
In the following statement, x and y are assigned the Variant data type. Only z is assigned the Integer
data type. Data Types
Dim x, y, z As Integer Data types refer to an extensive system used for declaring variables or functions of different types.
•In VB.NET, a data type is used to define a variable's type or function in a program.
Constants •Data types determine the type of data that any variable can store.
The constants refer to fixed values that the program may not alter during its execution, and these values •Variables belonging to different data types are allocated different amounts of space in the memory.
are also known as literals. VB.Net provides a wide range of data types. The following table shows the Visual Basic data types, their
• Constants store values that, as the name implies, remain constant throughout the execution of an supporting common language runtime types, and their nominal storage allocation.
application. A Data Type refers to which type of data or value is assigning to a variable or function so that a variable
• Constants can be of any of the basic data types like an integer constant, a floating constant, a can hold a defined data type value. The basic syntax of declaring a variable is as follows:
character constant, or a string literal. Dim VarName as DataType
• The constants are treated just like regular variables, except that their values cannot be modified •VarName: It defines the name of the variable that you assign to store values.
after their definition. •DataType: It represents the name of the data type that you assign to a variable.
Constant Declaration
You can use the Const statement to declare a constant and set its value. Once a constant is declared, it
cannot be modified or assigned a new value. Visual Basic Type CLR Type Structure Nominal Storage Allocation
• You declare a constant within a procedure or in the declarations section of a module, class, or
structure. Boolean Boolean Depends on implementing platform
• Class or structure-level constants are Private by default, but may also be declared as Public, Friend, Byte Byte 1 byte
Protected, or Protected Friend for the appropriate level of code access.
Char Char 2 bytes
The following example demonstrates the declaration and use of a constant value.
Const DaysInYear = 365 Date DateTime 8 bytes
Const WorkDays = 250
Console.WriteLine(DaysInYear) Decimal Decimal 16 bytes
Console.WriteLine(WorkDays) Double Double 8 bytes
Specify Data Type
The following example shows the declaration constants by specifying their data types using As keyword. Integer Int32 4 bytes
Const MyInteger As Integer = 42 Long Int64 8 bytes
Const DaysInWeek As Short = 7
Const Sunday As String = "Sunday" Object Object 4 bytes on 32-bit platform 8 bytes on 64-bit platform
Console.WriteLine(MyInteger)
SByte SByte 1 byte
Console.WriteLine(DaysInWeek)
Console.WriteLine(Sunday) Short Int16 2 bytes
Multiple Constants
Single Single 4 bytes
You can declare several constants in one declaration statement by specifying the name for each one and
separate the declarations with a comma and space as shown below. String String Depends on implementing platform
Const num1 As Integer = 4, num2 As Integer = 5, str1 As String = "Test String" Console.WriteLine(num1)
Console.WriteLine(num2) UInteger UInt32 4 bytes
Console.WriteLine(str1) ULong UInt64 8 bytes
Scope of User-Defined Constants
A Const statement's scope is the same as that of a variable declared in the same location. You can User-Defined (structure) (inherits from ValueType) Depends on implementing platform
specify the scope in any of the following ways.
• To create a constant that exists only within a procedure, declare it within that procedure. UShort UInt16 2 bytes
• To create a constant available to all procedures within a class, but not to any code outside that
module, declare it in the declarations section of the class.
• To create a constant that is available to all members of an assembly, but not to outside clients of
the assembly, declare it using the Friend keyword in the declarations section of the class.
• To create a constant available throughout the application, declare it using the Public keyword in
the declarations section of the class.
Operators Conditional Statements
In a programming language, operators are special symbols such as +, -, ^, etc. that perform some action The If...Then and If...Then...Else are conditional control statements. Using conditional statements, the
on operands. program can behave differently based on a defined condition checked during the statement's execution.
•Operators allow the processing of primitive data types and objects. If...Then
•They take as an input one or more operands and return some value as a result. The If...Then is the simplest form of control statement, frequently used in decision making and changing
For example, operators are the signs for adding, subtracting, multiplication, and division like +, -, *, /, the control flow of the program execution.
and the operations they perform on the integers and the real numbers. The basic syntax of the If...Then statement is shown below.
Types If condition Then
Below is a list of the different types of operators. [Statement(s)]
Type Description End If
Arithmetic Perform familiar calculations on numeric values, including shifting their bit An If...Then statement consists of an expression that determines whether a program statement or
patterns. statements execute.
Logical Compare Boolean expressions and return a Boolean result. The following example shows the usage of a simple If...Then statement.
Bitwise Evaluate two integral values in binary (base 2) form. Dim num1 As Integer = 7
Comparison Compare two expressions and return a Boolean value representing the Dim num2 As Integer = -1
result of the comparison. If num1 > 0 Then
String-concatenation Join multiple strings into a single string. Console.WriteLine("num1 is valid.")
Arithmetic End If
Arithmetic operators are used for performing many of the familiar arithmetic operations that involve If num2 < 0 Then
the calculation of numeric values represented by literals, variables, other expressions, function and Console.WriteLine("num2 is not valid.")
property calls, and constants. End If
Here are some examples of arithmetic operators and their effects. If...Then...Else
Dim a As Integer = 10 In an If...Then...Else statement, if the condition evaluates to true, the Body of the conditional
Dim b As Integer = 20 statement runs. If the condition is false, the else-statement runs.
Console.WriteLine("a + b = {0}", a + b) The basic syntax of the If...Then...Else statement is shown below.
Console.WriteLine("a - b = {0}", a - b) If condition Then
Console.WriteLine("a * b = {0}", a * b) [ statement(s) ]
Let's run the above code and you will see the following output. Else
a + b = 30 a - b = -10 a * b = 200 [ elsestatement(s) ]
The division operator / has a different effect on integer and real numbers. When we divide an integer End If
by an integer (like int, long, and sbyte) the returned value is an integer. Such division is called an integer It conditionally executes a group of statements, depending on the value of an expression.
division. The following example shows the usage of a simple If...Then...Else statement.
Here are some examples of division operators and their effect when using integer division. Public Sub Example2()
Dim squarePerimeter As Integer = 17 Dim randomizer As New Random()
Dim squareSideInt As Integer = squarePerimeter / 4 Dim count As Integer = randomizer.Next(0, 5)
Console.WriteLine(squareSideInt) Dim message As String
Dim squareSideDouble As Double = squarePerimeter / 4.0 If count = 0 Then
Console.WriteLine(squareSideDouble) message = "There are no items."
Let's run the above code and you will see the following output. Else
4 4.25 message = $"There are {count} items."
Logical End If
Logical operators or you can say Boolean operators take Boolean values and return a Boolean result Console.WriteLine(message)
(true or false). The basic Boolean operators are && (and), || (or), ^ (exclusive OR) and ! (logical End Sub
negation). Multiple If...Then...Else Statements
The following table contains the logical operators in C# and the operations that they perform. In some cases, we need to use a sequence of If...Then structures or multiple If...Then...Else statements,
Let's consider the following simple examples of logical operators. where the Else clause is a new If structure.
Dim a As Boolean = True If we use nested If structures, the code would be pushed too far to the right.
Dim b As Boolean = False In such situations, it is allowed to use a new If right after the Else and it is considered a good practice.
Console.WriteLine(a AndAlso b) Public Sub Example3()
Console.WriteLine(a OrElse b) Dim marks As Integer = 79
Console.WriteLine(Not b) If marks >= 90 Then
Console.WriteLine(b OrElse True) Console.WriteLine("A+")
Console.WriteLine((5 > 7) Xor (a = b)) ElseIf marks >= 80 Then
Bitwise Console.WriteLine("A")
A bitwise operator is an operator that acts on the binary representation of numeric types. ElseIf marks >= 70 Then
•In computers, all the data and particularly numerical data are represented as a series of ones and Console.WriteLine("B") E
zeros. lseIf marks >= 60
•For example, number 55 in the binary numeral system is represented as 00110111. Then Console.WriteLine("C")
Here is an example of using bitwise operators. ElseIf marks >= 50 Then
Dim a As Byte = 3 Console.WriteLine("D")
Dim b As Byte = 5 Else
Console.WriteLine(a Or b) Console.WriteLine("F")
Console.WriteLine(a And b) End If
Console.WriteLine(a Xor b) End Sub
Console.WriteLine(Not a And b) In the above example, a series of comparisons of a variable marks to check If...Then, it is one of the
Comparison grades (such as A+, A, B, C, or D). Every following comparison is done only in the case that the previous
Comparison operators are used to comparing two or more operands. comparison was not true. In the end, if none of the If...Then conditions are not fulfilled, the last Else
•greater than (>) clause is executed.
•less than (<) The result of the above example is shown below.
•greater than or equal to (>=) B
•less than or equal to (<=)
•equality (=)
•difference (<>) Do Loop
The Do Loop which is also known as do-while repeats a block of statements while a Boolean condition is
The following example shows the usage of comparison operators.
Dim x As Integer = 10 True or until the condition becomes True. The do-while loop is the same as the while loop, but the only
Dim y As Integer = 5 difference is while loop will execute the statements only when the defined condition returns true. Still,
Console.WriteLine("x > y : " & (x > y)) the do-while loop will execute the statements at least once because it will first execute the block of
Console.WriteLine("x < y : " & (x < y)) statements and then check the condition.
• Use a Do Loop structure when you want to repeat a set of statements an indefinite number of
Console.WriteLine("x >= y : " & (x >= y))
Console.WriteLine("x <= y : " & (x <= y)) times until a condition is satisfied.
Console.WriteLine("x = y : " & (x = y)) • You can use either While or Until to specify conditions, but not both.
Console.WriteLine("x != y : " & (x <> y)) • You can test the condition only one time, at either the start or the end of the loop.
String Concatenation • If you test conditions at the start of the loop, the loop might not run even once.
• If you test at the end of the loop, the loop always runs at least one time.
Concatenation operators join multiple strings into a single string. There are two concatenation
operators, + and &. Both carry out the basic concatenation operation, as the following example shows. The following example shows the Do Loop by using the While to specify the condition.
Dim vbnet As String = "VB.NET " Dim index As Integer = 0
Dim tutorial As String = "Tutorial." Do
Dim vbnetTutorial As String = vbnet & tutorial Console.WriteLine(vbnetTutorial) Console.WriteLine(index.ToString & " ")
index += 1
Dim csharp8 As String = vbnet + "15"
Console.WriteLine(csharp8) Loop While index <= 10
The following example behaves in the same way but uses an Until clause instead of a While clause.
Dim index As Integer = 0
While End Loop Do
In programming, developers often require a repeated execution of a sequence of operations. A loop is a basic programming Console.WriteLine(index.ToString & " ")
construct that allows repeated execution of a fragment of source code. index += 1
In a While End Loop, the code is repeated a fixed number of times, or it repeats until a given condition is true.
Syntax Loop Until index > 10
While condition In the following example, the condition stops the loop when the index variable is greater than 100.
'statements However, the If statement in the loop causes the Exit Do statement to stop the loop when the index
End While variable is greater than 10.
• The while statement executes a statement or a block of statements while a specified condition evaluates to true. Dim index As Integer = 0
• The condition is evaluated before each execution of the loop, a while loop executes zero or more times.
Example Do While index <= 100
Public Sub Example1() Dim index As Integer = 0 While index <= 10 Console.Write(index.ToString & " ") index += 1 End While If index > 10 Then
Console.WriteLine("") End Sub Exit Do
The following example shows the use of the Continue While and Exit While statements. End If C
Public Sub Example2() Dim index As Integer = 0 While index < 100000 index += 1 If index >= 5 And index <= 8 Then Continue onsole.WriteLine(index.ToString & " ")
While End If Console.Write(index.ToString & " ") If index = 10 Then Exit While End If End While End Sub
index += 1
Loop
For Next Loop INTRODUCTION TO ASP.NET
The For Next Loop is used to repeatedly execute a sequence of code or a block of code until a given ASP.NET, or Active Server Pages.NET, is a web development framework developed by Microsoft. It
condition is satisfied. It is useful in such a case when we know how many times a block of code has to be allows developers to build dynamic, interactive, and data-driven web applications and websites. ASP.NET
executed. You use a For Next Loop when you want to repeat some statements a set number of times. is a part of the larger .NET framework and is widely used for creating robust and scalable web
In the following example, the index variable starts with a value of 1 and is incremented with each applications.
iteration of the loop, ending after the value of the index reaches 10. Here's a brief introduction to ASP.NET:
Public Sub Example1() 1.Server-Side Web Development: ASP.NET is a server-side technology, meaning the code is executed on
For index As Integer = 1 To 10 the web server rather than on the user's browser. This allows for dynamic content generation and
Console.Write(index.ToString & ", ") processing on the server before sending it to the client.
Next 2.Object-Oriented Programming (OOP): ASP.NET is built on the principles of object-oriented
Console.WriteLine("") programming, providing a structured and modular approach to building web applications. This makes it
End Sub easier to manage and maintain code.
Let's consider another example in which the number variable starts at 5 and is reduced by 0.5 on each 3..NET Framework Integration: ASP.NET is tightly integrated with the .NET framework. This integration
iteration of the loop, ending after the value of number reaches 0. The Step argument of -.5 reduces the allows developers to leverage the rich set of libraries, tools, and languages provided by .NET for building
value by 0.5 on each iteration of the loop. web applications.
Public Sub Example2() 4.Support for Multiple Languages: ASP.NET supports various programming languages, including C#,
For number As Double = 5 To 0 Step -0.5 VB.NET, and F#. Developers can choose the language they are most comfortable with while building
Console.Write(number.ToString & ", ") ASP.NET applications.
Next 5.Web Forms and MVC: ASP.NET offers two primary development models: Web Forms and MVC
Console.WriteLine("") (Model-View-Controller). Web Forms follow a more event-driven, RAD (Rapid Application Development)
End Sub approach, while MVC provides a more structured and testable architecture.
Nesting Loops 6.Rich Controls and Components: ASP.NET provides a rich set of server controls and components that
You can also nest For Next loops by putting one loop within another. The following example shows simplify common web development tasks. These controls encapsulate complex HTML and JavaScript,
nested For Next loops that have different step values. making it easier to build interactive and feature-rich web applications.
Public Sub Example3() 7.State Management: ASP.NET provides mechanisms for managing state, both on the client and server
For indexA = 1 To 3 sides. This is crucial for maintaining user-specific data and preserving the application's state across
Dim sb As New System.Text.StringBuilder() multiple requests.
For indexB = 20 To 1 Step -2 8.Security Features: ASP.NET includes built-in security features to help protect web applications from
sb.Append(indexB.ToString) common threats. This includes authentication, authorization, and protection against common
sb.Append(" ") vulnerabilities.
Next indexB 9.Database Connectivity: ASP.NET seamlessly integrates with databases, allowing developers to interact
Console.WriteLine(sb.ToString) with data easily. It supports various data access technologies, including ADO.NET and Entity Framework.
Next indexA ASP.NET, a web development framework developed by Microsoft, comes with a variety of features that
End Sub make it powerful for building dynamic and scalable web applications. Here are some key features of
The outer loop creates a string for every iteration of the loop. The inner loop decrements a loop counter ASP.NET:
variable for every iteration of the loop. When nesting loops, each loop must have a unique counter Server-Side Code Execution: ASP.NET allows the execution of server-side code, enabling the
variable. development of dynamic web applications with server-based logic.
Exit For and Continue For Language Support: Supports multiple programming languages, including C#, VB.NET, F#, and more.
The Exit For statement immediately exits the For Next loop and transfers control to the statement that Developers can choose the language they are most comfortable with.
follows the Next statement. The Continue For statement transfers control immediately to the next ASP.NET Web Forms: Web Forms provide a drag-and-drop, event-driven programming model for
iteration of the loop. building web applications. Mimics the development style of Windows Forms applications.
The following example shows the use of the Continue For and Exit For statements. ASP.NET MVC (Model-View-Controller): Offers an alternative architecture for web development,
Public Sub Example4() emphasizing separation of concerns. Well-suited for building modern, maintainable web applications.
For index As Integer = 1 To 100000 ASP.NET Core: A cross-platform, high-performance, and open-source framework. Supports cloud-based
If index >= 5 AndAlso index <= 8 Then development and deployment.
Continue For ASP.NET Web API: Allows building RESTful web services and APIs. Facilitates communication between
End If different systems and devices.
Console.Write(index.ToString & " ") Integrated Development Environment (IDE): Developed within Visual Studio, a powerful integrated
'If index is 10, exit the loop. development environment. Offers features like code completion, debugging, and design tools.
If index = 10 Then Rich Class Library: Access to a vast library of classes and APIs in the .NET Framework. Simplifies common
Exit For tasks and accelerates development.
End If State Management: Provides various mechanisms for state management, including ViewState and
Next session state. Supports both client-side and server-side state management.
Console.WriteLine("") Security Features: Includes built-in security features to protect against common web vulnerabilities.
End Sub Supports authentication and authorization mechanisms.
You can put any number of Exit For statements in a For Next loop. When used within nested For Next Difference between ASP & ASP.NET
loops, Exit For exits the innermost loop and transfers control to the next higher level of nesting. ASP (Active Server Pages) and ASP.NET are both web development frameworks developed by Microsoft,
Exit For is often used after you evaluate some condition such as an If...Then...Else structure. but they have significant differences in terms of architecture, programming model, and features. Let's
Statements look at their differences and birthdates:
In VB.NET, a statement is a complete instruction. It can contain keywords, operators, variables, constants, and expressions. 1.ASP (Active Server Pages):
The statements can be categorized into the following categories. 1. Birthdate: ASP was first released in December 1996.
•Declaration Statements
2. Architecture: ASP uses a scripting language (like VBScript or JScript) embedded
•Executable Statements
Executable Statements in HTML pages. It is an interpreted language, and the code is processed on the
An executable statement performs an action. It can call a procedure, branch to another place in the code, loop through server each time a request is made.
several statements, or evaluate an expression. An assignment statement is a special case of an executable statement. 2.ASP.NET:
The following example uses an If...Then...Else control structure to run different blocks of code based on the value of a 1. Birthdate: ASP.NET was first released in January 2002.
variable.
2. Architecture: ASP.NET is a more modern and robust framework compared to
Sub ExecutableStatement()
Dim a As Integer = 13 ASP. It uses a compiled, object-oriented programming model and supports
If (a < 20) Then multiple languages like C# and VB.NET. ASP.NET applications are built on top of
Console.WriteLine("a is less than 20") the .NET Framework, providing a more modular and scalable approach to web
Else Console.WriteLine("a is greater than 20") development.
End If
Key Differences:
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine() •Programming Model: ASP uses a procedural scripting model, while ASP.NET uses an object-oriented
End Sub programming model.
Declaration Statements •Performance: ASP.NET generally offers better performance due to its compiled nature and various
You use declaration statements to name and define procedures, variables, properties, arrays, and constants. When you performance optimizations.
declare a programming element, you can also define its data type, access level, and scope. The following example contains
•Language Support: ASP primarily supports scripting languages, while ASP.NET supports multiple
three declarations.
Sub Example1() Const maxAge As Integer = 60 Dim height As Double = 6.5 End Sub languages, making it more versatile.
•The first declaration is the Sub statement, it declares a procedure named which is Public. •State Management: ASP.NET provides more sophisticated state management options, including server-
•The second declaration is the Const statement, which declares the constant maxAge, specifying the Integer data type and a side and client-side state management techniques.
value of 60. •Development Tools: ASP.NET benefits from a more modern set of development tools like Visual Studio,
•The third declaration is the Dim statement, which declares the variable height.
providing a richer development experience.
Statement Description ASP.NET Web Forms
Web Forms are web pages built on the ASP.NET Technology. It executes on the server and generates
Dim Declares and allocates storage space for one or more variables.
output to the browser. It is compatible to any browser to any language supported by .NET common
Const Declares and defines one or more constants. language runtime. It is flexible and allows us to create and add custom controls. We can use Visual
Studio to create ASP.NET Web Forms. It is an IDE (Integrated Development Environment) that allows us
Enum Declares an enumeration and defines the values of its members. to drag and drop server controls to the web forms. It also allows us to set properties, events and
Declares the name of a class and introduces the definition of the variables, properties, events, and methods for the controls. To write business logic, we can choose any .NET language like: Visual Basic or
Class
procedures that the class comprises. Visual C#. Web Forms are made up of two components: the visual portion (the ASPX file), and the code
behind the form, which resides in a separate class file. The main purpose of Web Forms is to overcome
Declares the name of a structure and introduces the definition of the variables, properties, events, and
Structure the limitations of ASP and separate view from the application logic.
procedures that the structure comprises.
ASP.NET provides various controls like: server controls and HTML controls for the Web Forms.
Module
Declares the name of a module and introduces the definition of the variables, properties, events, and Fig: This diagram shows the components of the ASP.NET
procedures that the module comprises.

Declares the name of an interface and introduces the definitions of the members that the interface
Interface
comprises.

Function Declares the name, parameters, and code that defines a Function procedure.

Declare Declares a reference to a procedure implemented in an external file.

Declares the operator symbol, operands, and code that define an operator procedure on a class or
Operator
structure.

Event Declares a user-defined event.

Used to declare a delegate. A delegate is a reference type that refers to a Shared method of a type or an
Delegate
instance method of an object.
Server Controls HTML Controls
Server controls in ASP.NET are elements or components that run on the server side and encapsulate the These controls render by the browser. These controls are standard HTML elements with additional
functionality and behavior of user interface elements. These controls generate HTML and run in attributes that make them server-side controls. They have a runat="server" attribute, which allows
response to server-side events, allowing developers to create dynamic and interactive web applications. them to be manipulated on the server side. Examples include <asp:TextBox>, <asp:Button>,
<asp:CheckBox>, and <asp:DropDownList>.
Control Name Applicable Events Description Example: <asp:TextBox ID="txtName" runat="server"></asp:TextBox>

Label None It is used to display text on the HTML page. Controls Name Description

TextBox TextChanged It is used to create a text input in the form.


Button It is used to create HTML button.

Button Click, Command It is used to create a button.


Reset Button Resets all other HTML form elements on a form to a default value
It is used to create a button that looks similar to the
LinkButton Click, Command
hyperlink. Automatically POSTs the form data to the specified page listed in the Action attribute in the FORM
Submit Button
tag
It is used to create an imagesButton. Here, an image
ImageButton Click
works as a Button. Text Field Gives the user an input area on an HTML form

It is used to create a hyperlink control that responds Text Area Used for multi-line input on an HTML form
Hyperlink None
to a click event.
Places a text field and a Browse button on a form and allows the user to select a file name from
DropDownList SelectedIndexChanged It is used to create a dropdown list control. File Field
their local machine when the Browse button is clicked

It is used to create a ListBox control like the HTML An input area on an HTML form, although any characters typed into this field are displayed as
ListBox SelectedIndexCnhaged Password Field
control. asterisks

CheckBox Gives the user a check box that they can select or clear
CancelCommand, EditCommand, DeleteCommand,
It used to create a frid that is used to show data. We
ItemCommand, SelectedIndexChanged,
DataGrid can also perform paging, sorting, and formatting Radio Button Used two or more to a form, and allows the user to choose one of the controls
PageIndexChanged, SortCommand,
very easily with this control.
UpdateCommand, ItemCreated, ItemDataBound
Table Allows you to present information in a tabular format

Image Displays an image on an HTML form


CancelCommand, EditCommand, DeleteCommand,
It is used to create datalist that is non-tabular and
DataList ItemCommand, SelectedIndexChanged,
used to show data. Displays a list of items to the user. You can set the size from two or more to specify how many
UpdateCommand, ItemCreated, ItemDataBound
ListBox items you wish show. If there are more items than will fit within this limit, a scroll bar is
automatically added to this control.

It allows us to create a non-tabular type of format


for data. You can bind the data to template items, Displays a list of items to the user, but only one item at a time will appear. The user can click a
Repeater ItemCommand, ItemCreated, ItemDataBound Dropdown
which are like bits of HTML put together in a specific down arrow from the side of this control and a list of items will be displayed.
repeating format.
Horizontal Rule Displays a horizontal line across the HTML page
CheckBox CheckChanged It is used to create checkbox.
Validation Controls
ASP.NET provides a set of validation controls that allow you to perform both client-side and server-side validation in your
It is used to create a group of check boxes that all web forms. These controls help ensure that user input is accurate, complete, and meets the specified criteria before it is
CheckBoxList SelectedIndexChanged
work together. processed by the server. The validation controls are part of the ASP.NET Web Forms framework and simplify the process of
implementing validation logic in your applications.
RadioButton CheckChanged It is used to create radio button.
Validator Description
It is used to create a group of radio button controls
RadioButtonList SelectedIndexChanged
that all work together.
It is used to compare the value of an input control against a value of another
CompareValidator
input control.
Image None It is used to show image within the page.

It is used to create a panel that works as a RangeValidator It evaluates the value of an input control to check the specified range.
Panel None
container.
RegularExpressionValid It evaluates the value of an input control to determine whether it matches a
PlaceHolder None It is used to set placeholder for the control. ator pattern defined by a regular expression.

SelectionChanged, VisibleMonthChanged, It is used to create a calendar. We can set the RequiredFieldValidator It is used to make a control required.
Calendar
DayRender default date, move forward and backward etc.

ValidationSummary It displays a list of all validation errors on the Web page.

AdRotator AdCreated
It allows us to specify a list of ads to display. Each CompareValidator:
time the user re-displays the page. • Compares the value of one input control to the value of another.
• We can use comparison operators like: less than, equal to, greater than etc.
Table None It is used to create table.
Property Description

It is used to display XML documents within the


XML None
HTML. AccessKey It is used to set keyboard shortcut for the control.

It is like a label in that it displays a literal, but allows TabIndex The tab order of the control.
Literal None us to create new literals at runtime and place them
CompareValidator Properties

into this control.


BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

ControlToComp
It takes ID of control to compare with.
are

ControlToValid
It takes ID of control to validate.
ate

It is used to display error message when validation


ErrorMessage
failed.

Operator It is used set comparison operator.


RangeValidator: Checks that the value entered falls within a specified range. It allows us to check ValidationSummary
whether the user input is between a specified upper and lower boundary. This range can be numbers, The ValidationSummary control in ASP.NET is used to display a summary of validation errors that occur
alphabetic characters and dates. The ControlToValidateproperty is used to specify the control to on the page. It consolidates error messages from multiple validation controls into a single location,
validate. The MinimumValue and MaximumValue properties are used to set minimum and maximum making it easier for users to identify and address issues with their input. We can
boundaries for the control. set DisplayMode property to display error messages as a list, bullet list or single paragraph.
RangeValidator Properties ValidationSummary Properties

Property Description Property Description

AccessKey It is used to set keyboard shortcut for the control. AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control. BackColor It is used to set background color of the control.

BackColor It is used to set background color of the control. BorderColor It is used to set border color of the control.

BorderColor It is used to set border color of the control. Font It is used to set font for the control text.

BorderWidth It is used to set width of border of the control. ForeColor It is used to set color of the control text.

Font It is used to set font for the control text. Text It is used to set text to be shown for the control.

ForeColor It is used to set color of the control text. ToolTip It displays the text when mouse is over the control.

Text It is used to set text to be shown for the control. Visible To set visibility of control on the form.

ToolTip It displays the text when mouse is over the control. Height It is used to set height of the control.

RegularExpressionValidator: Width It is used to set width of the control.


Validates that the input matches a specified pattern using a regular expression. It allows us to check and
validate predictable sequences of characters like: e-mail address, telephone number etc. ShowMessageBox It displays a message box on error in up-level browsers.
The ValidationExpression property is used to specify the regular expression, this expression is used to
validate input control.
ShowSummary It is used to show summary text on the form page.
RegularExpression Properties

Property Description ShowValidationErrors It is used to set whether the validation summary should be shown or not.

ADO.NET Introduction
AccessKey It is used to set keyboard shortcut for the control. It is a module of .Net Framework which is used to establish connection between application and data
sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes that can be used
to connect, retrieve, insert and delete data.
BackColor It is used to set background color of the control.
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes located
into System.Xml.dll.
BorderColor It is used to set border color of the control. ADO.NET has two main components that are used for accessing and manipulating data are the .NET
Framework data provider and the DataSet. .NET Framework Data Providers
Font It is used to set font for the control text. These are the components that are designed for data manipulation and fast access to data. It provides
various objects such as Connection, Command, DataReader and DataAdapter that are used to perform
ForeColor It is used to set color of the control text. database operations. We will have a detailed discussion about Data Providers in new topic.
The DataSet
It is used to access data independently from any data resource. DataSet contains a collection of one or
Text It is used to set text to be shown for the control. more DataTable objects of data. The following diagram shows the relationship between .NET Framework
data provider and DataSet.
ToolTip It displays the text when mouse is over the control.
Which one should we use DataReader or
DataSet?
Visible To set visibility of control on the form. We should consider the following points to use
DataSet. It caches data locally at our application,
Height It is used to set height of the control. so we can manipulate it. It interacts with data
dynamically such as binding to windows forms
control. It allows performing processing on data
Width It is used to set width of the control.
without an open connection. It means it can work
while connection is disconnected.
ErrorMessage It is used to set error message that display when validation fails. If we required some other functionality
mentioned above, we can use DataReader to
ControlToValidate It takes ID of control to validate. improve performance of our application.
DataReader does not perform in disconnected
ValidationExpression It is used to set regular expression to determine validity. mode. It requires DataReader object to
be connected.
RequiredFieldValidator:
Ensures that the user has entered a value in a specified input control. It is used to mandate form control
required and restrict the user to provide data. The ControlToValidateproperty should be set with the ID
of control to validate.
ADO.NET Framework Data Providers
RequiredFieldValidator Properties
Data provider is used to connect to the database, execute commands and retrieve the record. It is
lightweight component with better performance. It also allows us to place the data into DataSet to use it
further in our application. The .NET Framework provides the following data providers that we can use in
Property Description
our application.

AccessKey It is used to set keyboard shortcut for the control. .NET Framework data provider Description

BackColor It is used to set background color of the control.


.NET Framework Data Provider for It provides data access for Microsoft SQL Server. It requires
SQL Server the System.Data.SqlClient namespace.
BorderColor It is used to set border color of the control.
.NET Framework Data Provider for It is used to connect with OLE DB. It requires
Font It is used to set font for the control text. OLE DB the System.Data.OleDb namespace.

ForeColor It is used to set color of the control text. .NET Framework Data Provider for It is used to connect to data sources by using ODBC. It requires
ODBC the System.Data.Odbc namespace.
Text It is used to set text to be shown for the control.
.NET Framework Data Provider for It is used for Oracle data sources. It uses
ToolTip It displays the text when mouse is over the control. Oracle the System.Data.OracleClient namespace.

Visible To set visibility of control on the form. It provides data access for Entity Data Model applications. It
EntityClient Provider
requires the System.Data.EntityClient namespace.
Height It is used to set height of the control.
.NET Framework Data Provider for It provides data access for Microsoft SQL Server Compact 4.0. It
Width It is used to set width of the control. SQL Server Compact 4.0. requires the System.Data.SqlServerCe namespace.

ErrorMessage It is used to set error message that display when validation fails.

ControlToValidate It takes ID of control to validate.


.NET Framework Data Providers Objects Methods
.NET Framework Data Providers are a set of components that provide a consistent way for .NET
applications to interact with various data sources such as databases. These data providers implement
Method Description
the common interfaces defined in ADO.NET (ActiveX Data Objects .NET), which is the set of .NET classes
that facilitate data access.
Close() It is used to closes the SqlDataReader object.
Object Description
GetBoolean(Int32) It is used to get the value of the specified column as a Boolean.

Connection It is used to establish a connection to a specific data source. GetByte(Int32) It is used to get the value of the specified column as a byte.

Command It is used to execute queries to perform database operations. GetChar(Int32) It is used to get the value of the specified column as a single character.

GetDateTime(Int3
It is used to read data from data source. The DbDataReader is a base class for all It is used to get the value of the specified column as a DateTime object.
DataReader 2)
DataReader objects.

GetDecimal(Int32) It is used to get the value of the specified column as a Decimal object.
It populates a DataSet and resolves updates with the data source. The base class for all
DataAdapter
DataAdapter objects is the DbDataAdapter class. It is used to get the value of the specified column as a double-precision floating
GetDouble(Int32)
point number.
ADO.NET DataAdapter
The DataAdapter works as a bridge between a DataSet and a data source to retrieve data. DataAdapter It is used to get the value of the specified column as a single-precision floating
GetFloat(Int32)
is a class that represents a set of SQL commands and a database connection. It can be used to fill the point number.
DataSet and update the data source.
DataAdapter Class Signature GetName(Int32) It is used to get the name of the specified column.
public class DataAdapter : System.ComponentModel.Component, System.Data.IDataAdapter
DataAdapter Constructors
It is used to get a DataTable that describes the column metadata of the
GetSchemaTable()
SqlDataReader.
Constructors Description
GetValue(Int32) It is used to get the value of the specified column in its native format.
DataAdapter() It is used to initialize a new instance of a DataAdapter class.
GetValues(Object[ It is used to populate an array of objects with the column values of the current
DataAdapter(DataAdapt It is used to initializes a new instance of a DataAdapter class from an existing ]) row.
er) object of the same type.
NextResult() It is used to get the next result, when reading the results of SQL statements.
Methods
Read() It is used to read record from the SQL Server database.
Method Description

ADO.NET DataSet
CloneInternals() It is used to create a copy of this instance of DataAdapter.
It is a collection of data tables that contain the data. It is used to fetch data without interacting with a
Data Source that's why, it also known as disconnected data access method. It is an in-memory data
Dispose(Boolean) It is used to release the unmanaged resources used by the DataAdapter.
store that can hold more than one table at the same time. We can use DataRelation object to relate
these tables. The DataSet can also be used to read and write data as XML document.
Fill(DataSet) It is used to add rows in the DataSet to match those in the data source. ADO.NET provides a DataSet class that can be used to create DataSet object. It contains constructors and
methods to perform data related operations.
FillSchema(DataSet, SchemaType, String,
It is used to add a DataTable to the specified DataSet. DataSet Class Signature
IDataReader) public class DataSet : System.ComponentModel.MarshalByValueComponent, System.ComponentModel.I
ListSource,
GetFillParameters()
It is used to get the parameters set by the user when executing an SQL SELECT System.ComponentModel.ISupportInitializeNotification, System.Runtime.Serialization.ISerializable,
statement. System.Xml.Serialization.IXmlSerializable
DataSet Constructors
ResetFillLoadOption() It is used to reset FillLoadOption to its default state.
Constructor Description
ShouldSerializeAcceptChangesDuringFill( It determines whether the AcceptChangesDuringFill property should be persisted
) or not.
DataSet() It is used to initialize a new instance of the DataSet class.
ShouldSerializeFillLoadOption() It determines whether the FillLoadOption property should be persisted or not.
It is used to initialize a new instance of a DataSet class with the given
DataSet(String)
ShouldSerializeTableMappings() It determines whether one or more DataTableMapping objects exist or not. name.

Update(DataSet) It is used to call the respective INSERT, UPDATE, or DELETE statements. DataSet(SerializationInfo, It is used to initialize a new instance of a DataSet class that has the
StreamingContext) given serialization information and context.
ADO.NET SqlDataReader Class
This class is used to read data from SQL Server database. It reads data in forward-only stream of rows DataSet(SerializationInfo,
It is used to initialize a new instance of the DataSet class.
from a SQL Server database. it is sealed class so that cannot be inherited. It inherits DbDataReader class StreamingContext, Boolean)
and implements IDisposable interface.
SqlDataReader Signature DataSet Properties
public class SqlDataReader : System.Data.Common.DbDataReader, IDisposable
SqlDataReader Properties
Properties Description

Property Description
CaseSensitive It is used to check whether DataTable objects are case-sensitive or not.

Connection It is used to get the SqlConnection associated with the SqlDataReader. DataSetName It is used to get or set name of the current DataSet.

Depth It is used to get a value that indicates the depth of nesting for the current row. DefaultViewManag It is used to get a custom view of the data contained in the DataSet to allow
er filtering and searching.
FieldCount It is used to get the number of columns in the current row.
It is used to check whether there are errors in any of the DataTable objects within
HasErrors
It is used to get a value that indicates whether the SqlDataReader contains one or this DataSet.
HasRows
more rows.
IsInitialized It is used to check whether the DataSet is initialized or not.
It is used to retrieve a boolean value that indicates whether the specified
IsClosed
SqlDataReader instance has been closed. It is used to get or set the locale information used to compare strings within the
Locale
table.
It is used to get the value of the specified column in its native format given the
Item[String]
column name. Namespace It is used to get or set the namespace of the DataSet.

It is used to get the value of the specified column in its native format given the Site It is used to get or set an ISite for the DataSet.
Item[Int32]
column ordinal.
Tables It is used to get the collection of tables contained in the DataSet.
It is used to get the number of rows changed, inserted or deleted by execution of the
RecordsAffected
Transact-SQL statement.

VisibleFieldCoun
It is used to get the number of fields in the SqlDataReader that are not hidden.
t

You might also like