.NET Programming Course Overview
.NET Programming Course Overview
.NET PROGRAMMING
Prepared by,
[Link]., [Link]., [Link].,
DEPARTMENT OF INFORMATION
TECHNOLOGY, AKCAS
.NET PROGRAMMING
Unit I
The Creation of C#: C# Relates to the .Net Framework - Common Language
Runtime - Managed vs unmanaged code - An Overview of C#: Object-Oriented
Programming - First Simple Program-Handling Syntax errors - Using code
blocks-semicolon, positioning and Indentation-The C# Keywords-Identifiers-
The .Net Framework Class Library-Data Types, Literals and Variables-
Operators.
Unit II
Program Control Statements: If Statement- switch Statement-For Loop- While
loop do-while loop- foreach loop-using break to exit a loop using continue-
goto- Introducing Classes and objects: Class Fundamentals- objects creation-
Methods-constructors-Garbage Collection and Destructors-Exception Handling.
Unit III
Arrays and Strings: Arrays-Multidimensional Arrays-Jagged Arrays- for each
loop Strings- Methods and classes: Method overloading- Main Method-
Recursion-static Classes Delegates, Events and Lambda Expressions: Delegates
-Lambda Expressions-LINQ
Unit IV
Developing [Link] Applications: Visual Studio: Creating Websites- The
Anatomy of a Web Form – Web Form Fundamentals: Converting HTML Page
to an [Link] Page – Page Class – Web Controls. State Management: View
State - Transferring Information between Pages – Cookies – Session State –
Application State.
Unit V
Validation Controls – AdRotator Control. Working with Data: [Link]
Fundamentals:– Direct Data Access – Disconnected Data Access - Data
Binding: Data Binding with [Link] –Data Source Controls - The Data
Controls: The Grid View – Formatting the GridView – Selecting GridView
Row – Editing, Sorting and Paging the GridView Generating Crystal Reports.
Textbooks
1. Herbert Schildt (2010), C# 4.0 The Complete Reference, Tata McGraw-Hill
Pvt Ltd
2. Mathew MacDonald, (2010), Beginning [Link] 4 in C# 2010, Second
Edition, Apress.
UNIT I
UNIT I
THE CREATION OF C#
1.1 C# Relates to the .Net Framework
Microsoft created the language C#, known as C Sharp, in the year 2000.
C# is an object-oriented programming language that is used in .NET
Framework.
C# is designed to be simple, efficient, and versatile, and is often used to
build a wide range of desktop, web, and mobile applications.
The .NET Framework is a software development framework that
provides a runtime environment and a set of libraries and tools for
building and running applications on Windows operating systems. The
framework includes a variety of programming languages, including C#,
and supports a range of application types, including desktop, web,
mobile, and gaming applications.
The .NET Framework’s basic architecture consists of two key elements:
1. Common Language Runtime (CLR): The Common Language
Runtime is responsible for managing the execution of code written in
any of the
.NET-supported languages. When an application is run, the CLR loads the
required libraries and compiles the code into machine code that can be
executed by the computer’s processor. The CLR also provides a number
of services, such as automatic memory management and security, that
help ensure that applications are reliable and secure.
2. .NET Framework Class Library (FCL): The .NET Framework Class
Library provides a large set of pre-built functions and classes that can be
used to create a wide range of applications. The library includes a variety
of namespaces that provide access to classes that provide features such as
file I/O, networking, database access, and graphical user interface (GUI)
design. The library also includes a number of development tools, such as
the Visual Studio integrated development environment (IDE), which
provides a powerful set of tools for developing and debugging .NET
applications.
.NET is a software framework which is designed and developed by Microsoft. The
first version of .Net framework was 1.0 which came in the year 2002. In easy
words, it is a virtual machine for compiling and executing programs written in
different languages like C#, [Link], etc. It is used to develop Form- based
applications, Web-based applications, and Web services. There is a
.NET PROGRAMMING Page 1
UNIT I
usually written in languages such as C or C++, which are closer to the machine
level than C#.
Characteristics of Unmanaged Code
Some of the main characteristics of unmanaged code are:
Manual memory management: The developer has to allocate and
deallocate memory for unmanaged code manually, using functions such
as malloc() or free(). This gives more control over the memory usage and
performance of the application but also increases the complexity and
responsibility of the developer.
No garbage collection: Unmanaged code does not benefit from garbage
collection, so the developer has to ensure that no memory leaks occur in
the application. Memory leaks can degrade the performance and stability
of the application and cause unexpected errors or crashes.
Potential for memory leaks and vulnerabilities: Unmanaged code can
access any memory location directly without any checks or restrictions
from the CLR. This can lead to memory leaks, corruption, or overflows,
which can compromise the safety and security of the application.
Moreover, unmanaged code can be vulnerable to attacks such as buffer
overflow or injection, which can exploit these weaknesses to execute
malicious or harmful code.
Use Unmanaged Code
Unmanaged code is necessary in some scenarios where the developer needs to
create applications that are.
Platform-specific: Unmanaged code can run only on the platform that it
is compiled for, such as Windows, Linux, or Mac OS. This can increase
the performance and optimization of the application for a specific
platform or environment.
Low-level: Unmanaged code can access low-level features and resources
that are not available or restricted in managed code, such as device
drivers, kernel modules, or embedded systems. These features can enable
direct interaction with hardware resources or operating system functions.
Interoperable with native libraries: Unmanaged code can interoperate
with native libraries or frameworks that are written in languages other
than C#, such as Win32 API, DirectX, or OpenGL. These libraries or
Sr.
Key Managed Code Unmanaged code
No.
Executed by CLR, Common
Executed by Operating System
Executed Language Runtime, also named
1 directly on the underlying
By as Managed Runtime
hardware.
Environment.
CLR handles security concerns andNo inbuilt security present. It is
2 Security provides inbuilt security to code developer's responsibility to
written in .NET. write safe and secure code.
Memory buffer overflow never
Memory buffer overflow can occur
Memory happens, as CLR handles
3 and can hamper the program
Overflow memory allocation and
execution badly.
deallocation automatically.
4 Runtime CLR provides automatic garbage
No automatic garbage collection
Sr.
Key Managed Code Unmanaged code
No.
Services collection, exception handling to and other services are provided
managed code. to unmanaged code.
Managed Code is converted to
Unmanaged Code is converted to
5 Output IL, Intermiddiate Language also
native language code.
termed as CIL of MSIL.
Low Programmer can write low level
Programmer has no low level
6 Level access code using unmanaged
access using Managed Code.
Access code.
An Overview of C#
C# (pronounced as C sharp) is a general-purpose, object-oriented programming
language. It is one of the most popular languages used for developing desktop
and web applications.
Features of C# Programming
Simple to write and understand
The code written in C# is much simpler and easier to understand. It is
syntactically very similar to Java. Hence, for a person with experience in Java,
C# won't be a difficult language to learn.
Object-oriented
Like Java and C++, C# is an object-oriented programming language. It supports
the features of object-oriented paradigms such as objects, classes, inheritance,
polymorphism, etc.
Type-Safe
A type-safe language ensures that each variable of a particular type does not
hold values of other types. For example, an integer variable will not hold
character values.
Modern
C# is a modern and powerful language that allows developers to build robust
applications quickly and easily. It is built based on the current trend.
Example: C# Inheritance
using System;
namespace Inheritance {
// base class
class Animal
{
public string name;
public void display() {
[Link]("I am an animal");
}
}
// derived class of Animal
class Dog : Animal {
public void getName()
{ [Link]("My name is " + name);
}
}
class Program {
static void Main(string[] args) {
// object of derived class
Dog labrador = new Dog();
// access field and method of base class
[Link] = "Rohu";
[Link]();
// access method from own class
[Link]();
[Link]();
}
}
}
Output
I am an animal
My name
In is Rohu example, we have derived
the above a subclass Dog from the
superclass Animal. Notice the statements,
[Link] =
"Rohu";
[Link]();
Here, we are using labrador (object of Dog) to access the name and display() of
the Animal class. This is possible because the derived class inherits all fields
.NET PROGRAMMING Page 11
UNIT I
and methods of the base class.
Also, we have accessed the name field inside the method of the Dog class.
is-a relationship
In C#, inheritance is an is-a relationship. We use inheritance only if there is an
is-a relationship between two classes. For example,
Dog is an Animal
Apple is a Fruit
Car is a Vehicle
We can derive Dog from Animal class. Similarly, Apple from Fruit
class and Car from Vehicle class.
Types of inheritance
There are the following types of inheritance:
1. Single Inheritance
In single inheritance, a single derived class inherits from a single base class.
C# Single Inheritance
2. Multilevel Inheritance
In multilevel inheritance, a derived class inherits from a base and then the same
derived class acts as a base class for another class.
C# Multilevel Inheritance
3. Hierarchical Inheritance
In hierarchical inheritance, multiple derived classes inherit from a single base
class.
C# Hierarchical Inheritance
4. Multiple Inheritance
In multiple inheritance, a single derived class inherits from multiple base
classes. C# doesn't support multiple inheritance. However, we can achieve
multiple inheritance through interfaces.
Multiple Inheritance
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. The
combination of multilevel and hierarchical inheritance is an example of Hybrid
inheritance.
2. Encapsulation
Consider a gift box that contains a gift. The gift box acts as a container that
encapsulates the gift. The gift is hidden from the outside world and can only be
3. Polymorphism
Polymorphism is a core concept in object-oriented programming that allows
objects of different classes to be treated as objects of a common super class. It
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
[Link]("Hello World!");
}
}
}
Result:
Hello World!
Example explained
Line 1: using System means that we can use classes from
the System namespace.
Line 2: A blank line. C# ignores white space. However, multiple lines makes the
code more readable.
Line 3: namespace is used to organize your code, and it is a container for classes
and other namespaces.
Line 4: The curly braces {} marks the beginning and the end of a block of code.
Line 5: class is a container for data and methods, which brings functionality to
your program. Every line of code that runs in C# must be inside a class. In our
example, we named the class Program.
Line 7: Another thing that always appear in a C# program is the Main method.
Any code inside its curly brackets {} will be executed. You don't have to
understand the keywords before and after Main. You will get to know them bit
by bit while reading this tutorial.
Line 9: Console is a class of the System namespace, which has
a WriteLine() method that is used to output/print text. In our example, it will
output "Hello World!".
If you omit the using System line, you would have to
write [Link]() to print/output text.
9
From the New Project popup, shown below, select Visual C# in the left side
panel and select the Console App in the right-side panel.
C#
Console Program
Every console application starts from the Main() method of the Program class.
The following example displays "Hello World!!" on the console.
Example: C# Console Application
using System;
using [Link];
using [Link];
using [Link];
using [Link];
namespace CSharpTutorials
{
class Program
{
static void Main(string[] args)
{
string message = "Hello World!!";
[Link](message);
}
}
}
The following image illustrates the important parts of the above example.
C# Code Structure
using System;
int i, j, d;
i = 5;
j = 10;
using a case statement. The case statement can consist of multiple lines of code,
and ends when the system encounters the break keyword.
switch(variable)
{
case value1:
executeThis();
executeThat();
break;
case value2:
executeThisOtherThing();
break;
default:
break;
}
For example, let's imagine we have a company that is sponsoring us for a
tournament of some kind. We want to display the company a message, but we
need it to be a different message for each level of sponsorship that we offer. We
might implement a switch statement to output the correct message for each
sponsorship level:
Loops
In C#, loops are code blocks that are executed multiple times. The exact number
of times they are executed can differ, or be dependent on a variable, or on a
collection of objects.
There are four ways to implement a loop in C#, and they each have a distinct
use.
For Loop
A for loop is a loop that executes once for each value in a given range. The loop
must define a variable (commonly named i or j, termed the initializer);
a condition where the loop will execute again so long as the condition is true;
and an iterator which defines by how much the initializer will change after
every loop.
A common kind of for loop uses integers and a simple increment.
for(int i = 0; //Initializer
i < 10; //Condition
i++) //Iterator
{
//This code will execute ten times,
//one each for i = 0, i = 1, up to and including i = 9.
}
Foreach Loop
When dealing with collections of objects (such as an array or a List<T>; both of
which will be discussed later in this series), we can use a foreach loop to iterate
over every object in the collection. In this case, the iterator object is of the same
type as objects in said collection.
var items = new int[] {4, 5, 6, 7, 8};
foreach(int item in items)
{
[Link](item);
}
//Example class
public class Drawing
{
public string Name { get; set; }
}
{
[Link]([Link]);
}
Using a foreach loop to iterate over a collection is the most common scenario
for this kind of loop.
While Loop
A while loop evaluates a condition, and so long as that condition is true, the
loop will keep executing.
int myVal = 5;
while(myVal < 1000)
{
DoSomething();
DoSomethingElse();
//We didn't increment myVal, so this loop will never stop executing!
}
Because a while loop evaluates the condition before entering the loop, if that
condition is false before the loop starts, the loop will not be executed.
Do While Loop
By contrast, a do while loop will always execute at least once, because the
condition is evaluated at the end of the loop.
int myVal = 1;
do
{
DoSomething();
DoSomethingElse();
myVal++;
} while (myVal < 1000);
If you must guarantee that the code in a loop run at least one time, use a do
while loop.
Breaking the Loop
In many situations, we may want to stop executing the loop before the loop
reaches its end condition. There are several keywords we can use for these
situations.
Break
.NET PROGRAMMING Page 28
UNIT I
The break keyword ends execution of the loop. No further iterations of the loop
will execute.
for(int i = 0; i < 10; i++)
{
if(i == 7)
{
break; //Will exit the for loop
}
}
You might have noticed that this keyword was also used in the switch statement
examples above, and its function was similar there.
Continue
The continue keyword ends execution of the current iteration of the loop, but
will restart the loop at the next iteration.
int myVal = 5;
while (myVal <
10)
{
if (myVal == 7)
{
myVal++;
continue; //If i == 7, processing stops here and resumes
//at the top of the loop with the next value 8.
//[Link] is never called in that case.
}
//The below output will not happen when myVal = 7
[Link]("The current value of myVal is " + [Link]());
myVal++;
}Return
The return keyword, similarly to how it works in methods, will return a value to
the calling code. The loop will therefore stop executing.
var emails = GetEmails(); //Method not defined here
Positioning
Braces ({}): The positioning of braces can follow different styles, such as
Allman (braces on a new line) or K&R (braces on the same line).
Allman Style:
void MyMethod()
{
if (condition)
{
// code
}
}
K&R Style:
void MyMethod()
{ if (condition) {
// code
}
}
Indentation
Indentation: Proper indentation improves code readability. In C#, the
typical indentation is 4 spaces per indentation level.
Indentation Options:
o Block Contents: Indent the contents of blocks (e.g., methods,
loops).
o Case Contents: Indent the contents of case statements within a
switch.
o Labels: Indent labels in switch statements.
o Braces: Decide whether to indent braces or not.
Example:
void MyMethod()
{
if (condition)
{
// Indented block
[Link]("Hello, World!");
}
}
1.9 THE C# KEYWORDS
Keywords or Reserved words are the words in a language that are used for
some internal process or represent some predefined actions. These words are
therefore not allowed to use as variable names or objects. Doing this will result
in a compile-time error.
Example:
class GFG {
}
}
Output:
The value of a is: 10
There are total 78 keywords in C# as follows:
Example:
class GFG {
}
}
Output:
The value of a is: 47
The value of b is: True
2. Reference Type Keywords: There are 6 keywords in reference types
which are used to store references of the data or objects. The keywords in
this category are: class, delegate, interface, object, string, void.
virtual volatile
Example:
}
// Main Method
static void Main(string[] args)
{ Mod obj1 = new Mod();
// access to public members
obj1.n1 = 77;
[Link]("Value of n1: {0}", obj1.n1);
Output:
Value of n1: 77
4. Statements Keywords: There are total 18 keywords which are used in
program instructions.
Example:
class demoContinue
{
public static void Main()
{
[Link]("GeeksforGeeks");
}
}
}
Output:
GeeksforGeeks
5. Method Parameters Keywords: There are total 4 keywords which are
used to change the behavior of the parameters that passed to a method.
The keyword includes in this category are: params, in, ref, out.
7. Operator Keywords: There are total 8 keywords which are used for
different purposes like creating objects, getting a size of object etc. The
keywords are: as, is, new, sizeof, typeof, true, false, stackalloc.
using System;
class GFG {
}
}
Output:
The value of a is: 10
The value of a is: 11
1.10 IDENTIFIERS
Identifiers are the name given to entities such as variables, methods,
classes, etc. They are tokens in a program which uniquely identify an
element. For example,
int value;
Here, value is the name of variable. Hence it is an identifier. Reserved
keywords can not be used as identifiers unless @ is added as prefix. For
example,
int break;
This statement will generate an error in compile time.
Rules for Naming an Identifier
An identifier can not be a C# keyword.
Identifiers Remarks
number Valid
calculateMarks Valid
name1 Valid
_hello_hi Valid
{
static void Main(string[] args)
{
[Link]("Hello World!");
}
}
}
Keywords Identifiers
using System
void args
string Console
WriteLine
Namespaces Description
[Link], [Link],
[Link], These are used to access a database,
[Link], perform commands on a
[Link] database and retrieve database.
[Link], [Link],
These are used to access, read
[Link]
and write files.
[Link], [Link],
[Link],
[Link],
[Link], These are used to create ASP.
[Link], NET Web applications that run
[Link], over the web.
[Link],
[Link],
[Link]
[Link],
These are used to create XML
[Link],
Web services and components
[Link],
that can be published over the
[Link],
web.
[Link]
[Link],
[Link], These are used for
[Link], authentication, authorization,
[Link], and encryption purpose.
[Link]
[Link], [Link],
[Link], These namespaces are used to
[Link], create and access XML files.
[Link]
-2,147,483,648 to -
int 4 byte
2,147,483,647
-2,147,483,648 to -
signed int 4 byte
2,147,483,647
?9,223,372,036,854,775,808
long 8 byte to
9,223,372,036,854,775,807
?9,223,372,036,854,775,808
signed long 8 byte to
9,223,372,036,854,775,807
0 -
unsigned long 8 byte
18,446,744,073,709,551,615
Declaring a pointer
The pointer in C# language can be declared using * (asterisk symbol).
1. int * a; //pointer to int
2. char * c; //pointer to char
// C# program to demonstrate
// the above data types
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
static void Main()
{
// declaring character
char a = 'G';
short s = 56;
ushort us = 76;
// this will give error as number is
// larger than short range
}
}
}
output:
char: G
integer: 89
short: 56
long: 4564
float: 3.733064
double: 8.358674532
decimal: 389.5
Unsinged integer: 95
Unsinged short: 76
Unsinged long: 3624573
1.12.3 LITERALS
C# literals are fixed values (or hard-coded values) assigned to variables
that cannot be changed during program execution.
They represent various types of constants such as integers, floats, chars,
and strings.
Integer literals can be in decimal, binary, octal, or hexadecimal format.
Floating-point literals represent numbers with fractional parts.
Character literals represent individual characters, whereas string literals
represent sequences.
Boolean literals are 'true' or 'false', and 'null' represents absence.
By providing direct, recognizable values for data initialization and
manipulation, C# literals enhance code clarity and efficiency.
Example:
x = 100;
In this example, x is a variable that holds the value 100, which is a literal value.
The assignment of a literal value to a variable allows you to store and
manipulate data in your program.
Top 5 Types of Literals in
C# Integer Literals
Character Literals
Character literals are enclosed within single quotes (''). There are three ways to
represent character literals.
Single Quote: Character literals can be expressed as individual
characters within single quotes.
char ch = 'A'; // Character 'A'
Unicode Representation: Character literals can also be created using
Unicode representation, which includes using the syntax uxxxx,
where xxxx represents hexadecimal values.
char ch = '\u0041'; // Unicode representation of 'A'
Escape Sequence: Certain escape characters are recognized as character
literals, allowing you to represent special characters using escape
sequences.
char ch = '\n'; // Newline character
The following are various escape sequence literals and their meanings.
Escape Sequence Meaning
\ \ character
\’ ‘ character
? ? character
\” ” character
\b Backspace
\a Alert or Bell
\n New Line
\f Form Feed
\r Carriage Return
\v Vertical Tab
\xhh Hexadecimal number
String Literals
String literals are enclosed in double quotations (""). They can also start
with @"", making it simpler to handle large lines by breaking them into
multiple lines with string literals and separating them with spaces.
Example:
string str1 = "Hello, world!"; // String literal
string str2 = @"This is a long
string."; // Verbatim string literal
Boolean Literals
Boolean literals are restricted to just two values: true and false.
Example:
bool a = true;
bool b = false;
Examples of C# Literals
The examples below demonstrate how to implement all of the literals in C#.
Example 1: Integer Literal
using System;
class Scaler
{
public static void Main(String[] args)
{
// decimal literal
int a = 10;
// octal literal
int b = 062;
// Hexadecimal literal
int c = 0x132f;
// binary literal
int d = 0b101;
[Link](a);
[Link](b);
[Link](c);
[Link](d);
}
}
Output:
10
62
4911
5
Explanation:
The above C# code demonstrates the use of multiple integer literals and their
values. It uses variables to store these literals: a decimal literal (10), an octal
literal (062, which is equivalent to 50 in decimal), a hexadecimal literal
(0x132f0x132f, which is equivalent to 4911 in decimal), and a binary literal
(0b101, which is equivalent to 5 in decimal). The code then prints these values
using the [Link] statements.
Example 2: Floating Point Literal
using System;
class Scaler
{
public static void Main(String[] args)
{
double a = 632.281;
double b = 0574.951;
double c = 243183E-4F;
[Link](a);
[Link](b);
[Link](c);
}
}
Output:
632.281
574.951
24.3183002471924
class Scaler
{
public static void Main(String[] args)
{
char ch1 = 'a';
char ch2 = '\u0071';
[Link](ch1);
[Link](ch2);
[Link]("Hello\nWorld\t!");
}
}
Output:
a
q
Hello
World !
Explanation:
The above C# code initializes two character variables ch1 and ch2. The
character literal 'a' is allocated to ch1, while the Unicode representation of 'q' is
assigned to ch2 using the escape sequence u0071. The [Link]
statements then output the values of ch1 and ch2. Additionally, the last
[Link] statement prints the string "Hello" followed by a newline (\
n) and then "World" followed by a tab (\t) and finally an exclamation mark,
resulting in the formatted output "Hello\nWorld\t!".
Example 4: String Literal
using System;
class Scaler
{
public static void Main(String[] args)
{
string str1 = "Hello, world!"; // String literal
string str2 = @"This is a long string."; // Verbatim string literal
[Link](str1);
[Link](str2);
}
}
Output:
Hello, world!
This is a long string.
Explanation:
The C# code above declares two string variables, str1 and str2. The string literal
"Hello, world!" is assigned to str1, while the string literal @"This is a long
string." is assigned to str2. The values of str1 and str2 are then printed by the
[Link] statements, resulting in the display of the respective string
literals.
Example 5: Boolean Type Literal
using System;
class Scaler
{
public static void Main(String[] args)
{
bool a = true;
bool b = false;
[Link](a);
[Link](b);
}
}
Output:
True
False
1.12.3 VARIABLES
A variable is a symbolic name given to a memory location. Variables are used to
store data in a computer program.
How to declare variables in C#
Here's an example to declare a variable in C#.
int age;
In this example, a variable age of type int (integer) is declared and it can only
store integer values.
We can assign a value to the variable later in our program like such:
int age;
... ... ...
age = 24;
However, the variable can also be initialized to some value during declaration.
For example,
int age = 24;
Here, a variable age of type int is declared and initialized to 24 at the same
time. Since, it’s a variable, we can change the value of variables as well. For
example, int age = 24;
age = 35;
Here, the value of age is changed to 35 from 24.
Variables in C# must be declared before they can be used. This means, the name
and type of variable must be known before they can be assigned a value. This is
why C# is called a statically-typed language.
Once declared, the datatype of a variable can not be changed within a scope. A
scope can be thought as a block of code where the variable is visible or
available to use. If you don’t understand the previous statement, don’t worry
we’ll learn about scopes in the later chapters.
For now remember,we can not do the following in C#:
int age;
age = 24;
... ... ...
float age;
Implicitly typed variables
Alternatively in C#, we can declare a variable without knowing its type
using var keyword. Such variables are called implicitly typed local variables.
Variables declared using var keyword must be initialized at the time of
declaration.
var value = 5;
The compiler determines the type of variable from the value that is assigned to
the variable. In the above example, value is of type int. This is equivalent to:
int value;
value = 5;
You can learn more about implicitly typed local variables.
Rules for Naming Variables in C#
There are certain rules we need to follow while naming a variable. The rules for
naming a variable in C# are:
1. The variable name can contain letters (uppercase and lowercase),
underscore( _ ) and digits only.
2. The variable name must start with either letter, underscore or @ symbol.
For example,
Variable
Remarks
Names
Variable
Remarks
Names
name Valid
subject101 Valid
your_name Valid
Local Variables in C#
Local variables in C# are variables declared within a method, constructor, or block
of code. They have limited scope and are accessible only within the block where
they are declared. Local variables must be initialized before use and are often
used for temporary storage of data in a program.
Example
using System;class StudentDetails {
public void StudentAge()
{
int age = 0;
age = age + 10;
[Link]("Student age is : " + age);
}
public static void Main(String[] args)
{
StudentDetails obj = new StudentDetails();
[Link]();
}
}
Explanation
This C# code defines a class named "StudentDetails" with a method
"StudentAge" that increments a local variable "age" by 10 and prints the result.
The Main method creates an instance of the class and calls the "StudentAge"
method, displaying the student's age as 10
Output
Student age is: 10
Instance Variables or Non-Static Variables
In C#, instance variables are data members declared within a class but outside
of any method. They represent the attributes or properties of objects created
from the class. Each object instance has its own set of instance variables, which
define the object's state and behaviour.
Example
using System;
class Marks
{
int engMarks;
int mathsMarks;
int phyMarks;
[Link]([Link]);
Explanation
This C# program defines a class "Marks" with three instance variables
(engMarks, mathsMarks, and phyMarks) to store subject marks. It creates two
objects (obj1 and obj2), assigns different marks to each object, and displays the
marks for both objects using [Link], demonstrates the use of
instance variables to store and access data for different instances of the class.
Output
Marks for first object:
89
76
65
Marks for second object:
85
98
91
Static Variables or Class Variables
In C#, static variables are class-level variables that belong to the type itself
rather than to specific instances of the class. They are shared among all
instances of the class and retain their values throughout the program's
execution, providing a common storage location for all objects of that class.
Example
using System;
class Emp {static double salary;
static String name = "Rohan";
Explanation
This C# program defines a class "Emp" with static variables "salary" and
"name." It sets the static salary to 125000 and the name to "Rohan." In the Main
method, it prints the name and average salary using the static variables. Static
variables are shared among all instances of the class and can be accessed using
the class name.
Output
Rohan's average salary:125000
Constant Variables
In C#, a constant variable is a value that cannot be changed once it's defined. It's
declared using the 'const' keyword and must be initialized at the time of
declaration. Constants are typically used for values that should remain fixed
throughout the program, such as mathematical constants or configuration
settings, providing improved code readability and preventing accidental
modification.
Example
using System;
class Program
{
Explanation
This C# program in the C# Editor attempts to declare a constant variable "max"
of type float without providing an initial value. However, this will result in a
compilation error because constant variables must have a defined value at the
time of declaration. Additionally, it attempts to access an undefined constant
"b," which will also result in an error.
Output
The provided C# code has a compilation error because you cannot declare a
constant variable without initializing it with a value.
Read-only Variables
In C#, read-only variables are declared using the "readonly" keyword. They can
only be assigned a value at the time of declaration or within a constructor. Once
assigned, their value cannot be changed throughout the program's execution,
ensuring data integrity and immutability. This is useful for constants and values
that should not be modified after initialization.
Example
using System;
class Program
{
int a = 80;
static int b = 40;
const float max = 50;
readonly int k;
Explanation
This C# program demonstrates the use of instance variables (a), static variables
(b), constant variables (max), and readonly variables (k). It initializes a, b, and
max but doesn't initialize k, which is allowed for readonly variables. The
program then prints the values of these variables.
Output
The value of a is = 80
The value of b is = 40
The value of max is = 50
The value of k is = 0
1.13 OPERATORS
Operators allow us to perform different kinds of operations on operands.
In C#, operators Can be categorized based upon their different functionality :
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Conditional Operator
In C#, Operators can also categorized based upon Number of Operands :
Unary Operator: Operator that takes one operand to perform the
operation.
Binary Operator: Operator that takes two operands to perform the
operation.
Ternary Operator: Operator that takes three operands to perform the
operation.
1. Arithmetic Operators
These are used to perform arithmetic/mathematical operations on operands. The
Binary Operators falling in this category are :
Addition: The ‘+’ operator adds two operands. For example, x+y.
Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
Multiplication: The ‘*’ operator multiplies two operands. For
example, x*y.
Division: The ‘/’ operator divides the first operand by the second. For
example, x/y.
Modulus: The ‘%’ operator returns the remainder when first operand is
divided by the second. For example, x%y.
Example:
C#
// C# program to demonstrate the working
// of Binary Arithmetic Operators
using System;
namespace Arithmetic
{
class GFG
{
// Main Function
static void Main(string[] args)
{
int result;
int x = 10, y = 5;
// Addition
result = (x + y);
[Link]("Addition Operator: " + result);
// Subtraction
result = (x - y);
[Link]("Subtraction Operator: " + result);
// Multiplication
result = (x * y);
[Link]("Multiplication Operator: "+ result);
// Division
result = (x / y);
[Link]("Division Operator: " + result);
// Modulo
result = (x % y);
[Link]("Modulo Operator: " + result);
}
}
}
Output:
Addition Operator: 15
Subtraction Operator: 5
Multiplication Operator: 50
Division Operator: 2
Modulo Operator: 0
The ones falling into the category of Unary Operators are:
Increment: The ‘++’ operator is used to increment the value of an
integer. When placed before the variable name (also called pre-
increment operator), its value is incremented instantly. For
example, ++x.
And when it is placed after the variable name (also called post-
increment operator), its value is preserved temporarily until the
execution of this statement and it gets updated before the execution of the
next statement. For example, x++.
Decrement: The ‘- -‘ operator is used to decrement the value of an
integer. When placed before the variable name (also called pre-
decrement operator), its value is decremented instantly. For example, –
- x.
And when it is placed after the variable name (also called post-
decrement operator), its value is preserved temporarily until the
execution of this statement and it gets updated before the execution of the
next statement. For example, x- –.
Example:
C#
.NET PROGRAMMING Page 66
UNIT I
class GFG {
// Main Function
static void Main(string[] args)
{
// post-increment example:
// res is assigned 10 only,
// a is not updated yet
res = a++;
// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
// pre-increment example:
// res is assigned 11 now since a
// is updated here itself
res = ++a;
// pre-decrement example:
.NET PROGRAMMING Page 67
UNIT I
}
}
}
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10
2. Relational Operators
Relational operators are used for comparison of two values. Let’s see them one
by one:
‘=='(Equal To) operator checks whether the two given operands are
equal or not. If so, it returns true. Otherwise it returns false. For
example, 5==5 will return true.
‘!='(Not Equal To) operator checks whether the two given operands are
equal or not. If not, it returns true. Otherwise it returns false. It is the
exact boolean complement of the ‘==’ operator. For example, 5!=5 will
return false.
‘>'(Greater Than) operator checks whether the first operand is greater
than the second operand. If so, it returns true. Otherwise it returns false.
For example, 6>5 will return true.
‘<‘(Less Than) operator checks whether the first operand is lesser than
the second operand. If so, it returns true. Otherwise it returns false. For
example, 6<5 will return false.
‘>='(Greater Than Equal To) operator checks whether the first operand
is greater than or equal to the second operand. If so, it returns true.
Otherwise it returns false. For example, 5>=5 will return true.
‘<='(Less Than Equal To) operator checks whether the first operand is
lesser than or equal to the second operand. If so, it returns true. Otherwise
it returns false. For example, 5<=5 will also return true.
Example:
C#
// C# program to demonstrate the working
// of Relational Operators
using System;
namespace Relational {
class GFG {
// Main Function
static void Main(string[] args)
{
bool result;
int x = 5, y = 10;
// Equal to Operator
result = (x == y);
[Link]("Equal to Operator: " + result);
result = (x != y);
[Link]("Not Equal to Operator: " + result);
}
}
}
Output:
Equal to Operator: False
Greater than Operator: False
Less than Operator: True
Greater than or Equal to: False
Lesser than or Equal to: True
Not Equal to Operator: True
3. Logical Operators
They are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. They are described
below:
Logical AND: The ‘&&’ operator returns true when both the conditions
in consideration are satisfied. Otherwise it returns false. For example, a
&& b returns true when both a and b are true (i.e. non-zero).
Logical OR: The ‘||’ operator returns true when one (or both) of the
conditions in consideration is satisfied. Otherwise it returns false. For
example, a || b returns true if one of a or b is true (i.e. non-zero). Of
course, it returns true when both a and b are true.
Logical NOT: The ‘!’ operator returns true the condition in consideration
is not satisfied. Otherwise it returns false. For example, !a returns true if a
is false, i.e. when a=0.
Example:
C#
// C# program to demonstrate the working
// of Logical Operators
using System;
namespace Logical {
class GFG {
// Main Function
static void Main(string[] args)
{
bool a = true,b = false, result;
// AND operator
result = a && b;
[Link]("AND Operator: " + result);
// OR operator
result = a || b;
[Link]("OR Operator: " + result);
// NOT operator
result = !a;
[Link]("NOT Operator: " + result);
}
}
}
Output:
AND Operator: False
OR Operator: True
NOT Operator: False
4. Bitwise Operators
In C#, there are 6 bitwise operators which work at bit level or used to perform
bit by bit operations. Following are the bitwise operators :
& (bitwise AND) Takes two numbers as operands and does AND on
every bit of two numbers. The result of AND is 1 only if both bits are 1.
| (bitwise OR) Takes two numbers as operands and does OR on every bit
of two numbers. The result of OR is 1 any of the two bits is 1.
^ (bitwise XOR) Takes two numbers as operands and does XOR on
every bit of two numbers. The result of XOR is 1 if the two bits are
different.
~ (bitwise Complement) Takes one number as operand and invert each
bits that is 1 to 0 and 0 to 1.
<< (left shift) Takes two numbers, left shifts the bits of the first operand,
the second operand decides the number of places to shift.
>> (right shift) Takes two numbers, right shifts the bits of the first
operand, the second operand decides the number of places to shift.
Example:
C#
// C# program to demonstrate the working
// of Bitwise Operators
using System;
namespace Bitwise {
class GFG {
// Main Function
static void Main(string[] args)
{
int x = 5, y = 10, result;
// Bitwise OR Operator
result = x | y;
[Link]("Bitwise OR: " + result);
}
}
}
Output:
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1
5. Assignment Operators
Assignment operators are used to assigning a value to a variable. The left side
operand of the assignment operator is a variable and right side operand of the
assignment operator is a value. The value on the right side must be of the same
data-type of the variable on the left side otherwise the compiler will raise an
error.
Different types of assignment operators are shown below:
“=”(Simple Assignment): This is the simplest assignment operator. This
operator is used to assign the value on the right to the variable on the left.
Example:
a = 10;
b = 20;
ch = 'y';
“+=”(Add Assignment): This operator is combination of ‘+’ and ‘=’
operators. This operator first adds the current value of the variable on left
to the value on the right and then assigns the result to the variable on the
left.
Example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
“-=”(Subtract Assignment): This operator is combination of ‘-‘ and ‘=’
operators. This operator first subtracts the current value of the variable on
left from the value on the right and then assigns the result to the variable
class GFG {
// Main Function
static void Main(string[] args)
{
// initialize variable x
// using Simple Assignment
// Operator "="
int x = 15;
// it means x = x + 10
x += 10;
[Link]("Add Assignment Operator: " + x);
// it means x = x - 5
x -= 5;
[Link]("Subtract Assignment Operator: " + x);
// it means x = x * 5
x *= 5;
[Link]("Multiply Assignment Operator: " + x);
// it means x = x / 5
x /= 5;
[Link]("Division Assignment Operator: " + x);
// it means x = x % 5
x %= 5;
[Link]("Modulo Assignment Operator: " + x);
// it means x = x << 2
x <<= 2;
[Link]("Left Shift Assignment Operator: " + x);
// it means x = x >> 2
x >>= 2;
[Link]("Right Shift Assignment Operator: " + x);
// it means x = x >> 4
x &= 4;
[Link]("Bitwise AND Assignment Operator: " + x);
// it means x = x >> 4
x ^= 4;
[Link]("Bitwise Exclusive OR Assignment Operator: " + x);
// it means x = x >> 4
x |= 4;
[Link]("Bitwise Inclusive OR Assignment Operator: " + x);
}
.NET PROGRAMMING Page 77
UNIT I
}
}
Output :
Add Assignment Operator: 25
Subtract Assignment Operator: 15
Multiply Assignment Operator: 75
Division Assignment Operator: 5
Modulo Assignment Operator: 0
Left Shift Assignment Operator: 32
Right Shift Assignment Operator: 2
Bitwise AND Assignment Operator: 4
Bitwise Exclusive OR Assignment Operator: 8
Bitwise Inclusive OR Assignment Operator: 12
6. Conditional Operator
It is ternary operator which is a shorthand version of if-else statement. It has
three operands and hence the name ternary. It will return one of two values
depending on the value of a Boolean expression.
Syntax:
condition ? first_expression : second_expression;
Explanation:
condition: It must be evaluated to true or false.
If the condition is true
first_expression is evaluated and becomes the result.
If the condition is false,
second_expression is evaluated and becomes the result.
Example:
C#
// C# program to demonstrate the working
// of Conditional Operator
using System;
namespace Conditional {
class GFG {
// Main Function
static void Main(string[] args)
{
UNIT II
PROGRAM CONTROL STATEMENTS
2.1 IF STATEMENTS
if Statement
C# if-then statement will execute a block of code if the given condition is true.
The syntax of if-then statement in C# is:
if (boolean-expression)
{
// statements executed if boolean-expression is true
}
The boolean-expression will return either true or false.
If the boolean-expression returns true, the statements inside the body of if
( inside {...} ) will be executed.
If the boolean-expression returns false, the statements inside the body of
if will be ignored.
Example 1: C# if Statement
using System;
namespace Conditional
{
class IfStatement
{
public static void Main(string[] args)
{
int number = 2;
if (number < 5)
{
[Link]("hii”);
}
if (number < 5)
{
[Link](“hii);
}
else
{
[Link]("hello”);
}
Here, the value of number is initialized to 12. So the expression number < 5 is
evaluated to false. Hence, the code inside the else block are executed. The code
after the if..else statement will always be executed irrespective to the
expression.
if...else if Statement
When we have only one condition to test, if-then and if-then-else statement
works fine. But what if we have a multiple condition to test and execute one of
the many block of code.
For such case, we can use if..else if statement in C#. The syntax for if...else if
statement is:
if (boolean-expression-1)
{
// statements executed if boolean-expression-1 is true
}
else if (boolean-expression-2)
{
// statements executed if boolean-expression-2 is true
}
else if (boolean-expression-3)
{
// statements executed if boolean-expression-3 is true
}
.
.
.
else
{
// statements executed if all above expressions are false
}
The if...else if statement is executed from the top to bottom. As soon as a test
expression is true, the code inside of that if ( or else if ) block is executed. Then
the control jumps out of the if...else if block.
If none of the expression is true, the code inside the else block is executed.
Example 3: C# if...else if Statement
using System;
namespace Conditional
{
class IfElseIfStatement
{
public static void Main(string[] args)
{
int number = 12;
if (number < 5)
{
[Link]("{0} is less than 5", number);
}
else if (number > 5)
{
[Link]("{0} is greater than 5", number);
}
else
{
[Link]("{0} is equal to 5");
}
}
}
}
When we run the program, the output will be:
12 is greater than 5
The value of number is initialized to 12. The first test expression number <
5 is false, so the control will move to the else if block. The test
expression number > 5 is true hence the block of code inside else if will be
executed.
Similarly, we can change the value of number to alter the flow of execution.
Nested if...else Statement
An if...else statement can exist within another if...else statement. Such
statements are called nested if...else statement.
The general structure of nested if…else statement is:
if (boolean-expression)
{
if (nested-expression-1)
{
// code to be executed
}
else
{
// code to be executed
}
}
else
{
if (nested-expression-2)
{
// code to be executed
}
else
{
// code to be executed
}
}
Nested if statements are generally used when we have to test one condition
followed by another. In a nested if statement, if the outer if statement returns
true, it enters the body to check the inner if statement.
Example 4: Nested if...else Statement
The following program computes the largest number among 3 numbers using
nested if...else statement.
using System;
namespace Conditional
{
class Nested
{
public static void Main(string[] args)
{
int first = 7, second = -23, third = 13;
if (first > second)
{
if (firstNumber > third)
{
[Link]("{0} is the largest", first);
}
.NET PROGRAMMING Page 85
UNIT II
else
{
[Link]("{0} is the largest", third);
}
}
else
{
if (second > third)
{
[Link]("{0} is the largest",
second);
}
else
{
[Link]("{0} is the largest", third);
}
}
}
}
}
When we run the program, the output will be:
13 is the largest
// C# program to illustrate
// switch case statement
using System;
// Main Method
public static void Main(String[] args)
{
int nitem = 5;
switch (nitem) {
case 1:
[Link]("case 1");
break;
case 5:
[Link]("case 5");
break;
case 9:
[Link]("case 9");
break;
default:
[Link]("No match
found"); break;
}
}
}
Output:
case 5
Example:
csharp
// C# program to illustrate while loop
using System;
class whileLoopDemo
{
public static void Main()
{
int x = 1;
2. for loop
for loop has similar functionality as while loop but with different syntax. for
loops are preferred when the number of times loop statements are to be
executed is known beforehand. The loop variable initialization, condition to be
tested, and increment/decrement of the loop variable is done in one line in for
loop thereby providing a shorter, easy to debug structure of looping.
for (loop variable initialization ; testing condition;
increment / decrement)
{
// statements to be executed
}
1.
1. Initialization of loop variable: Th expression / variable controlling the loop
is initialized here. It is the starting point of for loop. An already declared
variable can be used or a variable can be declared, local to loop only.
2. Testing Condition: The testing condition to execute statements of loop. It is
used for testing the exit condition for a loop. It must return a boolean value true
or false. When the condition became false the control will be out from the loop
and for loop ends.
3. Increment / Decrement: The loop variable is incremented/decremented
according to the requirement and the control then shifts to the testing condition
again.
Note: Initialization part is evaluated only once when the for loop starts.
Example:
csharp
// C# program to illustrate for loop.
using System;
class forLoopDemo
{
public static void Main()
{
// for loop begins when x=1
// and runs till x <= 4
for (int x = 1; x <= 4; x++)
[Link]("GeeksforGeeks");
}
}
Output:
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
Exit Controlled Loops: The loops in which the testing condition is present at
the end of loop body are termed as Exit Controlled Loops. do-while is an exit
controlled loop.
Note: In Exit Controlled Loops, loop body will be evaluated for at-least one
time as the testing condition is present at the end of loop body.
1. do-while loop do while loop is similar to while loop with the only difference
that it checks the condition after executing the statements, i.e it will execute the
loop body one time for sure because it checks the condition after executing the
statements.
Syntax :
do
{
statements..
}while (condition);
Flowchart:
Example:
csharp
// C# program to illustrate do-while loop
using System;
class dowhileloopDemo
{
public static void Main()
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
[Link]("GeeksforGeeks"); x+
+;
}
while (x < 20);
}
}
Output:
GeeksforGeeks
Infinite Loops:
The loops in which the test condition does not evaluate false ever tend to
execute statements forever until an external force is used to end it and thus they
are known as infinite loops.
Example:
csharp
// C# program to demonstrate infinite loop
using System;
class infiniteLoop
{
public static void Main()
{
// The statement will be printed
// infinite times
for(;;)
[Link]("This is printed infinite times");
}
}
Output:
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
This is printed infinite times
..........
Nested Loops: When loops are present inside the other loops, it is known as
nested loops.
Example:
csharp
// C# program to demonstrate nested loops
using System;
class nestedLoops
{
public static void Main()
{
// loop within loop printing GeeksforGeeks
for (int i = 2; i < 3; i++)
for (int j = 1; j < i; j++)
[Link]("GeeksforGeeks");
}
}
Output:
GeeksforGeeks
Example 1:
class GFG {
// Main Method
static public void Main()
{
[Link]("Print array:");
// creating an array
int[] a_array = new int[] { 1, 2, 3, 4, 5, 6, 7 };
{
[Link](items);
}
}
}
Output:
Print array:
1
2
3
4
5
6
7
Explanation: foreach loop in above program is equivalent to:
for(int items = 0; items < a_array.Length; items++)
{
[Link](a_array[items]);
}
break statement
The break statement is used to terminate the loop or statement in which it
present. After that, the control will pass to the statements that present after the
break statement, if available. If the break statement present in the nested loop,
then it terminates only those loops which contains break statement.
Flowchart:
Example:
class Geeks {
// Main Method
static public void Main()
{
[Link]("GeeksforGeeks");
}
}
}
Output:
GeeksforGeeks
GeeksforGeeks
continue statement
This statement is used to skip over the execution part of the loop on a certain
condition. After that, it transfers the control to the beginning of the loop.
Basically, it skips its following statements and continues with the next iteration
of the loop.
Example:
// C# program to illustrate the
// use of continue statement
using System;
class Geeks {
// Main Method
public static void Main()
{
[Link](i);
}
}
}
Output:
1
2
3
5
6
7
8
9
10
goto statement
This statement is used to transfer control to the labeled statement in the
program. The label is the valid identifier and placed just before the statement
from where the control is transferred.
Example:
// C# program to illustrate the
// use of goto statement
using System;
class Geeks {
// Main Method
static public void Main()
{
int number = 20;
switch (number) {
case 5:
[Link]("case 5");
break;
case 10:
[Link]("case 10");
break;
case 20:
[Link]("case 20");
default:
[Link]("No match found");
}
}
}
Output:
case 20
case 5
return statement
This statement terminates the execution of the method and returns the control to
the calling method. It returns an optional value. If the type of method is void,
then the return statement can be excluded.
Example:
// C# program to illustrate the
// use of return statement
using System;
class Geeks {
// Main Method
static public void Main()
{
int number = 2;
Output:
The addition is 4
Example:
// declaring public class
public class Geeks
{
.NET PROGRAMMING Page
103
UNIT II
// field variable
public int a, b;
Objects correspond to things found in the real world. For example, a graphics
program may have objects such as “circle”, “square”, “menu”. An online
shopping system might have objects such as “shopping cart”, “customer”, and
“product”.
When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of
those attributes, i.e. the state are unique for each object. A single class may have
any number of instances.
Example:
As we declare variables like (type name;). This notifies the compiler that we
will use the name to refer to data whose type is type. With a primitive variable,
this declaration also reserves the proper amount of memory for the variable. So
for reference variable, the type must be strictly a concrete class name.
Dog tuffy;
If we declare a reference variable(tuffy) like this, its value will be
undetermined(null) until an object is actually created and assigned to it. Simply
declaring a reference variable does not create an object.
Initializing an object
The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the class
constructor.
Example:
// Class Declaration
// Instance Variables
String name;
String breed;
int age;
String color;
// Property 1
public String GetName()
{
return name;
}
// Property 2
public String GetBreed()
{
return breed;
}
// Property 3
public int GetAge()
{
return age;
}
// Property 4
public String GetColor()
{
return color;
}
// Method 1
public String ToString()
{
return ("Hi my name is " + [Link]()
+ ".\nMy breed, age and color are " +
[Link]()
+ ", " + [Link]() + ", " + [Link]());
}
// Main Method
public static void Main(String[] args)
{
// Creating object
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
[Link]([Link]());
}
}
Output:
Hi my name is tuffy.
My breed, age and color are papillon, 5, white
2.7 METHODS
Methods are generally the block of codes or statements in a program that gives
the user the ability to reuse the same code which ultimately saves the excessive
use of memory, acts as a time saver and more importantly, it provides a
better readability of code. So basically, a method is a collection of statements
that perform some specific task and return the result to the caller. A method can
also perform some specific task without returning anything.
Declaring a Method in C#
Here's the syntax to declare a method in C#.
returnType methodName()
{
// method body
}
Here,
returnType - It specifies what type of value a method returns. For
example, if a method has an int return type then it returns an int value.
If the method does not return a value, its return type is void.
methodName - It is an identifier that is used to refer to the particular
method in a program.
method body - It includes the programming statements that are used to
perform some tasks. The method body is enclosed inside the curly
braces { }
Let's see an
example, void
display() {
// code
}
.NET PROGRAMMING Page
108
UNIT II
Here, the name of the method is display(). And, the return type is void.
Calling a Method in C#
In the above example, we have declared a method named display(). Now, to use
the method, we need to call it.
Here's how we can call the display() method.
// calls the method
display();
namespace Method
{ class Program {
// method declaration
public void display() {
[Link]("Hello World");
}
//call method
[Link]();
[Link]();
}
}
}
Output
Hello World
In the above example, we have created a method named display(). We have
created an object p1 of the Program class.
Notice the line,
[Link]();
Here, we are using the object to call the display() method.
C# Method Return Type
A C# method may or may not return a value. If the method doesn't return any
value, we use the void keyword (shown in the above example).
If the method returns any value, we use the return statement to return any value.
For example,
int addNumbers() {
...
return sum;
}
Here, we are returning the variable sum. One thing you should always
remember is that the return type of the method and the returned value should be
of the same type.
In our code, the return type is int. Hence, the data type of sum should be
of int as well.
Example: Method Return Type
using System;
namespace Method
{ class Program {
// method declaration
static int addNumbers() {
// call method
int sum = addNumbers();
[Link](sum);
[Link]();
}
}
}
Output
19
namespace Method
{ class Program {
int addNumber (int a, int b)
{ int sum = a + b;
return sum;
//call method
int sum = [Link](100,100);
[Link]();
}
}
}
Output
Sum: 200
namespace Method
{ class Program {
}
static void Main(string[] args) {
//call method
string work = [Link]("Cleaning"); ;
[Link]("Work: " +
work); [Link]();
}
}
Output
Work: Cleaning
Here, the work() method has a single parameter work.
Built-in methods
So far we have defined our own methods. These are called user-defined
methods.
However, in C#, there are various methods that can be directly used in our
program. They are called built-in methods. For example,
Sqrt() - computes the square root of a number
ToUpper() - converts a string to uppercase
Example: [Link]() Method
using System;
namespace Method
{ class Program {
static void Main(string[] args) {
// Built in method
double a =
[Link](9);
[Link]("Square root of 9: " + a);
}
}
}
Output
Square root of 9: 3
In the above program, we have used
double a = [Link](9);
to compute the square root of 9. Here, the Sqrt() is a built-in method that is
defined inside the Math class.
We can simply use built-in methods in our program without writing the method
definition. To learn more, visit C# built-in methods.
Method Overloading in C#
In C#, we can create two or more methods with the same name. It is known as
method overloading. For example,
using System;
namespace MethodOverload
{ class Program {
// constructor
Car() {
//code
}
}
Here, Car() is a constructor. It has the same name as its class.
Call a constructor
Once we create a constructor, we can call it using the new keyword. For
example,
new Car();
In C#, a constructor is called when we try to create an object of a class. For
example,
Car car1 = new Car();
Here, we are calling the Car() constructor to create an object car1. To learn more
about objects, visit C# Class and Objects.
Types of Constructors
There are the following types of constructors:
Parameterless Constructor
Parameterized Constructor
Default Constructor
1. Parameterless Constructor
When we create a constructor without parameters, it is known as a
parameterless constructor. For example,
using System;
namespace Constructor {
class Car {
// parameterless constructor
Car() {
[Link]("Car Constructor");
}
// call constructor
new Car();
[Link]();
}
}
}
Output
Car Constructor
In the above example, we have created a constructor named Car().
new Car();
We can call a constructor by adding a new keyword to the constructor name.
2. C# Parameterized Constructor
In C#, a constructor can also accept parameters. It is called a parameterized
constructor. For example,
using System;
namespace Constructor {
class Car {
string brand;
int price;
// parameterized constructor
Car(string theBrand, int thePrice) {
brand = theBrand;
price = thePrice;
}
}
}
}
Output
Brand: Bugatti
Price: 50000
In the above example, we have created a constructor named Car(). The
constructor takes two parameters: theBrand and thePrice.
Notice the statement,
Car car1 = new Car("Bugatti", 50000);
Here, we are passing the two values to the constructor.
The values passed to the constructor are called arguments. We must pass the
same number and type of values as parameters.
3. Default Constructor
If we have not defined a constructor in our class, then the C# will automatically
create a default constructor with an empty code and no parameters. For
example,
using System;
namespace Constructor {
class Program {
int a;
}
}
}
Output
Default value of a: 0
In the above example, we have not created any constructor in the Program class.
However, while creating an object, we are calling the constructor.
Program p1 = new Program();
Here, C# automatically creates a default constructor. The default constructor
initializes any uninitialized variable with the default value.
Hence, we get 0 as the value of the int variable a.
2.9 GARBAGE COLLECTION AND DESTRUCTORS
A destructor is a method that which is called when a class object is no
longer required and is ready for grabage collection.
The destructor function is preceded with a ~ (tilde) operator/symbol and
it has the same name as the class.
The primary purpose of destructor method is to deallocate/destroy the
object or instance of classes.
It is also known as Finalizer in C#
programming. Properties of a Destructor:
1. Destructor name must start with ~ (tilde) and must have the same name as
the class.
2. Destructor method is used in a class only and no more than one destructor
is allowed in a class.
3. Destructor can't be defined for a Structure.
4. Destructor method can neither be inherited nor overloaded.
5. Destructor method can neither have an access modifier nor parameters.
namespace Studytonight
{
public class Student
{
public Student()
{
[Link]("Default Constructor");
}
// the destructor
~Student()
{
[Link]("This is the destructor");
}
}
In the code above we have defined a destructor method for our class Student.
In C#, destructor (finalizer) is used to destroy objects of class when the
scope of an object ends. It has the same name as the class and starts with a
tilde ~. For example,
class Test {
...
//destructor
~Test() {
...
}
}
Here, ~Test() is the destructor.
class Person {
public Person() {
[Link]("Constructor called.");
}
// destructor
~Person() {
[Link]("Destructor called.");
}
When we create an object of the Person class, the constructor is called. After the
scope of the object ends, object p1 is no longer needed. So, the destructor is
called implicitly which destroys object p1.
Example 2: C# Destructor
using System;
namespace CsharpDestructor {
class Person {
string name;
void getName()
{ [Link]("Name: " +
name);
}
// destructor
~Person() {
[Link]("Destructor called.");
}
Features of Destructors
There are some important features of the C# destructor. They are as follows:
We can only have one destructor in a class.
Keyword Definition
Used to define a try block. This block holds the code that may
try throw an exception.
Used to define the finally block. This block holds the default
finally code.
try
{
// code that may raise an exception
[Link](colors[5]);
}
catch (IndexOutOfRangeException e)
{
[Link]("An exception occurred: " + [Link]);
}
}
}
Output
An exception occurred: Index was outside the bounds of the array.
C# finally block
We can see in the above image that the finally block is executed in both cases.
The finally block is executed:
after try and catch block - when exception has occurred
after try block - when exception doesn't occur
The try..catch..finally block can be collectively used to handle exceptions.
Now let's look at an example of exception handling using try…catch…
finally.
}
finally
{
// this code is always executed whether of exception occurred or not
[Link]("Sum of two numbers is: " + (firstNumber +
secondNumber));
}}}
Output
Enter first number:
8
Enter second number:
0
An exception occurred: Attempted to divide by zero.
Sum of two numbers is: 8
In the above example, we have tried to perform division and addition operations
to two int input values using try...catch…finally.
Notice the code,
try
{
// code that may raise raise an exception
int divisionResult = firstNumber / secondNumber; }
Here, we have enclosed the code that performs division operation
inside try because this code may raise the DivideByZeroException exception.
There are two cases in this program:
Case I - When exception occurs in try, the catch block is executed followed by
the finally block.
Case II - The finally block is directly executed after the try block if an
exception doesn't occur. For example, if we enter 9 and 2, exception doesn't
occur in the try block and we get the following output:
// Output when exception doesn't occur
Enter first number:
9
Enter second number:
2
Division of two numbers is: 4
Sum of two numbers is: 11
UNIT III
ARRAYS AND
3.1 ARRAYS STRINGS
Elements of an Array
1. C# Array Declaration
In C#, here is how we can declare an array.
datatype[] arrayName;
Here,
dataType - data type like int, string, char, etc
arrayName - it is an
identifier Let's see an example,
int[] age;
Here, we have created an array named age. It can store elements of int type.
2. Array initialization in C#
In C#, we can initialize an array during the declaration. For
example, int [] numbers = {1, 2, 3, 4, 5};
Here, we have created an array named numbers and initialized it with
values 1, 2, 3, 4, and 5 inside the curly braces.
Note that we have not provided the size of the array. In this case, the C#
automatically specifies the size by counting the number of elements in the array
(i.e. 5).
.NET PROGRAMMING Page 129
UNIT III
namespace AccessArray
{ class Program {
static void Main(string[] args) {
// create
.NET an array
PROGRAMMING Page 130
UNIT III
[Link]();
}
}
}
Output
Element in first index : 1
Element in second index : 2
Element in third index : 3
In the above example, we have created an array named numbers with
elements 1, 2, 3. Here, we are using the index number to access elements of the
array.
numbers[0] - access first element, 1
namespace ChangeArray
{ class Program {
static void Main(string[] args) {
// create an array
int[] numbers = {1, 2, 3};
[Link]();
}
}
}
Output
Old Value at index 0: 1
New Value at index 0: 11
In the above example, the initial value at index 0 is 1. Notice the line,
//change the value at index 0
numbers[0] = 11;
Here, we are assigning a new value of 11 to the index 0. Now, the value at index
0 is changed from 1 to 11.
Types of Arrays in C#
There are three types of arrays in C#, which are
1. Single-dimensional Array in C#
2. Multi-dimensional Array in C#
3. Jagged Array in C#
1. Single-Dimensional Arrays
In C#, a single-dimensional array is a data structure that stores elements of the
same data type in a linear sequence. Each element in the array is accessed by its
index, starting from zero. Single-dimensional arrays are versatile and commonly
used for various programming tasks, providing efficient data storage and
retrieval.
Declaring Single dimensional array
int[] arr = new int[10];
Explanation
This C# code in the C# Compiler initializes an integer array "numbers" with
values {10, 20, 30, 40, 50} and then iterates through the array using a for loop
to print each element to the console. It demonstrates basic array declaration,
initialization, and traversal in a console application.
Output
Array elements:
10
20
30
40
50
2. Multi-Dimensional Arrays
Multi-dimensional arrays in C# are arrays that hold data in more than one
dimension, allowing for efficient storage and manipulation of complex data
structures. Unlike one-dimensional arrays, these arrays can be thought of as
matrices or tables, providing rows and columns to organize and access elements
{
for (int j = 0; j < columns; j++)
{
[Link](myArray[i, j] + " ");
}
[Link]();
}
}
}
Explanation
This code defines a 2D array called myArray with 3 rows and 4 columns. It
initializes the array with specific values. Then, it retrieves the dimensions of the
array using the GetLength method. The code then uses nested loops to iterate
over the array and prints each element on the console. The output displays the
array elements in a tabular format, with each row on a separate line.
Output
Array elements:
1234
5678
9 10 11 12
3. Jagged Array in C#
In C#, a jagged array is an array of arrays where each element can hold arrays
of different sizes. Unlike regular multi-dimensional arrays, jagged arrays allow
for flexible and uneven lengths, making them ideal for storing complex
data
You can also initialize the array upon declaration like this:
int[][] jaggedArray = new int[][]
{
new int[] { 4, 6, 8, },
new int[] { 1, 0, 2, 4, 6 }
};
You can use the following shorthand form:
int[][] jaggedArray =
{
new int[] { 4, 6, 8, },
new int[] { 1, 0, 2, 4, 6 }
};
Let’s see the practical implementation of Jagged Arrays in the following
example:
Example
using System;class Program
{
static void Main()
{
// Create a multi-dimensional jagged array int[]
[] jaggedArray = new int[3][]
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
}
[Link]();
}
}
}
Explanation
This code defines a 2D array called myArray with 3 rows and 4 columns. It
initializes the array with specific values. Then, it retrieves the dimensions of the
array using the GetLength method. The code then uses nested loops to iterate
over the array and prints each element on the console. The output displays the
array elements in a tabular format, with each row on a separate line.
Output
Row0:123
Row1:45
Row2:6789
3.2 STRINGS
A string is a sequence of characters. For example, "hello" is a string containing
a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
We use the string keyword to create a string.
For example,
// create a string
string str = "C# Programming";
Here, we have created a string named str and assigned the text "C#
Programming". We use double quotes to represent strings in C#.
Example: Create string in C#
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "Programiz";
// print string
[Link](str1);
[Link](str2);
[Link]();
}
}
}
Output
C# Programming
Programiz
In the above example, we have created two strings named str1 and str2 and
printed them.
Note: A string variable in C# is not of primitive types like int, char, etc. Instead,
it is an object of the String class.
String Operations
C# string provides various methods to perform different operations on strings.
We will look into some of the commonly used string operations.
1. Get the Length of a string
To find the length of a string, we use the Length property. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str = "C# Programming";
[Link]("string: " + str);
[Link]("Length: "+
length);
[Link]();
}
.NET PROGRAMMING Page 139
UNIT III
}
Output
string: C# Programming
Length: 14
In the above example, the Length property calculates the total number of
characters in the string and returns it.
2. Join two strings in C#
We can join two strings in C# using the Concat() method. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# ";
[Link]("string str1: " + str1);
// create string
string str2 = "Programming";
[Link]("string str2: " + str2);
[Link]();
}
}
}
Output
string str1: C#
string str2: Programming
Joined string: C# Programming
In the above example, we have created two strings named str1 and str2. Notice
the statement,
string joinedString = [Link](str1, str2);
Here, the Concat() method joins str1 and str2 and assigns it to
the joinedString variable.
We can also join two strings using the + operator in C#. To learn more, visit C#
string Concat.
3. C# compare two strings
In C#, we can make comparisons between two strings using
the Equals() method. The Equals() method checks if two strings are equal or
not. For example,
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";
result1);
[Link]();
}
}
}
Output
string
In the str1 and example,
above str2 are equal: True created 3 strings named str1, str2, and str3.
we have
Here, we are using the Equals() method to check if one string is equal to
another.
.NET PROGRAMMING Page 141
UNIT III
\\ backslash
\0 null
\n new line
\t horizontal tab
Methods of C# string
There are various string methods in C#. Some of them are as follows:
Methods Description
The in keyword used along with foreach loop is used to iterate over the iterable-
item. The in keyword selects an item from the iterable-item on each iteration
and store it in the variable element.
On first iteration, the first item of iterable-item is stored in element. On second
iteration, the second element is selected and so on.
The number of times the foreach loop will execute is equal to the number of
elements in the array or collection.
Example: Printing array using foreach loop
using System;
namespace Loop
{
class ForEachLoop
{
public static void Main(string[] args)
{
char[] myArray = {'H','e','l','l','o'};
foreach(char ch in myArray)
{
[Link](ch);
}
}
}
}
When we run the both program, the output will be:
H
e
l
l
o
In the above program, the foreach loop iterates over the array, myArray. On first
iteration, the first element i.e. myArray[0] is selected and stored in ch.
Similarly on the last iteration, the last element i.e. myArray[4] is selected.
Inside the body of loop, the value of ch is printed.
When we look at both programs, the program that uses foreach loop is more
readable and easy to understand. This is because of its simple and expressive
syntax.
.NET PROGRAMMING Page 145
UNIT III
Hence, foreach loop is preferred over for loop when working with arrays and
collections.
METHODS AND CLASSES
3.4 ACCESS MODIFIERS
In C#, access modifiers specify the accessibility of types (classes, interfaces,
etc) and type members (fields, methods, etc). For example,
class Student
{ public string
num;
Here,
name - public field that can be accessed from anywhere
num - private field can only be accessed within the Student class
Types of Access Modifiers
In C#, there are 4 basic types of access modifiers.
public
private
protected
internal
1. public access modifier
When we declare a type or type member public, it can be accessed from
anywhere. For example,
using System;
namespace MyApplication
{ class Student {
public string name = "Sheeran";
class Program {
static void Main(string[] args) {
namespace MyApplication {
class Student {
private string name = "Sheeran";
class Program {
static void Main(string[] args) {
[Link]();
}
}
}
In the above example, we have created a class named Student with a
field name and a method print().
// accessing name field and printing it
[Link]("Name: " + [Link]);
// accessing print method from Student
[Link]();
Since the field and method are private, we are not able to access them from
the Program class. Here, the code will generate the following error.
Error CS0122 '[Link]' is inaccessible due to its protection level
Error CS0122 '[Link]()' is inaccessible due to its protection level
namespace MyApplication
{ class Student {
protected string name = "Sheeran";
}
class Program {
static void Main(string[] args) {
class Student {
protected string name = "Sheeran";
}
// derived class
class Program : Student {
namespace Assembly
class Student {
internal string name = "Sheeran";
}
.NET PROGRAMMING Page 150
UNIT III
class Program {
static void Main(string[] args) {
namespace Studytonight
{
class Program
{
public static void Area(int a)
{
[Link]("Adding 2 to the value of a");
a = a+2;
[Link]("New value of a: " + a);
[Link]("Calculating the area of geometric shapes");
int result = a * a;
[Link]("Area of Square is " + result);
}
location is not created for these parameters. The reference parameters represent
the same memory location as the actual parameters that are supplied to the
method.
In simpler words, when we pass a reference of a variable to a method, then we
pass the address or the memory location where the value is stored. So if, inside
the method, the value of the parameter is changed, then the actual value stored
at the memory location gets changed as no copy is getting created for the value
passed as parameter.
The following example demonstrates the concept of passing a variable by
reference
Filename: [Link]
using System;
namespace Studytonight
{
public class Program
{
public static void Area(ref int a)
{
[Link]("Calculating Area of Geometric Shapes");
a = a * a;
[Link]("Area of Square is " + a);
}
3. Pass by Output
The out keyword indicates a value that is passed by reference type. It is pretty
similar to the ref keyword, the only difference is that out doesn't require a
variable to be initialized before we pass it as an argument to the method.
However, the called method is required to assign a value to the passed reference
before the method returns.
The following example demonstrates the concept of passing a variable by
reference using the out keyword.
Filename: [Link]
using System;
namespace Studytonight
{
public class Program
{
public static void Area(out int a)
{
a = 50;
[Link]("Calculating Area of Geometric Shapes");
a = a * a;
[Link]("Area of Square is " + a);
}
public static void Main()
{
int s;
Area(out s);
[Link]("Side Value is " + s);
[Link]();
}
}
}
Copy
Output:
void display(int a) {
...
}
...
void display(int a, int b) {
...
}
Here, we have two methods in a class with the same name - display(). It is
possible to have more than one method with the same name because the number
of parameters in methods is different.
For example,
using System;
namespace MethodOverload
{ class Program {
namespace MethodOverload
{ class Program {
[Link]("Programiz");
[Link]();
}
}
}
Output
int type: 100
string type: Programiz
In the above program, we have overloaded the display() method with different
types of parameters.
Based on the type of arguments passed during the method call, the
corresponding method is called.
[Link](100) - calls method with int type parameter
[Link]("Programiz") - calls method with string type parameter
namespace MethodOverload
{ class Program {
METHOD OVERRIDING
Method overriding is a concept in object-oriented programming (OOP) where a
subclass (derived class) provides a specific implementation of a method that is
already defined in its superclass (base class). The method in the subclass
overrides the method in the superclass, meaning the subclass method is called
instead of the superclass method when invoked on an object of the subclass.
}
class myProgram
{
public static void Main()
{
// obj1 is the object of Polygon class
Polygon obj1 = new Polygon();
The method in the subclass can have a different access modifier (in some
languages, like Java), but it cannot be more restrictive than the method in
the superclass.
3.7 MAIN METHOD
an entry point called Main Method. It is the first method which gets invoked
whenever an application started and it is present in every C# executable file.
The application may be Console Application or Windows Application. The
most common entry point of a C# program is static void Main() or static void
Main(String []args).
Different Declaration of Main() Method
Below are the valid declarations of Main Method in a C# program:
1. With command line arguments: This can accept n number of array type
parameters during the runtime. Example:
using System;
class GFG {
// Main Method
public static void Main(String[] args)
{
[Link]("Main Method");
}
}
Output:
Main Method
class GFG {
// Main Method
public static void Main()
{
[Link]("Main Method");
}
}
Output:
Main Method
class GFG {
// Main Method
protected static void Main()
{
[Link]("Main Method");
}
}
Output:
Main Method
4. Without any access modifier: The default access modifier is private for a
Main() method. Example:
using System;
class GFG {
[Link]("Main Method");
}
}
Output:
Main Method
5. Return Type: The Main Method can also have integer return type. Returning
an integer value from Main() method cause the program to obtain a status
information. The value which is returned from Main() method is treated as the
exit code for the process. Example:
using System;
class GFG {
// Main Method with int return type
static int Main()
{
[Link]("Main Method");
Working of C# Recursion
In the above example, we have called the recurse() method from inside the
Main method (normal method call). And, inside the recurse() method, we are
again calling the same recurse() method. This is a recursive call.
To stop the recursive call, we need to provide some conditions inside the method.
Otherwise, the method will be called infinitely.
This delegate type can point to any method that takes a string parameter and
returns void.
Using a Delegate:
1. Define a method that matches the delegate signature:
public void PrintMessage(string message)
{
[Link](message);
}
2. Create an instance of the delegate: You can then create a delegate
instance and point it to the method.
MyDelegate del = new MyDelegate(PrintMessage);
3. Invoke the method through the delegate: You can invoke the method
through the delegate like this:
del("Hello, Delegates!");
Example Code:
Here's a full example demonstrating the use of delegates:
using System;
class Program
{
// Declare a delegate type
public delegate void MyDelegate(string message);
Copy code
Hello, Delegates!
This is a shortcut way to call a delegate.
Multicast Delegates
A delegate in C# can also point to more than one method, which is known as
multicast delegates. When you invoke the delegate, it calls all the methods that
are in its invocation list.
Example of multicast delegates:
public delegate void MyDelegate(string message);
class Program
{
static void Main()
{
Button button = new Button();
3.11 EVENTS
Events are something that occurs in a program. Events allow a class or object to
notify other classes or objects when something occurs.
The class that raises (or sends) the event is called the publisher.
The classes that receive (or handle) the event are called subscribers. And
the method of the classes that handle the event is often called event
handlers.
This pattern is known as publisher/subscriber. In this pattern, the publisher
determines when to raise the event and the subscribers decide how to handle the
event.
Technically, an event has an encapsulated delegate. In fact, an event is like a
simpler delegate. Let’s take an example of using events.
Suppose you have a class called Order with a method Create() that creates a
new order:
class Order
{
public void Create()
{
[Link]("Order created");
}
}Code language: C# (cs)
class SMS
{
public static void Send()
{
[Link]("Send an SMS");
}
}Code language: C# (cs)
When an order is created, you want to send an email and SMS to the customer.
To do it, you may come up with the following code:
class Order
{
public void Create()
{
[Link]("Order was
created"); [Link]();
[Link]();
}
}Code language: C# (cs)
Later if you want to do other tasks when an order is created, you have to modify
the Create() method. Also, the Order class depends on the Email and SMS
classes which is not a good design.
To resolve this, you can use the publisher/subscriber pattern:
The Order class is the publisher.
The Email and SMS classes are the subscribers.
When an order is created, the Order object will notify
the Email and SMS classes to send an email and SMS.
Declaring an event
The following declares the OnCreated event when an order is created:
delegate void OrderEventHandler();
class Order
{
public event OrderEventHandler OnCreated;
[Link]("Order created");
}
}Code language: C# (cs)
How it works.
First, define a delegate type for the event:
delegate void OrderEventHandler();Code language: C# (cs)
Second, declare an event associated with the delegate type:
public event OrderEventHandler OnCreated;Code language: C# (cs)
Since an event is a member of a class, you need to declare it inside the class. In
this example, the event is public so that other classes can register event handlers
with it. Also, the event handlers must match the delegate type associated with
the event.
Raising an event
Raising an event is the same as invoking a method. An event that doesn’t have
any event handlers is null. Therefore, before raising an event, you need to
compare it to null.
The following raises the OnCreated event inside the Create() method:
class Order
{
public event OrderEventHandler OnCreated;
if(OnCreated != null)
{
OnCreated();
}
}
}Code language: C# (cs)
Subscribing to an event
.NET PROGRAMMING Page 175
UNIT III
[Link] += [Link];
[Link] += [Link];
[Link]();
}
}Code language: C# (cs)
Output:
Order created
Send an email
Send an SMSCode language: C# (cs)
How it works.
First, create a new Order object:
var order = new Order();Code language: C# (cs)
Second, add event handlers to the OnCreated event:
[Link] += [Link];
[Link] += [Link];Code language: C#
(cs) Third, call the Create() method of the Order
object: [Link]();Code language: C# (cs)
The Create() method raises the OnCreated event. Since
the Email and SMS classes are subscribed to the OnCreated event,
the Send() methods of these classes are automatically called.
class Order
{
public event OrderEventHandler OnCreated;
if(OnCreated != null)
{
OnCreated();
}
}
}
class Email
{
public static void Send()
{
[Link]($"Send an email");
}
}
class SMS
{
public static void Send()
{
[Link]($"Send an SMS");
}
}
class Program
{
static void Main(string[] args)
{
[Link] += [Link];
[Link] += [Link];
[Link]();
}
}Code language: C# (cs)
EventHandler
C# provides you with the standard EventHandler delegate type so that you don’t
need to define a new delegate type when you use events.
The following shows the declaration of the EventHandler delegate type:
public delegate void EventHandler(object sender, EventArgs e);Code language:
C# (cs)
In this delegate type:
The sender holds a reference to the object that raised the event.
The EventArgs object holds the state information which can be whatever
that is applicable to the application.
It’s important to understand that the EventArgs is designed for event handlers
that do not need to pass data from the publisher to subscribers. If you want to
pass the data, you need to define a class derived from the EventArgs class.
The following program shows how to use the EventHandler for the order
created event:
class Order
{
public event EventHandler OnCreated;
if(OnCreated != null)
{
OnCreated(this, [Link]);
}
}
}
class Email
{
public static void Send(object sender, EventArgs e)
{
[Link]($"Send an email");
}
}
class SMS
{
public static void Send(object sender, EventArgs e)
{
[Link]($"Send an SMS");
}
}
class Program
{
static void Main(string[] args)
{
var order = new Order();
[Link] +=
[Link]; [Link]
+= [Link];
[Link]();
}
}Code language: C# (cs)
How it works.
First, use the EventHandler instead of the OrderEventHandler delegate type:
public event EventHandler OnCreated;Code language: C# (cs)
Second, raise the OnCreated event by passing the Order object (this)
and [Link]:
OnCreated(this, [Link]);Code language: C# (cs)
Note that the [Link] provides a value to use with an event that does
not have event data.
Third, modify the signature of the Send() method of the Email and SMS classes
to match with the EventHandler delegate type:
public static void Send(object sender, EventArgs e)Code language: C# (cs)
The above expression is a statement lambda which contains two statements in the
lambda body. This takes two int inputs and returns its sum.
Example: C# Expression Lambda
using System;
class Program
{
static void Main()
{
// expression lambda that returns the square of a number
var square = (int num) => num * num;
Here, the expression lambda returns the square of num. We have then assigned
the expression lambda to the square variable.
So, when we pass 5 as an input in square, we get 25 as an output.
Note: Before C# 9.0, explicitly defining the delegate type was necessary when
using var with lambda expressions. C# 9.0 introduced the ability to assign
lambda expressions to var without specifying the delegate type.
In the above example, we have assigned lambda expression num => num * 3; to the
Func delegate multiply.
Here, the lambda expression takes an int type input num, multiplies it
with 3 and returns the result to multiply().
Hence, when we pass 5 in multiply(), it returns 15.
Note: The Func<> delegate type takes 0 or more input values and returns an output
value. For example, Func<int,int,string> takes two int inputs and returns a string
output. To learn more about delegates, visit C# delegates.
Use of Lambda Expression
Some of the uses of the lambda expression are:
1. Writing Easy and Simple Delegate Code
Using lambda expressions, we can write much easier and simpler code. Let's see
programs with and without using a lambda expression in a delegate.
Program Without Using Lambda Expression
using System;
class Program
{
static void Main()
{
// method that returns square of a number
int Square(int num)
{
return num * num;
}
49
Here, we don't need to define a separate method. We have replaced the pointer
to the square() method with the lambda expression.
2. Passing Parameter in Method
We can pass a lambda expression as a parameter in a method call.
Let's take a built-in Count() method of C# array and pass a lambda expression
as its parameter.
using System;
class Program
{
static void Main()
{
// array containing integer values
int[] numbers = { 2, 13, 1, 4, 13, 5 };
For instance, a program might get data from the understudy records or get to
worker records, and so on.
To beat such kinds of issues, Microsoft created LINQ. It connects one more
capacity to the C# or .NET dialects to create a question for any LINQ viable
information source. What's more, the best part is the sentence structure used to
make a question is similar regardless of which kind of information source is
utilized means the grammar of making an inquiry about information in a social
data set is the same as that used to make question information put away in a
cluster there is compelling reason need to utilize SQL or some other [Link]
language component. You can likewise utilize LINQ with SQL, with XML
records, with [Link], with web administrations, and with some other
information base.
In C#, LINQ is available in System. Linq namespace. It gives different sort of
classes and techniques which upholds LINQ questions. In this namespace:
1. The Enumerable class holds a standard query operator that works on an
object which executes IEnumerable<T>.
2. The queryable class holds standard inquiry administrators that work on an
object which executes IQueryable<T>.
For Example: SQL is a structured query Language that is used to save and
recuperate data from the database. Likewise, LINQ is an Organized Query
Sentence structure. LINQ is the basic C#. It is utilized to recover information
from various kinds of sources, for example, XML, docs, collections, [Link]
DataSet, Web Service, MS SQL Server, and different database servers.
Uses of LINQ
1. The primary reason behind making LINQ is, before C# 3.0, we used for
loop, for each loop, or delegates to traverse a collection to track down a
particular object, yet the detriment of involving these strategies for
finding an object is you really want to compose an enormous amount of
code to find an object which is additional tedious and make your program
less lucid. So to defeat these issues, LINQ is presented, which plays out
similar activity in a couple of quantities of lines and makes your code
clear; furthermore, you can involve similar code in different projects.
2. It additionally gives full sort checking at the compile time. It assists us
with distinguishing the error at the runtime, so we can undoubtedly
eliminate them.
3. LINQ is it is straightforward, very much arranged, and significant level
language than SQL
4. You can likewise utilize LINQ with C# array and collections. It provides
you with another guidance to take care of the old issues in a powerful
way.
5. With the assistance of LINQ, you can undoubtedly work with a data
source like XML, SQL, Entities, objects, and so forth. A single query can
work with the database, compelling reason need to learn various sorts of
languages.
6. LINQ upholds query expression, Anonymous types, Implicitly typed
variables, Lambda expressions, Object and collection initializers, and
Extension methods.
We can use LINQ queries in two ways
LINQ query Syntax structure is comprised of query keywords which are
characterized into the .NET System rendition 3.5 or Higher. This allows the
software engineer or developers to compose the directions very much like SQL
design in the code(C# or [Link]) without the utilization of rates. It is in like
manner known in light of the fact that the Question Articulation Grammar. In
LINQ, you can compose the inquiry to IEnumerable series or IQueryable
information sources utilizing the ensuing strategies:
1. Query Syntax:
The LINQ query language syntax starts with from keyword and finishes with the
Select or GroupBy keyword. After from keyword, you can utilize various sorts
of Standard Query operations like grouping, filtering, and so on, as indicated by
your need. In LINQ, 50 unique kinds of Standard Question Administrators are
accessible.
Steps for writing the Query syntax:
Step-1: In the first step, we have to add the [Link] namespace in the code.
.NET PROGRAMMING Page 187
UNIT III
{
" Hii JavaTpoint",
" Welcome to JavaTpoint ",
" The topic is LINQ ",
" Any Queries "
};
// step-
3: Creating the LINQ query for the data source using a keyword like select, f
rom, etc.
var r = from l in list
where [Link](" JavaTpoint")
select l;
// In this will print only the sentence which contains JavaTpoint word
// step-4: Executing LINQ Query using the for each loop
foreach(var i in r)
{
[Link](i);
}
}
}
Output:
2. Method Syntax
In LINQ, Method Syntax is utilized to call the expansion method for the
Enumerable or Queryable static classes. It is also called Method Extension
Syntax or Fluent. Notwithstanding, the compiler generally changes over the
query syntax in method syntax structure at compile time. It can summon the
standard Query operator like Where, Join, Max, Min, Avg, GroupBy Select, and
so forth. You are permitted to call them straightforwardly without utilizing
Query syntax.
Step-1: In the first step, we have to add the [Link] namespace in the code.
1. i.e., using [Link];
Step-2: In a second step, we have to create the data source on which we have to
perform the operations
Ex: List list = new List()
{
" Hii ",
" Welcome to JavaTpoint
", " The topic is LINQ "
" Any Queries "
};
Step-3: Now create the query using the methods provided by the Enumerable or
Queryable static classes
1. Ex: var r = [Link](a=> [Link](" JavaTpoint "));
Here r is the query variable that stores the result of the query articulation. The
form clause is utilized to determine the information source, i.e., list, where
condition applies to the channel, i.e., [Link](" Hii ") and select statement
gives the kind of the brought things back. Furthermore, l is the reach variable.
Step-4: The final step is to execute the query using the for each
loop. Advertisement
EX: foreach(var i in r)
{
[Link](i);
}
Example program on Method syntax:
// program to create LINQ query using Method syntax
// step-1: Adding the [Link] namespace in the code.
using System;
using [Link];
using [Link];
class HelloWorld
{
// Main Method
static public void Main()
{
// Step-
2: creating the data source on which we have to perform the operations
List<string> list = new List<string>()
{
" Hii JavaTpoint",
" Welcome to JavaTpoint ",
" The topic is LINQ ",
" Any Queries "
};
//step-
3 creating the query using the methods provided by the Enumerable or Query
able static classes
var r = [Link](a=> [Link](" JavaTpoint "));
// In this will print only the sentence which contains JavaTpoint word
// Executing LINQ Query using the for each loop
foreach(var i in r)
{
[Link](i);
}
}
}
Output:
Advantages of LINQ
1. The client doesn't have to learn new query languages for an alternate type
of data format or data source.
2. It increments the clarity of the code.
3. The query can be reused.
4. It gives type checking of the object at assemble time.
5. It gives IntelliSense to conventional collections.
6. It tends to be utilized with collections or arrays.
7. LINQ upholds ordering, grouping, filtering, and sorting.
8. It makes debugging simple since it is coordinated with the C# language.
9. It gives straightforward change suggesting you can without a doubt
change more than one data type into another data type like changing SQL
data into XML data.
.NET PROGRAMMING Page 191
UNIT IV
UNIT IV
DEVELOPING [Link]
APPLICATIONS VISUAL STUDIO
Visual Studio is an Integrated Development Environment(IDE)
developed by Microsoft to develop Desktop applications, GUI(Graphical
User Interface), console, web applications, mobile applications, cloud,
and web services, etc.
With the help of this IDE, you can create managed code as well as native
code. It uses the various platforms of Microsoft software development
software like Windows store, Microsoft Silverlight, and Windows API,
etc.
It is not a language-specific IDE as you can use this to write code in C#,
C++, VB(Visual Basic), Python, JavaScript, and many more languages. It
provides support for 36 different programming languages.
It is available for Windows as well as for macOS.
EVOLUTION OF VISUAL STUDIO
The first version of VS(Visual Studio) was released in 1997, named as Visual
Studio 97 having version number 5.0. The latest version of Visual Studio is 15.0
which was released on March 7, 2017. It is also termed as Visual Studio 2017.
The supported .Net Framework Versions in latest Visual Studio is 3.5 to 4.7.
Java was supported in old versions of Visual Studio but in the latest version
doesn’t provide any support for Java language.
Visual Studio Editions
There are 3 editions of Microsoft Visual Studio as follows:
1. Community
It is a free version which is announced in 2014. All other editions are paid. This
contains the features similar to Professional edition. Using this edition, any
individual developer can develop their own free or paid apps like .Net
applications, Web applications and many more. In an enterprise organization,
this edition has some limitations. For example, if your organization have more
than 250 PCs and having annual revenue greater than $1 Million(US Dollars)
then you are not permitted to use this edition. In a non-enterprise organization,
up to five users can use this edition. Its main purpose is to provide the
Ecosystem(Access to thousands of extensions) and Languages(You can code in
C#, VB, F#, C++, HTML, JavaScript, Python, etc.) support.
2. Professional
It is the commercial edition of Visual Studio. It comes in Visual Studio 2010
and later versions. It provides the support for XML and XSLT editing and
includes the tool like Server Explorer and integration with Microsoft SQL
Server. Microsoft provides a free trial of this edition and after the trial period,
the user has to pay to continue using it. Its main purpose is to provide
Flexibility(Professional developer tools for building any application type),
Productivity(Powerful features such as CodeLens improve your team’s
productivity), Collaboration(Agile project planning tools, charts, etc.) and
Subscriber benefits like Microsoft software, plus Azure, Pluralsight, etc.
3. Enterprise
It is an integrated, end to end solution for teams of any size with the demanding
quality and scale needs. Microsoft provides a 90-days free trial of this edition
and after the trial period, the user has to pay to continue using it. The main
benefit of this edition is that it is highly scalable and deliver high-quality
software.
Getting Started with Visual Studio 2017
First, you have to download and install the Visual Studio. For that, you
can refer to Downloading and Installing Visual Studio 2017. Don’t forget
to select the .NET core workload during the installation of VS 2017. If
you forget then you have to modify the installation.
You can see a number of tool windows when you will open the Visual
Studio and start writing your first program as follows:
2. In the Create a new project window, select C# from the Language list.
Next, select Windows from the All platforms list, and Web from the All
project types list.
After you apply the language, platform, and project type filters, select
the [Link] Core Web App (Razor Pages) template, and then select Next.
From this window, you can enable container support and add
authentication support. The drop-down menu for Authentication Type has the
following four options:
None: No authentication.
Individual accounts: These authentications are stored in a local or
Azure-based database.
Microsoft identity platform: This option uses Microsoft Entra ID
or Microsoft 365 for authentication.
Windows: Suitable for intranet applications.
Leave the Enable container support box unchecked, and
select None for Authentication Type.
Select Create.
Visual Studio opens your new project.
TOUR YOUR SOLUTION
1. The project template creates a solution with a single [Link] Core
project named MyCoreApp. Select the Solution Explorer tab to view its
contents.
4. Each .cshtml file has an associated code file. To open the code file in the
editor, expand the [Link] node in Solution Explorer, and select
the [Link] file.
6. The project contains a wwwroot folder, which is the root for your
website. Expand the folder to view its contents.
You can put static site content such as CSS, images, and JavaScript
libraries directly in the paths where you want them.
7. The project also contains configuration files that manage the web app at
run time. The default application configuration is stored
in [Link]. However, you can override these settings by
using [Link]. Expand the [Link] file
to view the [Link] file.
4. Return to Visual Studio, and then press Shift+F5 to stop debugging. This
action closes the project in the browser window.
5. In Visual Studio, open [Link] for editing. Next, delete the
sentence, Use this page to detail your site's privacy policy and replace it
with This page is under construction as of @ViewData["TimeStamp"].
Select Apply. Visual Studio deletes the unnecessary using directives from
the file.
7. Next, create a string for the current date that's formatted for your culture
or region by using the [Link] method.
The first argument for the method specifies how the date should be
displayed. This example uses the format specifier (d) which
indicates the short date format.
The second argument is the CultureInfo object that specifies the
culture or region for the date. The second argument determines,
among other things, the language of any words in the date, and the
type of separators used.
Change the body of the OnGet() method in [Link] to the
following code:
public void OnGet()
{
string dateTime = [Link]("d", new CultureInfo("en-
US"));
ViewData["TimeStamp"] = dateTime;
}
Notice that the following using directive automatically gets added to the top of
the file:
using [Link];
[Link] contains the CultureInfo class.
Press F5 to open your project in the web browser.
At the top of the web site, select Privacy to view your changes.
The [Link] file corresponds with your Home page in the web app,
which runs in a web browser.
In the code editor, you see HTML code for the text that appears on
the Home page.
3. Select https or press Ctrl+F5 to run the app and open it in a web
browser.
4. In the web browser, you see your new changes on the Home page.
5. Close the web browser, press Shift+F5 to stop debugging, and save your
project. You can now close Visual Studio.
</form>
The runat="server" attribute makes this form a server-side control. When the
page is loaded, [Link] processes this form and converts it into HTML that
the client browser can understand.
4. Web Controls
Web controls in [Link] are the building blocks of the user interface. They
include elements like buttons, textboxes, labels, grids, dropdowns, etc. These
controls can automatically generate HTML elements in the browser, and their
behavior is governed by event handlers defined in the code-behind.
Examples of Common Web Controls:
TextBox: For user input.
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
Button: To trigger an action.
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
Label: For displaying messages.
<asp:Label ID="lblMessage" runat="server" Text="Enter your
name"></asp:Label>
DropDownList: For displaying a list of options.
<asp:DropDownList ID="ddlCountry" runat="server">
<asp:ListItem Text="Select Country" Value="0"></asp:ListItem>
<asp:ListItem Text="USA" Value="1"></asp:ListItem>
<asp:ListItem Text="Canada" Value="2"></asp:ListItem>
</asp:DropDownList>
Each control has a runat="server" attribute that makes it a server-side control,
which means it will be processed on the server and can interact with the code-
behind logic.
namespace MyApp
{
public partial class Default : Page
{
Web forms in [Link] are a key part of the framework, enabling developers to
create dynamic, interactive websites. [Link] Web Forms allows for a rich
user interface and the ability to manage state in a stateless environment. Here's a
detailed breakdown of the fundamentals of Web Forms in [Link]:
1. [Link] Web Forms Overview
What are Web Forms? Web Forms is a part of the [Link] framework
that simplifies web application development by providing an event-driven
model. It uses a set of controls, like buttons and text boxes, to handle user
interaction.
Page-based Model: Web Forms are page-centric, meaning each page (or
form) in an [Link] application corresponds to a file (typically with a
.aspx extension), which contains both HTML and server-side code.
Server-Side Controls: Web Forms provide a range of built-in controls
(like text boxes, grids, buttons, and labels) that render as HTML elements
on the client side but execute on the server.
2. Basic Structure of a Web Form
A basic Web Form consists of:
Page Directive: Defines settings like the language of the page, the type
of code-behind file, etc.
HTML Markup: Defines the structure of the page, including forms,
tables, etc.
Server-Side Controls: Controls that are rendered as HTML but have
server-side functionality. These controls are enclosed within <asp:...>
tags.
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form id="form1" runat="server">
.NET PROGRAMMING Page 210
UNIT IV
<title>My Page</title>
</asp:Content>
9. Web Forms vs. MVC
Web Forms is event-driven and page-based, ideal for developers who are
more familiar with desktop applications.
MVC (Model-View-Controller): [Link] MVC is a more modern
approach focused on separating concerns with clear boundaries between
models, views, and controllers.
10. Deployment of Web Forms
Deploying an [Link] Web Forms application is similar to any web
application:
The compiled assemblies (.dll files) and other resources (e.g., images,
scripts) are placed on a server.
The .aspx pages and associated files are served through IIS (Internet
Information Services).
4.3 CONVERTING HTML PAGE TO AN [Link] PAGE
Converting an HTML page to an [Link] Web Forms page involves
integrating dynamic server-side functionality and [Link]-specific features
like server-side controls, event handling, and state management. Here's a step-
by-step guide on how to convert an HTML page to an [Link] Web Forms
page.
Step-by-Step Conversion Process
1. Create a New [Link] Web Forms Page
First, you need to create a new .aspx page in your [Link] project:
In Visual Studio, right-click your project and select Add > New Item.
Choose Web Form from the list, provide a name (e.g., [Link]),
and click Add.
This generates the basic structure of a Web Form page.
2. Convert HTML Tags to [Link] Server Controls
HTML tags that require server-side functionality need to be replaced with
[Link] server controls. These controls are enclosed within the <asp:...> tag.
namespace MyApp
{
public partial class MyPage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Handle page load logic here
}
function validateEmail() {
var email = [Link]("txtEmail").value;
if (!email) {
alert("Email is required!");
}
}
</script>
Converted [Link] with validation:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]" Inherits="[Link]" %>
<html>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="txtEmail" runat="server" placeholder="Enter your
email" />
<asp:RequiredFieldValidator
ID="rfvEmail"
runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Email is required!"
ForeColor="Red" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</form>
</body>
</html>
6. Replace JavaScript with Server-Side Logic (If Needed)
Any JavaScript logic, such as form submission or alerts, can be replaced with
server-side logic in the [Link] page. For example:
Instead of using JavaScript alert() for showing messages, use a Label
control to display the result on the page.
Complex form processing or validations can be handled on the server side
in the code-behind file, where you have access to the [Link]
framework.
If your original HTML page has common layout elements (e.g., headers,
footers, navigation bars), you can use Master Pages in [Link]. A master
page allows you to define common layout, which can be reused across multiple
pages.
Example:
<!-- [Link] -->
<%@ Master Language="C#" Inherits="[Link]" %>
<html>
<head><title><asp:ContentPlaceHolder ID="title" runat="server"
/></title></head>
<body>
<div id="header">Welcome to My Site</div>
<asp:ContentPlaceHolder ID="mainContent" runat="server" />
</body>
</html>
<body>
<form id="form1" runat="server">
<h1>Welcome to My Web Page</h1>
<asp:TextBox ID="txtName" runat="server" placeholder="Enter your
name" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<asp:Label ID="lblMessage" runat="server" />
</form>
</body>
</html>
And in the code-behind ([Link]):
using System;
using [Link];
namespace MyApp
{
public partial class MyPage : Page
{
protected void btnSubmit_Click(object sender, EventArgs
e)
{
string name = [Link];
[Link] = "Hello, " + name;
}
}
}
4.4 PAGE CLASS
In [Link] Web Forms, the Page class is a fundamental class that represents a
web page within the application. It serves as the base class for all Web Forms
pages and provides properties, methods, and events that are essential for
handling the page lifecycle, managing controls, handling user input, and
interacting with the server.
Key Features of the Page Class
The Page class is a part of the [Link] namespace and is used for
creating dynamic web pages. It provides several critical functions, such as
rendering content, managing server-side controls, and providing lifecycle events
to handle page requests.
.NET PROGRAMMING Page 219
UNIT IV
{
// Final modifications before rendering
}
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<form id="form1" runat="server">
<h2>Welcome to [Link] Web Forms</h2>
<asp:TextBox ID="txtName" runat="server" placeholder="Enter your
name" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
<asp:Label ID="lblMessage" runat="server" />
</form>
</body>
</html>
Code-behind ([Link]):
using System;
using [Link];
namespace WebApplication1
{
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
// This is a good place to initialize data or controls.
if (!IsPostBack)
{
[Link] = "Please enter your name.";
}
}
HTML controls. They are designed to be used with the server-side code.
Common Web Controls in [Link]
1. TextBox
The TextBox control is used to accept user input as a single-line text field.
Example:
<asp:TextBox ID="txtName" runat="server" placeholder="Enter your name" />
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
[Link] = "John Doe"; // Set initial value.
}
}
2. Button
The Button control is used to create a clickable button that can trigger events.
Example:
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
Code-behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
[Link]("Button Clicked!");
}
3. Label
The Label control is used to display static text or dynamic content.
Example:
<asp:Label ID="lblMessage" runat="server" Text="Hello, World!" />
Code-behind:
[Link] = "This is a dynamic message";
4. DropDownList
The DropDownList control is used to create a dropdown list that allows the user
to select a value from a list of options.
Example:
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="Select a Country" Value="" />
<asp:ListItem Text="USA" Value="USA" />
<asp:ListItem Text="India" Value="IND" />
</asp:DropDownList>
Code-behind:
string selectedCountry = [Link];
5. CheckBox
The CheckBox control is used to allow users to select or deselect an option.
Example:
<asp:CheckBox ID="chkAccept" runat="server" Text="I accept the terms and
conditions" />
Code-behind:
bool isChecked = [Link];
6. RadioButton
The RadioButton control is used when you want users to select one option from
a set of mutually exclusive options.
Example:
<asp:RadioButton ID="rdMale" runat="server" GroupName="Gender"
Text="Male" />
<asp:RadioButton ID="rdFemale" runat="server" GroupName="Gender"
Text="Female" />
Code-behind:
string gender = [Link] ? "Male" : "Female";
7. GridView
The GridView control is used to display data in a tabular format. It supports
data binding, pagination, sorting, and editing.
Example:
<asp:GridView ID="gvUsers" runat="server"
AutoGenerateColumns="False"
OnRowCommand="gvUsers_RowCommand">
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="Email" HeaderText="Email"
SortExpression="Email" />
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Example data binding
[Link] = GetUsers();
[Link]();
}
}
8. Repeater
The Repeater control is used to display repeated data items from a data source
in a customizable way. It is ideal for scenarios where you need full control over
the layout of each item.
Example:
<asp:Repeater ID="rptProducts" runat="server">
.NET PROGRAMMING Page 229
UNIT IV
<ItemTemplate>
<p><%# Eval("ProductName") %></p>
</ItemTemplate>
</asp:Repeater>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
[Link] = GetProducts();
[Link]();
}
}
}
}
Code-behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
string name = [Link];
[Link] = "Hello, " + name;
}
1. Button Controls
[Link] provides three types of button control:
Button : It displays text within a rectangular area.
Link Button : It displays text that looks like a hyperlink.
.NET PROGRAMMING Page 231
UNIT IV
Property Description
Text box controls are typically used to accept input from the user. A text box
control can accept one or more lines of text depending upon the settings of the
TextMode attribute.
Label controls provide an easy way to display text which can be changed from
one execution of a page to the next. If you want to display text that does not
change, you use the literal text.
Basic syntax of text control:
<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>
Common Properties of the Text Box and Labels:
Property Description
The mostly used attribute for a label control is 'Text', which implies the text
displayed on the label.
3. Check Boxes and Radio Buttons
A check box displays a single option that the user can either check or uncheck
and radio buttons present a group of options from which the user can select just
one option.
To create a group of radio buttons, you specify the same name for the
GroupName attribute of each radio button in the group. If more than one group
is required in a single form, then specify a different group name for each group.
If you want check box or radio button to be selected when the form is initially
displayed, set its Checked attribute to true. If the Checked attribute is set to true
for multiple radio buttons in a group, then only the last one is considered as
true.
Basic syntax of check box:
<asp:CheckBox ID= "chkoption" runat= "Server">
</asp:CheckBox>
Basic syntax of radio button:
<asp:RadioButton ID= "rdboption" runat= "Server">
</asp: RadioButton>
Common properties of check boxes and radio buttons:
Property Description
4. List Controls
[Link] provides the following controls
Drop-down list,
List box,
Radio button list,
Check box list,
Bulleted list.
These control let a user choose from one or more items from the list. List boxes
and drop-down lists contain one or more list items. These lists can be loaded
either by code or by the ListItemCollection editor.
Basic syntax of list box control:
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
Basic syntax of drop-down list control:
<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
Common properties of list box and drop-down Lists:
Property Description
Property Description
item are set to the string value you specify. To set it differently you must create
a list item object and then add that item to the collection.
The ListItemCollection Editor is used to add item to a drop-down list or list
box. This is used to create a static list of items. To display the collection editor,
select edit item from the smart tag menu, or select the control and then click the
ellipsis button from the Item property in the properties window.
Common properties of ListItemCollection:
Property Description
Methods Description
Property Description
Property Description
8. HyperLink Control
The HyperLink control is like the HTML <a> element.
Basic syntax for a hyperlink control:
<asp:HyperLink ID="HyperLink1" runat="server">
HyperLink
</asp:HyperLink>
It has the following important properties:
Property Description
9. Image Control
The image control is used for displaying images on the web page, or some
alternative text, if the image is not available.
Basic syntax for an image control:
<asp:Image ID="Image1" runat="server">
It has the following important properties:
Property Description
STATE MANAGEMENT
State Management in [Link] is a crucial concept because HTTP is a
stateless protocol, meaning that each request to the server is independent, and
the server does not remember previous requests or data associated with a
particular client. This stateless nature can be problematic when developing
dynamic, interactive applications that need to preserve data between requests
(such as user preferences, login credentials, form values, etc.).
[Link] provides several techniques for state management, which can be
broadly divided into two categories:
1. Client-Side State Management: Where the state is stored on the client
(e.g., in the browser).
2. Server-Side State Management: Where the state is stored on the
server. Let's explore each type of state management in more detail:
1. Client-Side State Management
Client-side state management stores the state on the client’s browser or device,
which reduces the load on the server. Common methods include:
1.1 Cookies
Cookies are small pieces of data stored on the client's browser. They can be
used to store simple information (like user preferences or session identifiers)
and persist data across requests and sessions.
Creating and Storing Cookies:
HttpCookie cookie = new HttpCookie("UserName");
[Link] = "JohnDoe";
[Link] = [Link](1); // Set expiration date
[Link](cookie);
Reading Cookies:
HttpCookie cookie = [Link]["UserName"];
if (cookie != null)
{
string userName = [Link];
}
Advantages:
o Persistent across sessions if expiration date is set.
Advantages:
o Simple to implement.
o Visible in the URL (can be bookmarked or shared).
Disadvantages:
o Visible to the user, so not suitable for sensitive data.
o Limited length (depending on the browser).
1.3 Hidden Fields
Hidden fields are HTML elements (<input type="hidden" />) that store data on
the client side. They are not visible to the user but can be accessed by the server.
Example:
<input type="hidden" id="hiddenField" value="SomeValue" runat="server"
/>
.NET PROGRAMMING Page 242
UNIT IV
1.4 ViewState
ViewState is a mechanism that allows the storage of the state of a page's
controls between requests. The state is stored in a hidden field on the page and
is automatically managed by [Link].
Example:
Enabling ViewState (by default it is enabled):
<asp:TextBox ID="txtName" runat="server" />
Retrieving ViewState in code-behind:
string userName = [Link];
Advantages:
o Simple to use, automatically managed by [Link].
o Useful for preserving data between postbacks.
Disadvantages:
o Can increase the page size, affecting performance (especially for
large pages).
o Visible to the user in the form of a hidden field, so not suitable for
sensitive data.
Client- Server-
Method Advantages Disadvantages
Side Side
Simple to implement,
Limited size, security
Cookies Yes No persistent across
concerns
sessions
Simple to implement,
Query Limited length, visible to
Yes No visible in URL,
String user
shareable
Consumes server
Stores complex data,
Session State No Yes resources, session
secure on server
timeout
Consumes server
Application Shared across users,
No Yes resources, concurrency
State global access
issues
Fast data retrieval,
May expire, consumes
Cache No Yes
reduces database hits server memory
UNIT V
5.1 VALIDATION CONTROLS
[Link] validation controls validate the user input data to ensure that useless,
unauthenticated, or contradictory data don't get stored.
[Link] provides the following validation controls:
RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary
Base Validator Class
The validation control classes are inherited from the BaseValidator class hence
they inherit its properties and methods. Therefore, it would help to take a look at
the properties and the methods of this base class, which are common for all the
validation controls:
Members Description
is valid.
2. RangeValidator Control
The RangeValidator control verifies that the input value falls within a
predetermined range.
It has three specific properties:
Properties Description
</asp:RangeValidator>
3. CompareValidator Control
The CompareValidator control compares a value in one control with a fixed
value or a value in another control.
It has the following specific properties:
Properties Description
</asp:CompareValidator>
Character
Description
Escapes
\b Matches a backspace.
\t Matches a tab.
\ Escape character.
Apart from single character match, a class of characters could be specified that
can be matched, called the metacharacters.
Metacharacters Description
Quantifier Description
{N} N matches.
</asp:RegularExpressionValidator>
5. Custom Validator
The CustomValidator control allows writing application specific custom
validation routines for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction
property. The client side validation routine should be written in a scripting
language, such as JavaScript or VBScript, which the browser can understand.
The server side validation routine must be called from the control's
ServerValidate event handler. The server side validation routine should be
written in any .Net language, like C# or [Link].
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>
6. ValidationSummary
The ValidationSummary control does not perform any validation but shows a
summary of all errors in the page. The summary displays the values of the
ErrorMessage property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
ShowSummary : shows the error messages in specified format.
ShowMessageBox : shows the error messages in a separate
window. The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:"
/>
Validation Groups
Complex pages have different groups of information provided in different
panels. In such situation, a need might arise for performing validation separately
for separate group. This kind of situation is handled using validation groups.
To create a validation group, you should put the input controls and the
validation controls into the same logical group by setting
their ValidationGroup property.
Example
The following example describes a form to be filled up by all the students of a
school, divided into four houses, for electing the school president. Here, we use
the validation controls to validate the user input.
This is the form in design view:
<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose your president"
runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server"
style="width:239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td
class="style3">
House:
</td>
<td class="style2">
<asp:RadioButtonList ID="rblhouse" runat="server"
RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvhouse" runat="server"
ControlToValidate="rblhouse" ErrorMessage="Enter your house
name" >
<br />
</td>
</tr>
<tr>
<td
class="style3">
Class:
</td>
<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td
class="style3">
Email:
</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server" style="width:250px">
</asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator ID="remail" runat="server"
ControlToValidate="txtemail" ErrorMessage="Enter your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-
.]\w+)*">
</asp:RegularExpressionValidator>
<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
style="text-align: center" Text="Submit" style="width:140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:"
/>
</form>
The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if ([Link])
{
[Link] = "Thank You";
}
else
{
[Link] = "Fill up all the fields";
}
}
</ads>
imageUrl: The path to the advertisement image.
navigateUrl: The URL where the user will be directed when the ad is
clicked.
altText: The alternate text for the image.
impressions: A weight value indicating the number of times the ad is
likely to be shown (higher values mean the ad is more likely to appear).
Step 2: Add the AdRotator Control in the [Link] Page
Once the XML file is created, you can add the AdRotator control in your
[Link] page (e.g., [Link]):
<asp:AdRotator ID="adRotator1" runat="server"
DataFile="~/[Link]"
Width="300px"
Height="250px" />
DataFile: Points to the XML file that contains the ad data.
Width: Defines the width of the ad display.
NavigateUrl VARCHAR(255),
AltText VARCHAR(255),
Impressions INT
);
Step 2: Bind the AdRotator to the Database
To bind the AdRotator to a SQL database, you'll use the SqlDataSource control
to fetch the ad data. Here's an example:
<asp:SqlDataSource ID="adsDataSource" runat="server"
ConnectionString="YourConnectionString"
SelectCommand="SELECT ImageUrl, NavigateUrl, AltText, Impressions
FROM Advertisements">
</asp:SqlDataSource>
ItemStyle: Controls the appearance of the ad, such as its width and
height.
Target: Specifies how the ad link should be opened. It can be set to
_blank (new tab/window) or _self (same window).
while ([Link]())
{
[Link]($"{reader["FirstName"]} {reader["LastName"]}");
}
[Link]();
Non-query Command (ExecuteNonQuery)
while ([Link]())
{
[Link]($"{reader["FirstName"]} {reader["LastName"]}");
}
[Link]();
try
{
// Open the connection
[Link]();
[Link]("Connection Opened Successfully");
}
catch (Exception ex)
{
[Link]($"Error: {[Link]}");
}
finally
{
// Close the connection
[Link]();
}
The connectionString contains the database details, such as the server
name, database name, and credentials.
Open(): Opens the connection to the database.
try
{
[Link](); // Open the connection
transaction = [Link](); // Begin the transaction
Rollback(): Rolls back the transaction, undoing any changes made during
the transaction.
4. Handling Errors in Direct Data Access
When performing database operations, it's important to handle exceptions
properly to ensure that your application can recover from errors such as network
failures, SQL errors, or connection issues.
Example: Basic Error Handling
try
{
SqlCommand command = new SqlCommand("SELECT * FROM
Employees", connection);
[Link]();
SqlDataReader reader = [Link]();
while ([Link]())
{
.NET PROGRAMMING Page 273
UNIT V
[Link]($"{reader["FirstName"]} {reader["LastName"]}");
}
}
catch (SqlException ex)
{
[Link]($"SQL Error: {[Link]}");
}
catch (Exception ex)
{
[Link]($"General Error: {[Link]}");
}
finally
{
[Link]();
}
SqlException: Catches errors specific to SQL Server (like connection
issues or query syntax errors).
Exception: Catches any general exceptions (such as network errors or
other unexpected issues).
Summary of Key [Link] Classes for Direct Data Access
Class Description
Class Description
(used for aggregate functions).
class Program
{
static void Main()
{
// Step 1: Create the connection
string connectionString =
"Server=myServerAddress;Database=myDatabase;User
Id=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);
try
{
// Fill the DataSet with data
[Link](dataSet, "Employees");
[Link]("Original Data:");
foreach (DataRow row in [Link])
{
[Link]($"{row["EmployeeID"]} - {row["FirstName"]}
{row["LastName"]} - {row["Department"]}");
}
[Link]("\nUpdated Data:");
foreach (DataRow row in [Link])
{
[Link]($"{row["EmployeeID"]} - {row["FirstName"]}
{row["LastName"]} - {row["Department"]}");
}
DATA BINDING
5.6 DATA BINDING WITH [Link]
In [Link], data binding refers to the process of linking data from a
data source (such as a database, XML file, or in-memory collection) to user
interface (UI) controls like GridView, DropDownList, or TextBox in an
[Link] application. This allows the data to be displayed in the UI and, in
many cases, updated automatically when the data changes.
Data binding is commonly used to display data from a database in a UI
component, enabling seamless interaction between the data and the UI.
[Link] provides various methods for binding data, especially with
disconnected data access.
Key [Link] Classes for Data Binding
1. DataSet / DataTable
These are in-memory representations of data from the database. DataSet
is a collection of DataTable objects, while a DataTable represents a single
table of data.
2. DataAdapter
The DataAdapter is responsible for filling a DataSet or DataTable with
data from the database and saving changes back to the database.
3. BindingSource
A BindingSource acts as an intermediary between data and UI controls in
Windows Forms. It allows you to bind a DataTable or List<T> to UI
controls and manage their interactions.
4. UI Controls (e.g., GridView, DropDownList, TextBox)
These are the controls used to display and manipulate data on the web
page.
Steps for Data Binding in [Link]
1. Create a Connection to the Database
Establish a connection to the database using SqlConnection or another
connection class.
2. Create a DataAdapter and Retrieve Data
Use the SqlDataAdapter to execute a SELECT query and fill a DataSet or
DataTable with the results.
Explanation:
SqlDataAdapter: Retrieves data from the database using a SQL query and
fills the DataSet.
[Link]: The DataSource property of the GridView is set
to the DataTable inside the DataSet.
[Link](): Binds the data to the GridView control, which
will display the data in the table format.
Step 2: Create the GridView in the [Link] Web Form
In the ASPX page, create a GridView control where the data will be
displayed:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="[Link]"
Inherits="[Link]" %>
<!DOCTYPE html>
<html xmlns="[Link]
<head runat="server">
<title>Data Binding Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Employee List</h2>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="True" />
</div>
</form>
</body>
</html>
Explanation:
AutoGenerateColumns="True": Automatically generates the columns
based on the data provided in the DataSource. If you want to manually
define columns, you can use the BoundField controls inside the
GridView.
GridView1: This is the ID of the GridView control where the data will be
displayed.
Example of Data Binding in Windows Forms
In Windows Forms, the process is similar but uses controls like
DataGridView instead of GridView.
Step 1: Retrieve Data and Bind to DataGridView
using System;
using [Link];
using [Link];
using [Link];
public MainForm()
{
InitializeComponent();
}
using [Link];
public MainForm()
{
InitializeComponent();
}
Explanation:
BindingSource: A BindingSource is used to bind the DataTable to the
DataGridView.
[Link]: Sets the DataSource of the BindingSource to
the DataTable inside the DataSet.
[Link]: The DataGridView is bound to the
BindingSource rather than directly to the DataTable, making it easier to
manage complex data-binding scenarios.
5.7 DATA SOURCE CONTROLS
In [Link], Data Source Controls are not directly part of [Link], but
they are related to how data can be bound to web controls in [Link].
[Link] itself is a set of classes for data access and manipulation, such as
SqlConnection, SqlCommand, DataSet, and DataTable. However, in [Link],
Data Source Controls like SqlDataSource, ObjectDataSource,
LinqDataSource, and others provide an easy way to connect to various data
sources (like databases or custom objects) and bind that data to UI controls,
abstracting the underlying [Link] code.
Understanding Data Source Controls in the Context of [Link]
Although [Link] provides a lower-level approach to data access, [Link]
provides specialized data source controls that make it easier to work with data
sources like SQL databases, XML files, and business objects. These data source
controls allow developers to use declarative data binding without writing the
boilerplate [Link] code. In the background, these data source controls are
still leveraging [Link] or similar technologies to interact with databases.
Here are a few key Data Source Controls in [Link] that abstract [Link]
functionality:
1. SqlDataSource Control
Purpose: The SqlDataSource control is used to connect to a SQL Server
database and execute SQL queries (e.g., SELECT, INSERT, UPDATE,
DELETE).
Internals: It uses [Link]'s SqlConnection, SqlCommand, and
SqlDataAdapter to interact with the database.
TypeName="[Link]"
SelectMethod="GetEmployees" />
Explanation:
TypeName: The full name of the class that contains the method you want
to bind to.
SelectMethod: The name of the method in the specified class that
retrieves data.
In the above example, the ObjectDataSource will call the GetEmployees
method of the EmployeeService class, which might internally use [Link] to
query a database.
3. LinqDataSource Control
Purpose: The LinqDataSource control binds data to LINQ queries, which
can fetch data from any data source such as databases, collections, or
XML.
Internals: Internally, it uses LINQ (Language Integrated Query) and can
leverage [Link] for database queries. It simplifies querying and
binding data from databases by using LINQ syntax.
Usage: Ideal for developers who are using LINQ (such as LINQ to SQL,
LINQ to Entities) to query their data source.
Example:
<asp:LinqDataSource
ID="LinqDataSource1"
runat="server"
ContextTypeName="[Link]"
TableName="Employees" />
Explanation:
ContextTypeName: The name of the LINQ data context class.
TableName: The name of the table (entity) to bind to within the LINQ
context.
Explanation:
ContextTypeName: The name of the Entity Framework context class.
EntitySetName: The name of the EntitySet (a collection of entities) to
bind to.
This control simplifies data binding for applications that use Entity Framework.
Entity Framework handles the ORM (Object-Relational Mapping) and data
access, while the EntityDataSource abstracts much of the underlying logic.
5. XmlDataSource Control
Purpose: The XmlDataSource control allows you to bind data to an XML
document or XML file.
Internals: Uses the XmlDocument or XDocument classes in [Link]
to load and query the XML data.
Usage: Ideal for applications that work with XML data as the data source.
Example:
<asp:XmlDataSource
ID="XmlDataSource1"
runat="server"
DataFile="~/App_Data/[Link]" />
Explanation:
DataFile: The path to the XML file that contains the data.
This control is useful for data that is stored in an XML format, allowing easy data
binding to controls like GridView, Repeater, or ListView.
Advantages of Using Data Source Controls
1. Simplified Data Binding: You don't have to write [Link] code to
retrieve data, manage database connections, or handle CRUD operations.
2. Declarative Syntax: You can easily configure data sources using a
declarative syntax in your ASPX pages.
3. Built-in Features: Supports features like paging, sorting, and updating
without writing much code.
4. Reduced Boilerplate Code: Eliminates the need to manually write
database connection management code (like opening and closing
connections, executing queries, etc.).
Disadvantages of Using Data Source Controls
1. Less Flexibility: Data Source Controls may not support complex
scenarios, such as complex joins, advanced queries, or custom SQL.
2. Performance Considerations: For large-scale
Although [Link] itself doesn’t provide direct data controls (like [Link]
does with controls such as GridView, DropDownList, etc.), it provides the data
handling backend that these controls rely on to perform data operations.
[Link] allows developers to fetch, update, and manage data via its classes,
while [Link]’s data-bound controls use [Link] for the data access
layer.
Here’s an overview of some of the important data controls in the context of
[Link] (which use [Link] behind the scenes):
1. GridView Control
Purpose: The GridView control is a powerful data display control that
presents data in a tabular format. It is used for displaying, editing, and
paging through data retrieved from a data source.
[Link] Integration: Data can be bound to a GridView using various
data source controls (e.g., SqlDataSource, ObjectDataSource, etc.), which
internally use [Link] to retrieve the data.
Example:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="True"
DataSourceID="SqlDataSource1">
</asp:GridView>
Important Features:
o Auto Paging, Sorting, and Editing: Built-in features for
pagination, sorting, and editing operations without writing extra
code.
o Custom Bound Fields: You can bind data columns manually using
the BoundField or TemplateField.
o Integration with [Link]: You can bind data from an
[Link] DataSet, DataTable, or a database using a
SqlDataSource.
2. DropDownList Control
Purpose: The DropDownList control is a dropdown menu that allows
users to select an item from a list. It is commonly used for displaying a
set of predefined options, often sourced from a database.
4. DetailsView Control
Purpose: The DetailsView control is used to display a single record at a
time in a form-like format. It is typically used for viewing and editing
detailed information for a single entity, such as an employee’s details.
[Link] Integration: It works with data sources like SqlDataSource
or ObjectDataSource to fetch and update data.
Example:
<asp:DetailsView
ID="DetailsView1"
runat="server"
AutoGenerateRows="True"
DataSourceID="SqlDataSource1">
</asp:DetailsView>
Important Features:
o Automatic Editing and Insertion: Can automatically generate
fields for data editing or insertion.
o Master-Detail Views: Frequently used in conjunction with a
GridView to create master-detail data views.
5. Repeater Control
Purpose: The Repeater control is a more lightweight data-bound control
that displays data in a custom template format. It’s used for situations
where you need full control over the layout of data.
[Link] Integration: You can bind a Repeater control to [Link]
objects like DataTable, DataSet, or a data source control like
SqlDataSource.
Example:
<asp:Repeater
ID="Repeater1"
runat="server"
DataSourceID="SqlDataSource1">
<ItemTemplate>
<div><%# Eval("FirstName") %> <%# Eval("LastName") %></div>
</ItemTemplate>
</asp:Repeater>
Important Features:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="True"
DataSourceID="SqlDataSource1"
AllowPaging="True"
AllowSorting="True"
OnRowEditing="GridView1_RowEditing"
OnRowDeleting="GridView1_RowDeleting"
OnRowUpdating="GridView1_RowUpdating"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
</asp:GridView>
[Link] = -1;
BindGrid();
}
BindGrid();
}
o Drag and drop the fields you want to display on the report.
o Optionally, you can apply grouping, sorting, filtering, and
formatting rules to the report.
o Save the report (.rpt file).
3. Fetch Data Using [Link]
You will fetch data from your database using [Link]. In this example, we'll use
a SqlDataAdapter to fetch data and bind it to a Crystal Report.
Here’s an example of how to fetch data from a SQL Server database and bind it
to a Crystal Report in the code-behind.
using System;
using [Link];
using [Link];
using [Link];
<html>
<body>
<form id="form1" runat="server">
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server"
Width="100%" Height="600px"
EnableDatabaseLogonPrompt="False" />
</form>
</body>
</html>
CrystalReportViewer: This control displays the report. You can
configure it to allow features like printing, exporting, and zooming.
EnableDatabaseLogonPrompt: Set this to False to disable the login
prompt when connecting to the database.
5. Passing Parameters to Crystal Reports
If your Crystal Report has parameters (e.g., date range or customer ID), you can
pass them dynamically from the [Link] page.
Example of passing parameters to the Crystal Report:
using [Link];
using [Link];