C#.NET+Material+ +harsha
C#.NET+Material+ +harsha
C#.NET+Material+ +harsha
0
Harsha Vardhan
.NET Expert
C#.NET 8.0
.NET Fundamentals........................................................................................................................ 26
Introduction to .NET ............................................................................................................. 26
What is .NET? ....................................................................................................................... 26
Parts of .NET ......................................................................................................................... 26
History of .NET...................................................................................................................... 27
History of .NET...................................................................................................................... 27
Versions of .NET ................................................................................................................... 29
CIL and CLR ........................................................................................................................... 30
Execution Model of .NET Programs ..................................................................................... 30
CIL (Common Intermediate Language) or MSIL ................................................................... 31
CLR (Common Language Runtime)....................................................................................... 31
Sub Components of CLR ....................................................................................................... 32
.NET Framework Architecture .............................................................................................. 34
What is .NET Framework ...................................................................................................... 34
System Requirements of .NET Framework: ......................................................................... 34
.NET Framework Architecture .............................................................................................. 35
CLS and CTS .......................................................................................................................... 36
CLS (Common Language Specification) ................................................................................ 36
CTS (Common Type System) ................................................................................................ 36
FCL and BCL .......................................................................................................................... 37
FCL (Framework Class Library) ............................................................................................. 37
Introduction to Visual Studio ............................................................................................... 38
What is Visual Studio ............................................................................................................ 38
Versions of Visual Studio ...................................................................................................... 38
System Requirements of Visual Studio 2019: ...................................................................... 39
Project .................................................................................................................................. 40
Solution ................................................................................................................................ 40
File Types of .NET ................................................................................................................. 40
Folder Structure of .NET Project in Visual Studio ................................................................ 41
1
.NET Fundamentals
Introduction to .NET
What is .NET?
• .NET is an “application development platform”, which is used to develop desktop, web and mobile applications.
• “Application” is a program (collection of instructions) that can run based on the operating
system.
• “Application Development Platform” is a software tool, based on which you can develop
applications.
Parts of .NET
3. Xamarin.NET
1. C#.NET
machine.
2. ASP.NET
architecture”.
3. Xamarin.NET
History of .NET
History of .NET
• 1998: Microsoft has completed developing the new language and named it as Simple
Managed C (SMC).
• 1999: Microsoft renamed “SMS” as “C#” and wants to integrate C#, ASP. They named the
integrated development platform as “NGWS” (Next Generation Windows Services).
Versions of .NET
Steps:
1. Source Code: The source code of the program is written in “.cs” file.
2. Compilation Process: “CSC” (C Sharp Compiler) compiles (converts) the program from
Language)” (also called as “byte code”). The “MSIL code” will be saved in “.exe” file. This
EXE file can’t execute directly. The MSIL is neither understandable by the programmer, nor
by operating system.
3. Execution Process: CLR (Common Language Runtime) converts the program from MSIL
language at “EXE file” to “native machine language” (based on the current operating
system). Operating System executes the “native machine language”. Then we will get
output.
▪ The .net programs are converted into “MSIL language” first; and then converted into “native
machine language”.
▪ The MSIL code will be stored in "EXE" file. Ex: filename.exe. The “native machine language”
▪ Once the code is converted into MSIL, it doesn't matter in which .net language it is originally
developed. So for all .net languages, we can have a common runtime engine called "CLR".
▪ To run any type of .net program (app), CLR must be installed in the computer.
▪ CLR will be started automatically when the .net application execution starts. CLR performs
▪ CLR reads the “MSIL code” from the EXE file, converts the same into “native machine code”,
gives the same to the operating system and then operating system executes the native
machine code; then the user gets the output. So CLR is helps the operating system while
▪ CLR will be installed automatically as a part of “.NET Framework” software. CLR must be
1. Memory Manager: “Memory Manager” is a sub component in CLR, which allocates memory
2. Garbage Collector: “Garbage Collector” is a sub component in CLR, which deletes the
variables and objects that are created during the program, automatically at the end of the
program execution.
3. Class Loader: “Class Loader” is a sub component in CLR, which loads a class on-demand.
When we try to access a class in the program for the first time, then the “Class Loader”
searches for the class in the entire program, loads the class into the memory, and it passes
the class to JIT compiler. That means if we don’t call a class, it will not be loaded into
memory. This avoids un-necessary loading of the classes, if we don’t require them. So it
improves performance.
4. JIT (Just-In-Time) Compiler: “JIT Compiler” is a sub component in CLR, which converts the
“MSIL code” into “native machine language” (based on current operating system).
5. Thread Manager: “Thread Manager” is a sub component in CLR, which manages the
threads of the program. It gives necessary instructions to the processor, which thread is to
necessary instructions to the operating system, which code should be executed when an
7. Security Manager: “Security Manager” is a sub component in CLR, which takes care about
• It is the “Software Development Kit (SDK)”, which contains many components such as CIL,
CLR, FCL, CLS, which is used to develop & run the .net applications.
https://www.microsoft.com/en-us/download/details.aspx?id=55167
Windows 8
Windows 8.1
Windows 10
• “.NET Framework Architecture” explains the list of components of .NET Framework, and
Explanation:
• "WinForms", "ASP.NET", and “Other Frameworks” work based on "ADO.NET" and "BCL".
• Finally, the programmers are writing the programs by using the languages called “C#.NET,
“VB.NET” etc.
▪ “CLS” is the set of rules, based on which all .net languages (C#.NET, VB.NET, VC++.NET etc.)
are developed.
▪ The common rules are about literals, operators, identifiers, data types, type conversion, object
▪ “CTS” is a set common data types, based on which, the data types of all .net languages
▪ Thus, we achieve the uniform data types among all .net languages.
1. SByte
2. Byte
3. Short
4. UShort
5. Int32
6. UInt32
7. Int64
8. UInt64
9. Single
10. Double
11. Decimal
12. Char
13. String
14. Boolean
▪ .NET provides a set of classes and interfaces, based on which we can develop .net applications.
▪ The “DLL (Dynamic Link Library)” file is a collection of namespaces; Namespace is a collection
1. BCL: BCL is a set of classes and interfaces, which can be used in all types of applications.
2. WinForms: This is a set of classes and interfaces, which can be used only in windows
applications.
3. ASP.NET: This is a set of classes and interfaces, which can be used only in web applications.
4. ADO.NET: This is a set of classes and interfaces, which can be used in all types of
• Visual Studio is the “IDE” (Integrated Development Environment), where you can write all
C: drive
Operating System Windows 7 + Service Pack 1 Windows 10
Windows 8.1
Windows 10
Project
• When we compile the project, Visual Studio generates only one EXE file for the entire
project, which contains the compiled source code (in MSIL language) of all the files of the
same project.
Solution
.exe Executable file The EXE file contains the compiled source code of a
project. For every project, a separate EXE file will be
created.
.config Configuration File The configuration file contains the configuration
settings of a project.
Solution Folder
Project Folder
o filename.cs
o App.config
o projectname.csproj
o bin\projectname.exe
solutionname.sln
Go to http://www.visualstudio.com
Click on “Run”.
Click on “Continue”.
Check the checkboxes “.NET desktop development” and “ASP.NET and web development”.
Click on “Install”.
Click on “Restart”.
If you have Microsoft account already and click on “Sign in” and complete the login process.
If you don’t have Microsoft account, click on “Sign up” and complete the registration process.
Note: If you don’t want to login, click on “Not now, may be later”; but then Visual Studio expires in
30 days.
If you click on “Sign up”, you will get the following page.
Click on “Next”.
You will get a security code to your email. Login into your gmail, check the code that you have
received and enter it in this page.
Now click on “Sign in” in Visual Studio and enter the email.
2
C#.NET – Language
Fundamentals
Introduction to C#.NET
What is C#.NET:
C#.NET is the .NET’s most popular programming language, which is used to create stand-alone
applications (console applications and windows applications, windows services) primarily.
• C#.NET programs run based on the CLR (.NET run time environment).
Versions of C#.NET
Tokens of C#.NET
No
1 Keywords abstract, as, base, bool, break, byte, case, catch, char, class, const, continue,
decimal, default, delegate, do, double, else, enum, event, false, finally, float,
for, foreach, goto, if, in, int, interface, internal, is, long, namespace, new,
null, object, out, override, private, protected, public, readonly, ref, return,
sbyte, sealed, short, sizeof, static, string, struct, switch, this, throw, true,
try, typeof, uint, ulong, ushort, using, virtual, void, while, async, await, from,
123$”
• Class names, Interface names, Namespace names, Structure names, Method names,
You must follow the below rules while giving name for identifier.
• Console applications are the programs that run on “Command Prompt” window.
• In console applications, all the input and output will be in the form of characters only.
• Console applications are not used in real time, but good for learning programming basics
• Console application must have atleast one class; which is called as “Main class”.
• The “Main class” must contain atleast one method; which is called as “Main method”.
• When the program execution starts the “Main” method will be automatically executed.
• The Main method should be “static” method, because it should be called without creating
Syntax:
class classname
{
static void Main()
{
}
}
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
static void Main()
{
System.Console.Write("Hello World");
}
}
Output
1. System.Console.Write()
2. System.Console.WriteLine()
3. System.Console.ReadKey()
4. System.Console.ReadLine()
5. System.Console.Clear()
1. System.Console.Write()
• This statement is used to display the given value on the command prompt window.
• After printing the value, the cursor will be kept in the same line.
• Syntax: System.Console.Write(value);
• Example: System.Console.Write(100);
2. System.Console.WriteLine()
• This statement is used to display the given value on the command prompt window.
• After printing the value, the cursor will be automatically moved to the next line.
• Syntax: System.Console.WriteLine(value);
• Example: System.Console.WriteLine(100);
3. System.Console.ReadKey()
• This statement is used to wait until the user presses any key on the keyboard.
• Syntax: System.Console.ReadKey();
• Example: System.Console.ReadKey();
4. System.Console.ReadLine()
• Syntax: System.Console.ReadLine();
• Example: System.Console.ReadLine();
5. System.Console.Clear()
• Syntax: System.Console.Clear();
• Example: System.Console.Clear();
System.Console.WriteLine – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
System.Console.WriteLine("Hello");
System.Console.WriteLine("Hello");
System.Console.WriteLine("Hello");
System.Console.ReadKey();
}
}
Output
System.Console.ReadKey – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//display message
System.Console.WriteLine("Hello");
//display message
System.Console.WriteLine("Hello");
//display message
System.Console.WriteLine("Hello");
Output
Press Enter.
Press Enter.
System.Console.Clear - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//display message
System.Console.WriteLine("Hello");
//wait for pressing any key on the keyboard
System.Console.ReadKey();
//clear the screen
System.Console.Clear();
//display message
System.Console.WriteLine("how");
//wait for pressing any key on the keyboard
System.Console.ReadKey();
//clear the screen
System.Console.Clear();
//display message
System.Console.WriteLine("are you");
//wait for pressing any key on the keyboard
System.Console.ReadKey();
}
}
Output
Press Enter.
Press Enter.
Variables
Variables
• A variable is a named memory location in RAM, to store a particular type of value
temporarily while the program is running.
• All the variables must be declared before its usage. While declaring variables, data type is
to be specified. Based on the data type, the amount of memory to be allocated will be
decided. Once a variable is declared, we can’t change the “variable name” or “variable’s data
type”.
• The variables memory will be allocated when the program execution starts; and all the
variables will be deleted (de-allocated) from memory automatically, at the end of the
program.
• A variable can store only one value. If you assign another value, the old value will be
overwritten.
datatype variablename ;
variablename = value ;
variablename
Variables - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create a variable
int x;
//set value into the variable
x = 10;
//get the value of variable
System.Console.WriteLine(x);
//wait for pressing any key on the keyboard
System.Console.ReadKey();
}
}
Output
Data Types
Data Type
• A data type is a concept, which specifies the type of the data that is to be stored in a
variable.
• C# compiler automatically treats a “number without decimal part” as “int” data type, if it is
within the maximum limit of “int” data type.
• C# compiler automatically treats a “number without decimal part” as “long” data type, if it
exceeds the limit of “int” data type.
• C# compiler automatically treats a number with decimal part as “double” data type.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables for all numerical data types
sbyte a = 10;
byte b = 20;
short c = 30;
ushort d = 40;
int e = 50;
uint f = 60;
long g = 70;
ulong h = 80;
float i = 90.23F;
double j = 100.23489;
decimal k = 110.882932M;
Output
NumericalDataType.MinValue
• This statement returns the minimum value of the specified numerical data type.
• Syntax: datatype.MinValue
• Ex: int.MinValue
NumericalDataType.MaxValue
• This statement returns the maximum value of the specified numerical data type.
• Syntax: datatype.MaxValue
• Ex: int.MaxValue
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//get the minimum value of "int" data type
int min = int.MinValue;
Output
char - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variable of "char" data type
char ch = 'A';
//display the value of the variable
System.Console.WriteLine(ch);
System.Console.ReadKey();
}
}
Output
String
String
• String: A string is a group of characters.
• All the names are strings. Ex: person names, city names, country names etc.
• String may contain alphabets, numbers, spaces and also special symbols.
• Alpha-numerical values are also treated as strings. Ex: car number, phone number, bank
ifsc codes etc.
String - Example
Creating Project
• Open Visual Studio 2019.
Program.cs
class Program
{
static void Main()
{
//create a variable
string s = "Hello 123 $#&";
System.Console.ReadKey();
}
Output
Bool - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variable of "bool" data type
bool b = true;
//display the value of the variable
System.Console.WriteLine(b);
System.Console.ReadKey();
}
}
Output
Operators
What is Operator:
• Operator is a symbol to perform an operation.
• An operator receives one or two operands and perform some operation & returns the
result.
• Types of operators:
1. Arithmetical Operators
2. Assignment Operators
4. Relational Operators
5. Logical Operators
6. Concatenation Operator
7. Conditional Operator
Arithmetical Operators
Arithmetical Operators
1 + Addition
2 - Subtraction
3 * Multiplication
4 / Division
5 % Remainder
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create two variables of "double" data type
double a = 10, b = 3;
//addition
double c = a + b;
//subtraction
double d = a - b;
//multiplication
double e = a * b;
//division
double f = a / b;
//remainder
double g = a % b;
System.Console.ReadKey();
}
}
Output
Assignment Operators
Assignment Operators
1 = Assigns to
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create two variables of "int" data type
int a = 100;
int b;
//get the value from "a" and set the same into "b"
b = a;
//display the values of "a" and "b"
System.Console.WriteLine(a); //Output: 100
System.Console.WriteLine(b); //Output: 100
//a = a + 10
a += 10;
System.Console.WriteLine(a); //Output: 110
//a = a - 10
a -= 10;
System.Console.WriteLine(a); //Output: 100
//a = a * 3
a *= 3;
System.Console.WriteLine(a); //Output: 300
//a = a / 3
a /= 3;
System.Console.WriteLine(a); //Output: 100
//a = a % 30
a %= 30;
System.Console.WriteLine(a); //Output: 10
System.Console.ReadKey();
}
}
Output
1 ++ Increment
2 -- Decrement
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create a variable of "int" data type
int n = 10;
//display the value of "n"
System.Console.WriteLine(n); //Output: 10
//n = n + 1
n++;
System.Console.WriteLine(n); //Output: 11
//n = n - 1
n--;
System.Console.WriteLine(n); //Output: 10
System.Console.ReadKey();
}
}
Output
Relational Operators
Relational Operators
1 == Equal to
2 != Not equal to
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create two variables of "long" data type
long x = 1000, y = 2000;
System.Console.ReadKey();
}
}
Output
Logical Operators
Logical Operators
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create 3 variables of "int" data type
int a = 10, b = 20, c = 10;
//and
bool result1 = ((a == b) && (b > c));
System.Console.WriteLine(result1); //Output: false
//or
bool result2 = ((a == b) || (b > c));
System.Console.WriteLine(result2); //Output: true
//not
System.Console.ReadKey();
}
}
Output
Concatenation Operator
Concatenation Operator
• String + String
• String + Number
• Number + String
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create strings
string s1 = "peers";
string s2 = "tech";
string s3;
Output
Conditional Operator
Conditional Operator
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create a variable of "int" data type
int n = -100;
Output
Control Statements
• If
• Switch-case
• While
• Do-While
• For
• Break
• Continue
• Goto
If
If
if (condition)
{
Your code here
}
else
{
Your code here
}
}
else
{
if (condition)
{
Your code here
}
else
{
Your code here
}
}
If - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int n = 100;
Output
If – Else - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int n = 150;
Output
Else – If - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int a = 10, b = 20;
Output
Nested If - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variables
int a = 150, b = 100;
string msg;
//outer if
if (a >= b)
{
//inner if
if (a > b)
{
msg = "a is greater than b";
}
//"else" for "inner if"
else
{
msg = "a is equal to b";
}
}
//"else" for "outer if"
else
{
msg = "a is less than b";
}
System.Console.WriteLine(msg); //Output: a is greater than b
System.Console.ReadKey();
}
}
Output
Switch – Case
Switch-case
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
While
while
While - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//initialization
int i = 1;
//condition
while (i <= 10)
{
System.Console.WriteLine(i);
i++; //incrementation
}
System.Console.ReadKey();
}
}
Output
Do – While
do-while
Do – While - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
for
for
for - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
Break
Break - Example
Creating Project
• Open Visual Studio 2019.
Program.cs
class Program
{
static void Main()
{
//initialization; condition; incrementation
for (int i = 1; i <= 10; i++)
{
System.Console.WriteLine(i);
if (i == 6)
break; //stop the loop when "i" value is reached to "6".
}
System.Console.ReadKey();
}
}
Output
Continue
continue
1 Continue continue; It skips the current iteration and jumps to the next iteration.
Continue - Example
Creating Project
• Open Visual Studio 2019.
Program.cs
class Program
{
static void Main()
{
//initialization; condition; incrementation
for (int i = 1; i <= 10; i++)
{
if (i == 6)
continue; //skip "6" and go to "7"
System.Console.WriteLine(i);
}
System.Console.ReadKey();
}
}
Output
Goto
goto
1 Goto goto LabelName; It jumps to the specified label, within the same
method.
Goto - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
System.Console.WriteLine("one");
System.Console.WriteLine("two");
//jump to mylabel
goto mylabel;
System.Console.WriteLine("three");
System.Console.WriteLine("four");
System.Console.WriteLine("five");
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//outer loop (5 times)
for (int i = 1; i <= 5; i++)
{
//inner loop (10 times)
for (int j = 1; j <= 10; j++)
{
System.Console.Write(j);
System.Console.Write(", ");
}
System.Console.WriteLine();
}
System.Console.ReadKey();
}
}
Output
o These are also imperative programming languages with control structures like if,
switch-case, while, do-while, for, break, continue, return etc.
o Ex: C
o These are also procedural programming languages with objects and classes.
• OOP is followed in almost-all modern programming languages such as C++, VC++, Java,
C#.NET, VB.NET etc.
• Advantages of OOP:
3. Security: The members of a class can be private or public. The private members
can’t be accessible outside the class.
Object
• An object represents a real world item. For example, you are an object, your laptop is an
object, and your city is an object.
Fields
Methods
Example:
Class
For example, there are 10 students. Each student is an object. So 10 students are
10 objects. In each student, we want to store "studentid", "studentname", "marks".
So first we have to create a class called "Student" and we have to create
"studentid", "studentname", "marks" as members of the "Student" class. Then we
have to create objects based on the class.
• A class specifies the list of Fields and methods that you want to store in every object.
• So you must create an object for the class, in order to access its members.
• Class is a just “model” only; no actual data will be stored in class. Object is the “real
instance”; actual data will be stored in object only.
1. Memory will be allocated in RAM (Random Access Memory) for the object.
▪ Numerical Fields: 0
▪ Bool: false
• All the objects are stored in RAM (temporarily). Objects are created when the program
execution starts. Objects are automatically deleted (erased from memory) when the
program execution ends.
Example:
Reference variables
• You should store the “address of an object” in the reference variable; through the
reference variable only, we can access the object, in further statements.
class Classname
{
Class members here
}
Classname Referencevariablename ;
new Classname ( );
• All the reference variables are stored in an area called "stack" in RAM. For every method
call, a “stack” will be created automatically.
• All the objects are stored in an area called "heap" in RAM. For entire application, a “heap”
will be created.
• You must store the address of an object into the reference variable; otherwise you can't
access the object.
Principles of OOP
1) Encapsulation
2) Abstraction
3) Inheritance
4) Polymorphism
Encapsulation:
• Fields are variables that stores the data; Methods are functions that manipulates
the data.
Abstraction:
Inheritance:
• As a result of inheritance, all the members of parent class are accessible in child
class.
Polymorphism:
Types of polymorphism:
▪ You will create a reference variable for the parent class (or) interface;
assign the reference of child class’s object; and call the method. Then the
current child class’s method will be called.
Access Modifiers
Access Modifiers
• Access Modifiers are also called as “Access Specifiers”, which are used to specify the access
privileges of a member of a class.
• Access Modifiers can be applicable to all types of members (such as Field, method,
constructor, property etc.) that tell which classes can access the member and which can’t.
• Access Modifiers are used to create security for the member of a class.
1. private (default)
2. protected
3. internal
4. protected internal
5. public
1. private: The private members are accessible “only within the same class”. These are
not accessible in any other classes. “Private” is the default access modifier in c#.net.
That means, if you don’t specify any access modifier, by default, “private” will be
applied.
2. protected: The protected members are accessible “within the same class” and also
within the “child classes at same project” and “child classes at other projects”. These
are not accessible in any other classes. Note: The other projects must add the
reference of current project.
3. internal: The internal members are accessible “anywhere within the same project”.
These are not accessible in any classes at other projects.
Creating Project
• Open Visual Studio 2019.
Program.cs
namespace AccessModifiersExample
{
//same class
class Class1
{
private int a; //private member
protected int b; //protected member
internal int c; //internal member
protected internal int d; //protected internal member
public int e; //public member
System.Console.WriteLine("Done");
System.Console.ReadKey();
}
}
}
Output
• Access Modifiers can be used for classes also, to specify where the class is accessible.
1. internal (default)
2. public
3. private
1. internal: The internal classes can be accessible within the same project only. They are
not accessible in other projects. “Internal” is the default access modifier for the classes.
2. public: The public classes can be accessible anywhere (within the same project and also
in other projects too).
3. private: Only inner classes can be “private classes”. The “private inner classes” can be
accessible within the same outer classes only. They are not accessible in other classes.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public int a, b;
}
class Program
{
static void Main()
{
Sample s1; //create reference variable
s1 = new Sample(); //create object
s1.a = 10;
s1.b = 20;
//display values
System.Console.WriteLine(s1.a); //Output: 10
System.Console.WriteLine(s1.b); //Output: 20
System.Console.WriteLine(s2.a); //Output: 30
System.Console.WriteLine(s2.a); //Output: 40
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Student
{
public int StudentId;
public string StudentName;
public int Marks;
class Program
{
static void Main()
{
//create reference variables
Student s1, s2;
//create objects
s1 = new Student();
s2 = new Student();
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Employee
{
public int EmployeeId;
public string EmployeeName;
public int Salary;
}
class Program
{
static void Main()
{
//create reference variables
Employee s1, s2;
//create objects
s1 = new Employee();
s2 = new Employee();
System.Console.ReadKey();
}
}
Output
Static Fields
• Static Fields are used to common data that belongs to all the objects. Non-Static Fields are
stored in the objects; Static Fields are stored outside the objects. Static members are not
accessible with reference variable, but accessible with “class name”.
1 By default, all the Fields are non-static Fields. Static Fields are created using “static” keyword.
These are not created with a keyword called
“static”.
2 Non static Fields are stored in the object. That For static Fields, memory will not be allocated in
means when you create an object for the class, the object. When you access the class name for
the memory will be allocated for all the non- the first time in the main method, then memory
static Fields in the object. will be allocated for the static Fields.
3 Non-static Field’s memory will be allocated Static Field’s memory will be allocated only once
separately for every object of the class. for entire project.
4 Non-static Fields accessible with reference Static Fields are accessible with class.
variable.
5 If you don’t create an object for the class, no If you don’t access the class in the entire
memory will be allocated for non-static Field. program, no memory will be allocated for static
Fields.
6 Use non-static Fields if you want to store Use static Fields if you want to store common
object-specific data (which is different for data that belongs to all the objects.
each object).
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace StaticFieldsExample
{
//creating a class called "Student".
class Student
{
//instance Fields (or) non-static Fields
public int studentid;
public string studentname;
public int marks;
class Program
{
Console.ReadKey();
}
}
}
Output
Constant Fields
Constant Fields
• Constant Field’s value can’t be changed in the rest life of the object.
• Constant Fields must be initialized along with the declaration. Those can’t be initialized in
the constructor.
• Constant Fields are by default “static”; so they are accessible without creating an object for
the class, using class name.
• Syntax:
Creating Project
• Open Visual Studio 2019.
Program.cs
class Sample
{
public const int NoOfMonthsInYear = 12;
}
class Program
{
static void Main()
{
System.Console.WriteLine(Sample.NoOfMonthsInYear);
System.Console.ReadKey();
}
}
Output
ReadOnly Fields
Read-only Fields
• Read-only Fields must be initialized along with the declaration or in the constructor. It
must be initialized before constructor ends.
• Read-only Field’s value can’t be changed in the rest life of the object.
• Syntax:
3 Should be initialized along with its Should be initialized either along with its
declaration. declaration or in the constructor.
4 Useful to initialize a fixed value only. Useful to initialize fixed value or result of a
calculation.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
Program.cs
class Sample
{
public readonly int NoOfMonthsInYear = 12;
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
System.Console.WriteLine(s.NoOfMonthsInYear);
System.Console.ReadKey();
}
}
Output
Methods
Methods
▪ The method is a “function” inside the class.
▪ Arguments: The value that are passed from calling portion to the method definition are
called arguments or parameters. The data type of argument is called “argument type”.
Every argument can be different type.
▪ Return Value: The value that is passed from method definition to the calling portion is
called “return value”. A method can return only one value maximum. The data type of
return value is called “return type”. If a method doesn’t return any value, its return type
should be said as “void”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public void Address()
{
System.Console.WriteLine("Ameerpet");
System.Console.WriteLine("Hyderabad");
System.Console.WriteLine("India");
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
s.Address();
s.Address();
s.Address();
System.Console.ReadKey();
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public int Add(int a, int b)
{
int c;
c = a + b;
return (c);
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
System.Console.WriteLine(s.Add(10, 20));
System.Console.WriteLine(s.Add(50, 30));
System.Console.ReadKey();
}
}
Output
Scope of Variables
Scopes of Variables
▪ “Life time” of the variable is called as “scope”.
1. Local variables:
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Person
{
public int age = 20;
class Program
{
static void Main()
{
Person p;
p = new Person();
System.Console.WriteLine(p.age);
p.Birthday();
System.Console.WriteLine(p.age);
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Class1
{
public double a, b;
public double sum;
class Program
{
static void Main()
{
Class1 c1;
c1 = new Class1();
System.Console.Write("Enter first number : ");
c1.a = System.Convert.ToDouble(System.Console.ReadLine());
System.Console.Write("Enter second number : ");
c1.b = System.Convert.ToDouble(System.Console.ReadLine());
c1.Add();
System.Console.WriteLine("Sum: " + c1.sum);
c1.Subtract();
System.Console.WriteLine("Difference: " + c1.difference);
c1.Multiply();
System.Console.WriteLine("Product: " + c1.product);
c1.Divide();
System.Console.WriteLine("Quotient: " + c1.quotient);
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
Program.cs
class User
{
public string Username;
public string Password;
public string Message;
public void CheckLogin()
{
if (Username == "admin" && Password == "manager")
{
Message = "Successful login";
}
else
{
Message = "Invalid login";
}
}
}
class Program
{
static void Main()
{
User u;
u = new User();
System.Console.Write("Enter username : ");
u.Username = System.Console.ReadLine();
System.Console.Write("Enter password : ");
u.Password = System.Console.ReadLine();
u.CheckLogin();
System.Console.WriteLine(u.Message);
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Student
{
public int studentid;
public string studentname;
public double marks1, marks2, marks3, totalmarks, averagemarks;
public string grade;
public void calculatetotalmarks()
{
totalmarks = marks1 + marks2 + marks3;
}
public void calculateaveragemarks()
{
averagemarks = totalmarks / 3;
}
public void calculategrade()
{
if (marks1 < 35 || marks2 < 35 || marks3 < 35)
{
grade = "Fail";
}
else if (averagemarks >= 80 && averagemarks <= 100)
{
grade = "A grade";
}
else if (averagemarks >= 60 && averagemarks < 79)
{
grade = "B grade";
}
else if (averagemarks >= 50 && averagemarks < 59)
{
grade = "C grade";
}
else if (averagemarks >= 35 && averagemarks < 49)
{
grade = "D grade";
}
}
}
class Program
{
static void Main()
{
Student s1, s2;
s1 = new Student();
s2 = new Student();
System.Console.Write("Enter first student id: ");
s1.studentid = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first student name: ");
s1.studentname = System.Console.ReadLine();
System.Console.Write("Enter first student marks 1: ");
s1.marks1 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first student marks 2: ");
s1.marks2 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.Write("Enter first student marks 3: ");
s1.marks3 = System.Convert.ToInt32(System.Console.ReadLine());
System.Console.WriteLine();
s1.calculatetotalmarks();
s1.calculateaveragemarks();
s1.calculategrade();
s2.calculatetotalmarks();
s2.calculateaveragemarks();
s2.calculategrade();
System.Console.ReadKey();
}
}
Output
"this" keyword
this keyword
• “this” is a keyword, which represents “current object”, based on which, the method or
constructor was called.
• “this” keyword can be used in non-static methods and non-static constructors only. “this”
keyword can’t be used in static methods or static constructors.
• By default, the usage of “this” keyword is optional. By default system referrers to “current
object”. But when a local variable name and Field name are same, then by default the
system refers to local variable. Then if you want to access Field name, you must use
“this.Field”. So in that way “this” keyword is must to use.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Class1
{
public int n = 10;
public void Display()
{
int n = 20;
System.Console.WriteLine("data member: " + this.n); //Output: 20
System.Console.WriteLine("local variable: " + n); //Output: 20
System.Console.WriteLine();
}
}
class Program
{
static void Main()
{
Class1 c1;
c1 = new Class1();
c1.Display();
System.Console.ReadKey();
}
}
Output
Static Methods
Static Methods
• Non-static methods are used to manipulate non-static Fields; Static methods are used to
manipulate static Fields only. Static methods can be called with class name only.
1 By default, all the methods are non- Static methods are created using “static”
static methods. These are not created keyword.
with a keyword called “static”.
2 Non-static methods can access both Static methods can access only static members.
non-static members and non-static Static methods can’t access non-static members.
members. However, if you create an object for the class in
the static methods, then you can access any non-
static members though the object, in the static
method.
3 Non-static methods are accessible with Static methods are accessible with class only.
object only. Non-static methods are not Static methods are accessible without creating an
accessible without creating an object object for the class. Static methods are not
for the class. accessible with an object.
4 We can use “this” keyword in the non- We can’t use “this” keyword in the static
static methods, because non-static methods, because static methods are called with
methods are called with an object. class only, without an object.
5 Use non-static methods, if you want to Use static Fields if you want to perform some
perform some operation based on non- operation based on static Fields.
static Fields.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public static int n = 10;
public static void Increment()
{
n++;
}
}
class Program
{
static void Main()
{
System.Console.WriteLine(Sample.n); //Output: 10
Sample.Increment();
System.Console.WriteLine(Sample.n); //Output: 11
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Person
{
public int age;
}
class Sample
{
public void Birthday(Person p)
{
p.age++;
}
class Program
{
static void Main()
{
Person p;
p = new Person();
Sample s;
s = new Sample();
p.age = 20;
s.Birthday(p);
System.Console.WriteLine(p.age);
System.Console.ReadKey();
}
}
Output
• If you do so, we can access the source class’s object, through the Field of destination class.
Then the data type of the Field should be “source class” type.
• For example, assume you have a class called “Hyderabad”. You can create an object for
“Hyderabad” class and store its reference in a Field called “h” in another class called “India”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Hyderabad
{
public string Charminar = "Hyderabad.Charminar";
public string Golconda = "Hyderabad.Golconda";
class India
{
public Hyderabad h = new Hyderabad();
}
class Program
{
static void Main()
{
India i;
i = new India();
System.Console.WriteLine(i.h.Charminar);
System.Console.WriteLine(i.h.Golconda);
System.Console.ReadKey();
}
}
Output
Default Arguments
▪ While calling the method, if you don’t supply a value for the parameter, then the default
value will be assigned to the parameter automatically.
▪ If you supply a value for the parameter, then the given value will be assigned to the
parameter, as usual.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public void Display(int n = 10)
{
System.Console.WriteLine("n value is " + n);
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
s.Display(50); //Output: 50
s.Display(100); //Output: 100
s.Display(); //Output: 10
System.Console.ReadKey();
}
}
Output
Named Parameters
▪ “Named parameters” concept allows the programmer to pass a value, based on the
“parameter name”, instead of depending on the order of arguments, while calling a method.
▪ Syntax:
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public void Display(int x, int y)
{
class Program
{
static void Main()
{
Sample s;
s = new Sample();
s.Display(y: 10, x: 20); //Output: x is 20, y is 10
System.Console.ReadKey();
}
}
Output
Methods Overloading
▪ “Method Overloading” concept is “writing multiple methods with same name within the
same class, with different types of arguments”.
▪ When you call a method, it calls the method, which matches with the given arguments.
▪ Example:
⬧ Method1()
⬧ Method1(int a)
⬧ Method1(double d)
⬧ Method1(int a, double d)
⬧ Method1(double d, int a)
⬧ Method1(string s)
etc.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
//method 1
public void Display(int n)
{
System.Console.WriteLine("int: " + n);
}
//method 2
public void Display(string s)
{
System.Console.WriteLine("string: " + s);
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a = 100;
string b = "hello";
s.Display(a); //calls method1
s.Display(b); //calls method2
System.Console.ReadKey();
}
}
Output
Types of Parameters
Types of Parameters
1. Call by value
2. Call by reference
3. Call by output
Call by Value
▪ The changes made to the “argument variable” will not be effected in “original variable”.
Call by Reference
▪ The changes made to the “argument variable” will be effected automatically in the “original
variable”.
▪ This is implemented using “ref” keyword with “original variable” and “argument variable”.
Call by Output
▪ This is same as “call by reference”.
▪ The difference between “call by reference” and “call by output” is: the value of “original
variable” will not be transferred to the “argument variable”; but the value comes back from
“argument variable” to “original variable”, at the end of method.
▪ The “argument variable” must be set to a value before the method definition ends.
▪ This is implemented using “out” keyword in both calling portion and receiving portion.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public void Method1(int x)
{
System.Console.WriteLine(x); //Output: 100
x = 150;
System.Console.WriteLine(x); //Output: 150
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a = 100;
s.Method1(a);
System.Console.WriteLine(a); //Output: 100
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public void Method1(ref int x)
{
System.Console.WriteLine(x); //Output: 100
x = 150;
System.Console.WriteLine(x); //Output: 150
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a = 100;
s.Method1(ref a);
System.Console.WriteLine(a); //Output: 150
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
public void Method1(out int x)
{
x = 150;
System.Console.WriteLine(x); //Output: 150
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
int a;
s.Method1(out a);
System.Console.WriteLine(a); //Output: 150
System.Console.ReadKey();
}
}
Output
Type Conversion
1. Implicit Casting
3. Parsing
4. Conversion Methods
Implicit Casting
• C# compiler automatically converts a value from “lower numeric data type” to “higher
numeric data type”. This automatic conversion is called “implicit casting”.
• We will compare the no. of data types of the data type, to identify whether it is a lower
data type / higher data type.
• Ex: “int” to “long”. Here “int” is 4 bytes and “long” is 8 bytes. So, it is “lower” to “higher”.
• As implicit casting will be performed automatically, there is no syntax for this. Directly you
can assign a value of “lower numeric data type” to “higher numeric data type”.
Creating Project
• Open Visual Studio 2019.
Program.cs
class Program
{
static void Main()
{
//A variable of "lower numerical data tye" i.e. "short" (2 bytes)
short a = 100;
//A variable of "higher numerical data tye" i.e. "int" (4 bytes)
int b;
//short to int = lower to higher = implicit casting
b = a;
System.Console.WriteLine(a); //Output: 100
System.Console.WriteLine(b); //Output: 100
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variable of "int" data type
int a = 100;
//create variable of "short" data type
short b;
//convert the value from "int" data type "short" data type (higher to
lower), using "type casting" concept
b = (short)a;
System.Console.WriteLine(a); //Output: 100
System.Console.WriteLine(b); //Output: 100
System.Console.ReadKey();
}
}
Output
Parsing
▪ It is used to convert a value from “string” data type to “any numerical data type”.
▪ Syntax: NumericalDataTypeName.Parse(value);
▪ Rule: The string value should contain digits only; otherwise it can’t be converted into
numerical data type.
▪ Note: If the string value is not convertible into “numerical data type”, you will get exception
(run time error).
Parsing - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create variable of "string" data type
string s = "100";
Output
TryParse
▪ When you are converting "alphabets" or "alpha-numeric value" from "string" data type to
"numeric", you will get a run time error (exception).
▪ "TryParse" is a pre-defined method, which is used to avoid while converting the value from
"string" to "numerical data type".
▪ It tries to convert the string to numerical data type. If conversion is successful, it returns
"true". If conversion is failed, it returns "false". If conversion is successful, it stores the
result value in the destination variable; otherwise, it stores 0 (zero) in the destination
variable.
TryParse - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
Output
TryParse – Example 2
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create string and integer
string s = "hyderabad1234";
int n;
Output
Conversion Methods
Conversion Methods
▪ C#.NET provides a set of conversion methods, which are used to convert a value from “any
standard data type” to “any other standard data type”.
▪ Syntax: System.Convert.MethodName(value);
▪ Note: You have to use the conversion method, based on the destination data type (target
data type), into which you want to convert.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Program
{
static void Main()
{
//create a variable of "double" data type
double d = 100;
//create a variable of "int" data type
int n;
//convert the value from "double" data type to "int" data type", using
conversion method
n = System.Convert.ToInt32(d);
System.Console.WriteLine(d); //Output: 100
System.Console.WriteLine(n); //Output: 100
System.Console.ReadKey();
}
}
//Note: Try all the remaining conversion methods.
Output
Constructors
• Constructors are special methods of the class, which initializes the Fields and perform any
initialization process, which will be called automatically when an object is created for the
class.
• Constructors are used to receive a set of parameters and initialize those parameters into
respective Fields.
• For example, you have a class with Fields. So your constructor can receive 3 arguments and
assign those arguments into Fields respectively. However, if you don’t want to initialize all
the Fields, you can receive less no. of arguments also. For example, you can initialize 1 or 2
Fields also.
o Memory will be allocated for the object in RAM (in Heap of RAM).
Syntax of Constructor
public Classname(datatype variable1, datatype variable2, …)
{
Field1 = variable1;
Field2 = variable2;
…
}
Types of Constructor
Default Constructor
• As per the rules of c#.net, a class should have a constructor. If you don’t create a
constructor in the class, .net creates an empty constructor (implicit constructor or default
constructor) automatically and internally.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
//Fields
public int a, b;
//constructor
public Sample()
{
a = 10;
b = 20;
}
}
class Program
{
static void Main()
{
Sample s;
s = new Sample();
System.Console.WriteLine(s.a);
System.Console.WriteLine(s.b);
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Sample
{
//Fields
public int a, b;
//constructor
public Sample(int x, int y)
{
a = x;
b = y;
}
}
class Program
{
static void Main()
{
//creating reference variable
//get data
System.Console.WriteLine("s1.a is " + s1.a);
System.Console.WriteLine("s1.b is " + s1.b);
System.Console.WriteLine("s2.a is " + s2.a);
System.Console.WriteLine("s2.b is " + s2.b);
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//create a class called "Student" with 3 Fields called "studentid",
"studentname" and "marks"
class Student
{
//Fields
public int studentid;
public string studentname;
public int marks;
class Program
{
static void Main()
{
//create 3 reference variables of "Student" type
Student s1, s2, s3;
//create 3 objects of "Student" type
s1 = new Student(101, "Scott", 70);
s2 = new Student(102, "Allen", 80);
s3 = new Student(103, "John", 90);
//get data from first object
System.Console.WriteLine("First student:");
System.Console.WriteLine("Student ID: " + s1.studentid);
System.Console.WriteLine("Student Name: " + s1.studentname);
System.Console.WriteLine("Marks: " + s1.marks);
System.Console.WriteLine("----------------------------------");
//get data from second object
System.Console.WriteLine("Second student:");
System.Console.WriteLine("Student ID: " + s2.studentid);
System.Console.WriteLine("Student Name: " + s2.studentname);
System.Console.WriteLine("Marks: " + s2.marks);
System.Console.WriteLine("---------------------------------");
//get data from third object
System.Console.WriteLine("Third student:");
System.Console.WriteLine("Student ID: " + s3.studentid);
System.Console.WriteLine("Student Name: " + s3.studentname);
System.Console.WriteLine("Marks: " + s3.marks);
System.Console.WriteLine("---------------------------------");
System.Console.ReadKey();
}
}
Output
Object Initializer
Object Initializer
• Drawback of constructor: Once we have created a constructor with some set of arguments,
every time we call it, you must pass the same no. of values; we can't initialize desired Fields;
so there is no flexibility in the constructor.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//create a class called "Student" with 3 Fields called "studentid",
"studentname" and "marks"
class Student
{
//Fields
public int studentid;
public string studentname;
public int marks;
}
class Program
{
static void Main()
{
//create 3 reference variables of "Student" type
Student s1, s2, s3;
Output
Set Method
• Set method receives a value as argument, checks (validates) it, and then assigns the same
into the Field.
• Set method protects the Field from invalid values.
• Set method acts as mediator between Main method and Field.
• Set method is used to perform validations and makes the program stronger and
systematic.
• Note: When set method is created, it is recommended to make the Field as “private”. The
private members are accessible only within the same class.
Get Method
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//create a class called "Person"
class Person
{
//Field
public int age;
//set method
public void SetAge(int value)
{
if (value >= 18 && value <= 60)
{
age = value;
}
}
//get method
public int GetAge()
{
return (age);
}
}
class Program
{
static void Main()
{
Person p = new Person();
p.SetAge(70);
System.Console.WriteLine(p.GetAge());
p.SetAge(24);
System.Console.WriteLine(p.GetAge());
p.SetAge(240);
System.Console.WriteLine(p.GetAge());
System.Console.ReadKey();
}
}
Output
Properties
• A property is a group of “set method” and “get method”, which perform validation on a
private Field.
• Properties are used for validations and automatic calculations. The “set method” is used to
create validations; and “get method” is used to create automatic calculations or return the
value of a Field as it is.
• Properties offer simple way to call “set method” and “get method”.
• In real time, for every private Field, we create a property. That means the private Field is
not accessible directly in the client code; though property it can be accessible indirectly.
• The property’s set method will be called automatically when a value is assigned to a
property.
• The property’s set method has an implicit argument called “value” that represents the
value assigned to the property.
• The property’s get method will be called automatically when the client code gets the value
of the property.
• The property’s get method has no arguments but should return the value.
• Note: While creating properties, it is recommended to create Field name start with “_”
(underscore). The underscore has no meaning, but it indicates that it is Field.
get
{
return (Field);
}
}
Properties - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//create a class called "Person"
class Person
{
//private Field
private int _age;
return _age;
}
}
class Program
{
static void Main()
{
Person p = new Person();
p.Age = 70;
System.Console.WriteLine(p.Age);
p.Age = 24;
System.Console.WriteLine(p.Age);
p.Age = 240;
System.Console.WriteLine(p.Age);
System.Console.ReadKey();
}
}
Output
Read-only properties
• Read-only properties contain only get method; no set method.
• The user can get the value of read-only property, but can’t set the value.
Write-only properties
• Write-only properties contain only set method; no get method.
• The user can set the value of write-only property, but can’t get the value.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Student
{
//private Fields
public int _marks;
public string _result;
//properties
public int Marks
{
set
{
if (value >= 0 && value <= 100)
{
_marks = value;
}
}
get
{
return (_marks);
}
}
//readonly property (only get method)
public string Result
{
get
{
if (_marks < 35)
_result = "Fail";
else
_result = "Pass";
return _result;
}
}
}
class Program
{
static void Main()
{
Student s = new Student();
s.Marks = 70;
System.Console.WriteLine(s.Result);
System.Console.ReadKey();
}
}
Output
Automatic Properties
Automatic properties
• Automatic properties are created using { get; set; } syntax.
• When you create automatic property, the compiler automatically creates the following
things automatically at compilation time:
o Private Field
o Set method
o Get method
• But automatic properties are useful only when you don’t want to perform any validation. If
you want to perform validation, use normal properties.
• Syntax:
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
class Person
{
//automatic properties
public string PersonName { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person p = new Person();
p.PersonName = "Scott";
p.Age = 22;
System.Console.WriteLine(p.PersonName);
System.Console.WriteLine(p.Age);
System.Console.ReadKey();
}
}
Output
Inheritance
What is Inheritance
• It is a OOP concept of creating “parent-child” relationship among two or more classes.
• Here, the classes are two types: parent class and child class.
• As a result of inheritance, all the members of parent class will become as members of child
class automatically.
• When an object of child class is created, it creates an object of parent class internally, and
it will be part of the child class’s object.
• One parent class can have one or more child classes; but one child class can have ONLY
ONE parent class.
• If you create a new child class based on an existing child class, all its members and also its
parent class members will be inherited into the new child class.
• Syntax of inheritance:
Inheritance - Example
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
• Click on OK.
Program.cs
//parent class
class Class1
{
public int a = 10;
public int b = 20;
}
//child class
class Class2 : Class1
{
public int c = 30;
public int d = 40;
}
class Program
{
static void Main()
{
//create a reference variable for child class (Class2)
Class2 p;
//create object for child class (Class2); It internally creates an object for
parent class also. That means it allocates memory for "a", "b", "c" and "d".
p = new Class2();
System.Console.ReadKey();
}
}
Output
Inheritance – Example 2
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class
class Person
{
public string PersonName;
public string Gender;
}
//child class 1
class Student : Person
{
public int StudentID;
public int Marks;
}
//child class 2
class Employee : Person
{
public int EmpID;
public double Salary;
class Program
{
static void Main()
{
/******* creating object for parent class ********/
Person p;
p = new Person();
p.PersonName = "Scott";
p.Gender = "Male";
System.Console.WriteLine("Person Name: " + p.PersonName);
System.Console.WriteLine("Gender: " + p.Gender);
System.Console.WriteLine("\n");
System.Console.ReadKey();
}
}
Output
“base” keyword
o Syntax: base.parentclassmembername
• Note: Here, “base” is a keyword that represents the “object of parent class”, which is a part
of “object of child class”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class
class Person
{
public string PersonName;
public string Gender;
}
//child class 1
class Student : Person
{
public int StudentID;
public int Marks;
//Student.DisplayStudentDetails
public void DisplayStudentDetails()
{
System.Console.WriteLine("Student Name: " + base.PersonName);
System.Console.WriteLine("Gender: " + base.Gender);
System.Console.WriteLine("Student ID: " + this.StudentID);
System.Console.WriteLine("Student Marks: " + this.Marks);
}
}
//child class 2
class Employee : Person
{
public int EmpID;
public double Salary;
//Employee.DisplayEmployeeDetails
public void DisplayEmployeeDetails()
{
System.Console.WriteLine("Employee Name: " + base.PersonName);
System.Console.WriteLine("Gender: " + base.Gender);
System.Console.WriteLine("Employee ID: " + this.EmpID);
System.Console.WriteLine("Employee Salary: " + this.Salary);
}
}
class Program
{
static void Main()
{
/********* creating object for child class 1 *************/
Student s;
s = new Student();
s.PersonName = "Allen";
s.Gender = "Male";
s.StudentID = 101;
s.Marks = 70;
s.DisplayStudentDetails();
System.Console.WriteLine("\n");
System.Console.ReadKey();
}
}
Output
• In the child class’s constructor, you can use the following syntax to call the parent class’s
parameterized constructor:
o base(parameter1, parameter2, …)
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class
class Person
{
public string PersonName;
public string Gender;
//child class 1
class Student : Person
{
public int StudentID;
public int Marks;
//Student.DisplayStudentDetails
public void DisplayStudentDetails()
{
System.Console.WriteLine("Student Name: " + base.PersonName);
System.Console.WriteLine("Gender: " + base.Gender);
//child class 2
class Employee : Person
{
public int EmpID;
public double Salary;
//Employee.DisplayEmployeeDetails
public void DisplayEmployeeDetails()
{
System.Console.WriteLine("Employee Name: " + base.PersonName);
System.Console.WriteLine("Gender: " + base.Gender);
System.Console.WriteLine("Employee ID: " + this.EmpID);
System.Console.WriteLine("Employee Salary: " + this.Salary);
}
}
class Program
{
static void Main()
{
/********* creating object for child class 1 *************/
Student s;
s = new Student("Allen", "Male", 101, 70);
s.DisplayStudentDetails();
System.Console.WriteLine("\n");
System.Console.ReadKey();
}
}
Output
Method Hiding
Method Hiding
• “Method hiding” is used to hide the parent class’s method, by creating another method in
the child class, with same signature (access modifier, method name and arguments).
• For method hiding, we need not use any special keyword in the parent class’s method. But
we have to use “new” keyword in the child class’s method optionally. The “new” keyword
specifies the compiler that we are doing the “method hiding” intentionally.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class
class Class1
{
//Class1.Display
public void Display()
{
System.Console.WriteLine("Class1.Display");
}
}
//child class
class Class2 : Class1
{
//Class2.Display
//Method hiding: This method hides the parent class's method called
"Display". Both methods are having the same signature; but code is
different. Note: The "new" keyword is optional here.
public new void Display()
{
System.Console.WriteLine("Class2.Display");
}
}
class Program
{
static void Main()
{
Class2 c2;
c2 = new Class2();
c2.Display(); //calls Class2.Display only
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class
class Person
{
//Fields of "Person" class
public string PersonName;
public string Gender;
//Person.Display
public void Display()
{
System.Console.WriteLine("Person Name: " + PersonName);
System.Console.WriteLine("Gender: " + Gender);
}
}
//child class 1
class Student : Person
{
public int StudentID;
public int Marks;
//Student.Display
//Method Hiding: This method hides the parent class's method called
"Display". Both methods are having the same signature; but code is
different.
public new void Display()
{
System.Console.WriteLine("Student Name: " + PersonName);
System.Console.WriteLine("Gender: " + Gender);
System.Console.WriteLine("Student ID: " + StudentID);
System.Console.WriteLine("Student Marks: " + Marks);
}
}
//child class 2
class Employee : Person
{
public int EmpID;
public double Salary;
//Employee.Display
//Method Hiding: This method hides the parent class's method called
"Display". Both methods are having the same signature; but code is
different.
public new void Display()
{
System.Console.WriteLine("Employee Name: " + PersonName);
System.Console.WriteLine("Gender: " + Gender);
System.Console.WriteLine("Employee ID: " + EmpID);
System.Console.WriteLine("Employee Salary: " + Salary);
}
}
class Program
{
static void Main()
{
/********* creating object for child class 1 *************/
Student s;
s = new Student();
s.PersonName = "Allen";
s.Gender = "Male";
s.StudentID = 101;
s.Marks = 70;
s.Display(); //calls Student.Display only
System.Console.WriteLine();
/********* creating object for child class 2 *************/
Employee emp;
emp = new Employee();
emp.PersonName = "Jones";
emp.Gender = "Male";
emp.EmpID = 201;
emp.Salary = 7000;
emp.Display(); //calls Employee.Display only
System.Console.ReadKey();
}
}
Output
Method Overriding
• The parent class’s method should be “virtual method”. The child class’s method should be
“override method”.
• The “virtual” keyword in parent class’s method allows the child classes to override
(redefine) the parent class’s method in the child classes.
• The “override” keyword in child class’s method informs the parent class that it is overriding
the parent class’s virtual method.
• The method signature (method name, access modifier, arguments, and return type) should
be same in between virtual method and override method.
• In real time, we use “method overriding” to extend an existing method, which is created by
another programmer.
2 Present in any class (parent class or in Should be present in parent class only.
child class).
• "Method Hiding" is similar to "Method Overriding", but having the following differences.
1 We need not use any keyword in parent class We should use "virtual" keyword in parent
method; "new" keyword in child class method. class method; "override" keyword in child
class method.
2 Method hiding is used to hide (overwrite) the Method overriding is used to extend the
parent class’s method. That means parent parent class’s method. That means both
class’s method will not execute; only child parent class’s method and child class’s
class’s method executes. method execute.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class
class Class1
{
//Class1.Display (virtual method)
public virtual void Display()
{
System.Console.WriteLine("Class1.Display");
}
}
//child class
class Class2 : Class1
{
//Class2.Display
//Method overriding: This method overrides (extends) the parent class's
virtual method called "Display". That means both methods will execute.
Both methods should have same signature.
public override void Display()
{
base.Display();
System.Console.WriteLine("Class2.Display");
}
}
class Program
{
static void Main()
{
Class2 myobject;
myobject = new Class2();
//call the both methods Class1.Display and Class2.Display
myobject.Display();
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class
class Person
{
public string PersonName;
public string Gender;
//Student.Display
//Method overriding: This method overrides (extends) the parent class's
virtual method called "Display". Both methods will execute. Both methods
should have same signature.
public override void Display()
{
base.Display();
System.Console.WriteLine("Student ID: " + StudentID);
System.Console.WriteLine("Student Marks: " + Marks);
}
}
//child class 2
class Employee : Person
{
public int EmpID;
public double Salary;
//Employee.Display
//Method overriding: This method overrides (extends) the parent class's
virtual method called "Display". Both methods will execute. Both methods
should have same signature.
public override void Display()
{
base.Display();
System.Console.WriteLine("Employee ID: " + EmpID);
System.Console.WriteLine("Employee Salary: " + Salary);
}
}
class Program
{
static void Main()
{
/********* creating object for child class 1 *************/
Student s;
s = new Student();
s.PersonName = "Allen";
s.Gender = "Male";
s.StudentID = 101;
s.Marks = 70;
s.Display(); //calls to Person.Display and Employee.Display
System.Console.WriteLine("\n");
/********* creating object for child class 2 *************/
Employee emp;
emp = new Employee();
emp.PersonName = "Jones";
emp.Gender = "Male";
emp.EmpID = 201;
emp.Salary = 7000;
emp.Display(); //calls to Person.Display and Student.Display
System.Console.ReadKey();
}
}
Output
Abstract Classes
Abstract Classes
• Abstract classes are similar to normal classes and can contain abstract members
additionally, and those can’t be instantiated.
• Abstract classes contain a set of members that are common to all of its child classes.
• Abstract classes can be inherited. That means we can create a child class based on the
abstract class.
• We can’t create object for the abstract class directly. The only way to utilize its members is
“creating object for child class and calling abstract class’s members through the child
class’s object”.
2 We can create an object for normal class. We can't create an object for abstract class;
but we can create a reference variable.
3 Normal class can't contain abstract Abstract class can contain abstract methods.
methods.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
Program.cs
//parent class (abstract class)
abstract class Person
{
//normal method in abstract class
public void Display()
{
System.Console.WriteLine("Person.Display");
}
}
//child class 1
class Student : Person
{
}
//child class 2
class Employee : Person
{
}
class Program
{
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class (abstract class)
abstract class Person
{
public string PersonName;
public string Gender;
//child class 1
class Student : Person
{
public int StudentID;
public int Marks;
//child class 2
class Employee : Person
{
public int EmpID;
public double Salary;
}
class Program
{
static void Main()
{
/************* creating object for child class 1 ********************/
Student s;
s = new Student();
s.PersonName = "Allen";
s.Gender = "Male";
s.StudentID = 101;
s.Marks = 70;
s.Display();
System.Console.WriteLine("Student ID: " + s.StudentID);
System.Console.WriteLine("Marks: " + s.Marks);
System.Console.WriteLine("\n");
/************* creating object for child class 2 ********************/
Employee emp;
emp = new Employee();
emp.PersonName = "Jones";
emp.Gender = "Male";
emp.EmpID = 201;
emp.Salary = 7000;
emp.Display();
System.Console.WriteLine("Employee ID: " + emp.EmpID);
System.Console.WriteLine("Salary: " + emp.Salary);
System.Console.ReadKey();
}
}
Output
Abstract Methods
Abstract Methods
• Abstract methods are “declaration-only” method that are declared in the abstract class
(parent class) and must be implemented (overridden) in the child class(es).
• Abstract methods should be overridden in the child class, using “override” keyword.
• In real time, abstract class with abstract method(s) will be created by one programmer and
its child class(es) will be created by another programmer.
• Assume that there are two programmers. The first programmer is creating parent class
(cum abstract class); the second programmer is creating child class. But both are present
in two different components (parts) of the project. So whenever the first programmer can’t
write the actual code for a method in the parent class and wants to let the second
programmer two write actual code for the method, then he will create an abstract method
in the parent class. So the first programmer writes method signature only; but not the
method definition. Then the second programmer has to create a child class, based on the
existing parent class. Then the second programmer must create method definition. This
work is called as “method overriding with abstract methods”.
• Virtual methods contain method body also. Abstract methods contain signature only, no
method body.
2 We can call the normal method. We can't call the abstract method.
3 Normal methods can be created in both Abstract methods can be created in only
normal class and also in abstract class. abstract class.
4 Normal methods contain method signature Abstract methods contain only method
and body. signature; no method body.
5 Normal methods can be present in both Abstract methods can be present only in the
parent class and also in the child class. parent class.
2 We can call the virtual method. We can't call the abstract method.
3 Virtual methods can be created in both Abstract methods can be created in only
normal class and also in abstract class. abstract class.
4 Virtual methods contain method signature Abstract methods contain only method
and body. signature; no method body.
5 Overriding the virtual methods is optional. Overriding the abstract methods is must.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class (abstract class)
abstract class Class1
{
//abstract method in parent class. Abstract method doesn't contain
method body. It contains only signature.
public abstract void Display();
}
//child class
class Class2 : Class1
{
//Class2.Display
//Method overriding: This method overrides the parent class's abstract
method called "Display". Both methods are having the same signature.
public override void Display()
{
System.Console.WriteLine("Class2.Display");
}
}
class Program
{
static void Main()
{
Class2 c2;
c2 = new Class2();
c2.Display();
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//parent class (abstract class)
abstract class Person
{
public string PersonName;
public string Gender;
//child class 1
class Student : Person
{
public int StudentID;
public int Marks;
//Student.Display
//Method Overriding: This method overrides the parent class's abstract
method called "Display". Both methods are having the same signature.
public override void Display()
{
System.Console.WriteLine("Student Name: " + base.PersonName);
System.Console.WriteLine("Gender: " + base.Gender);
System.Console.WriteLine("Student ID: " + this.StudentID);
System.Console.WriteLine("Student Marks: " + this.Marks);
}
}
//child class 2
class Employee : Person
{
public int EmpID;
public double Salary;
//Employee.Display
//Method overriding: This method overrides the parent class's abstract
method called "Display". Both methods are having the same signature.
public override void Display()
{
System.Console.WriteLine("Employee Name: " + base.PersonName);
System.Console.WriteLine("Gender: " + base.Gender);
System.Console.WriteLine("Employee ID: " + this.EmpID);
System.Console.WriteLine("Employee Salary: " + this.Salary);
}
}
class Program
{
static void Main()
{
/*********** creating object for child class 1 *****************/
Student s;
s = new Student();
s.PersonName = "Allen";
s.Gender = "Male";
s.StudentID = 101;
s.Marks = 70;
s.Display();
System.Console.WriteLine("\n");
System.Console.ReadKey();
}
}
Output
Interfaces
• Interfaces are similar to abstract classes, but interfaces contain only abstract methods and
property declarations.
• We can’t create other members such as Fields, normal methods, constructors, properties
etc., in interface.
• We can’t create an object for the interface, but we can create one or more child classes for
interface.
• Interface provides a list of abstract methods that should be overridden in the child classes.
By default, all the interface methods “public” and “abstract” automatically.
• All the child classes that inherits (implements) the interface should implement (override)
all the interface methods. But different child classes can implement the interface methods
with different code. If you don’t implement (override) any of the interface methods in the
child class, you will get compile-time error.
• Real-time use of interface: Interface acts as “contract” or “bridge” between two parts of a
project. Assume that there are two programmers that create two different components of
the project. The interface acts as bridge between both the programmers. This situation
occurs in advanced .net frameworks such as WPF, MVC etc.
o The first programmer creates an interface; then creates an interface variable and
calls the method, without knowing its implementation.
o The second programmer creates a child class for the interface and implements all
of its methods, without knowing its calling.
1 Abstract class can contain all types of Can have only abstract methods & property
members such as Fields, methods, declarations.
properties, constructors etc. & also
abstract methods.
2 A child class can’t inherit multiple abstract A child class can inherit (implement) multiple
classes. interfaces
3 Abstract class can’t act as a mediator Interface act as a mediator between two
between two classes. classes.
4 Use abstract class, if you want to provide Use interface, if you want to provide only a
a list of non-abstract methods and list of abstract methods to the child classes.
abstract methods to the child classes.
5 Use abstract class, if you want to create a Use interface, if you want to create pure
“partial generic type”. “generic type”.
Observation:
• “CompanyHolidayTrip” is partial
general-purpose. It provides the list of
methods that are common for all
company holiday trips; but it doesn’t
matter which company holiday trip it
is.
Interfaces - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//interface
interface Interface1
{
//abstract methods
void Display();
}
//child class
class Class1 : Interface1
{
//Method Overriding: This method overrides (implements) the
"Interface1.Display" method. Both methods are having the same signature.
public void Display()
{
System.Console.WriteLine("Class1.Display");
}
}
class Program
{
static void Main()
{
Class1 p;
p = new Class1();
p.Display();
System.Console.ReadKey();
}
}
Output
Interfaces – Example 2
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//interface
interface IPerson
{
//properties
string PersonName { get; set; }
string Gender { get; set; }
//abstract method
void Display();
}
//child class 1
class Student : IPerson
{
//properties
public string PersonName { get; set; }
public string Gender { get; set; }
public int StudentID { get; set; }
public int Marks { get; set; }
s.Marks = 70;
s.Display();
System.Console.WriteLine("\n");
/********** creating object for child class 2 ***************/
Employee emp;
emp = new Employee();
emp.PersonName = "Jones";
emp.Gender = "Male";
emp.EmpID = 201;
emp.Salary = 7000;
emp.Display();
System.Console.ReadKey();
}
}
Output
Dynamic Polymorphism
o Create an object for first child class; Assign its reference into interface’s variable & call
the method now. It calls the first child class’s method.
o Create an object for second child class; Assign its reference into interface’s variable &
call the method now. It calls the second child class’s method.
o So, same statement is calling different methods in different situations, right! This is
called “dynamic polymorphism”.
2 Decision will be taken by the compiler at Decision will be taken by the CLR at run-
compile-time. time.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//interface
interface Interface1
{
//abstract method in interface
void Display();
}
//child class 1
class Class1 : Interface1
{
//Overriding the "Interface1.Display" method
public void Display()
{
System.Console.WriteLine("Class1.Display");
}
}
//child class 2
class Class2 : Interface1
{
//Overriding the "Interface1.Display" method
public void Display()
{
System.Console.WriteLine("Class2.Display");
}
}
class Program
{
static void Main()
{
//create a reference variable of interface type.
Interface1 i;
//create object for first child class
i = new Class1();
i.Display(); //It calls Class1.Display()
//create object for second child class
i = new Class2();
i.Display(); //It calls Class2.Display()
System.Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
• Click on OK.
Program.cs
//interface
interface IPerson
{
//properties
string PersonName { get; set; }
string Gender { get; set; }
//abstract method
void Display();
}
//child class 1
class Student : IPerson
{
//properties
public string PersonName { get; set; }
public string Gender { get; set; }
//child class 2
class Employee : IPerson
{
//properties
public string PersonName { get; set; }
public string Gender { get; set; }
class Program
{
static void Main()
{
//create reference variable of interface type
IPerson p;
p.PersonName = "Allen";
p.Gender = "Male";
p.Display(); //calls Student.Display
System.Console.WriteLine("\n");
Output
• Then you can store the address of class’s object in any reference variable of any of those
interfaces.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//interface 1
interface Interface1
{
void Method1();
void Method2();
}
//interface 2
interface Interface2
{
void Method3();
void Method4();
}
Output
Interface Inheritance
Interface Inheritance
• An interface can inherit from another interface.
• Then the child class of child interface should implement all the methods of parent interface
& child interface.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
• Click on OK.
Program.cs
//parent interface
interface Interface1
{
void Method1();
void Method2();
}
//child interface
interface Interface2 : Interface1
{
void Method3();
void Method4();
}
class Program
{
static void Main()
{
//create reference variable & object for child class
Class1 c1;
c1 = new Class1();
System.Console.ReadKey();
}
}
Output
Sealed Classes
Sealed Classes
• Sealed classes can’t be inheritable.
• If you don’t want to allow your class to be inheritable by others, you can make it as sealed
class.
• Sealed classes can contain any members just like normal classes.
• Syntax:
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
• Click on OK.
Program.cs
//sealed class
sealed class Class1
{
}
class Program
{
static void Main()
{
}
}
Output
Namespaces
Namespaces
• Namespaces are collections of “types”, such as classes, structures, enumerations, interfaces
and delegate types.
• The type that is present inside the namespace can be accessed by using
“Namespacename.Typename” syntax.
• Namespaces are used to group-up the types that belongs to a module or a section of the
project.
• Syntax:
namespace Namespacename
{
Classes, Structures, interfaces, Enumerations here
}
Namespaces - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
namespace Namespace1
{
class Class1
{
public void Method1()
{
System.Console.WriteLine("Namespace1.Class1.Method1");
}
}
}
namespace NamespacesExample
{
class Program
{
static void Main()
{
//create a reference variable
Namespace1.Class1 c1;
//create an object
c1 = new Namespace1.Class1();
System.Console.ReadKey();
}
}
}
Output
Child Namespaces
Child Namespaces
• A namespace inside another namespace is called as “child namespace”.
• Syntax:
namespace ParentNamespacename
{
namespace ChildNamespacename
{
Types (Classes, structures etc.)
}
}
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//outer namespace starts
namespace ICICIBank
{
//inner namespace starts
namespace SavingsBanking
{
//class starts
class BankAccount
{
public void Deposit()
{
System.Console.WriteLine("ICICIBank.SavingsBanking.BankAccount.Depo
sit");
}
}
//class ends
}
//inner namespace ends
}
//outer namespace ends
namespace ChildNamespacesExample
{
class Program
{
static void Main()
{
//create a reference variable for BankAccount class
ICICIBank.SavingsBanking.BankAccount c1;
//create an object for BankAccount class
c1 = new ICICIBank.SavingsBanking.BankAccount();
//call the method
c1.Deposit();
System.Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//Create a child namespace called "SavingsBanking" in a parent namespace
called "ICICIBank"
namespace ICICIBank.SavingsBanking
{
class BankAccount
{
public void Deposit()
{
System.Console.WriteLine("ICICIBank.SavingsBanking.BankAccount.Depo
sit");
}
}
}
namespace ChildNamespacesExample2
{
class Program
{
static void Main()
{
//create reference variable
ICICIBank.SavingsBanking.BankAccount c1;
//create object
c1 = new ICICIBank.SavingsBanking.BankAccount();
//call method
c1.Deposit();
System.Console.ReadKey();
}
}
}
Output
“using” statement
Using
• The “using” statement is used to import a namespace in the file.
• When you import a namespace, you can access all its members (classes, structures etc.)
directly, without writing the namespace name every time.
• Syntax:
using Namespacename;
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//import the namespace
using ICICIBank.SavingsBanking;
System.Console.WriteLine("ICICIBank.SavingsBanking.BankAccount.Depo
sit");
}
}
}
namespace UsingExample
{
class Program
{
static void Main()
{
//create reference variable; access "BankAccount" class directly, as it
is already imported above.
BankAccount c1;
//create object; access "BankAccount" class directly, as it is already
imported above.
c1 = new BankAccount();
//call the method
c1.Deposit();
System.Console.ReadKey();
}
}
}
Output
Using Alias
• It is used to create a “nick name” (alias name) for a namespace, for easy access.
• You can access all the namespace’s members, by using the alias name.
Syntax:
using Aliasname = Namespacename;
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//creating alias name
using i = India;
using p = Pakisthan;
namespace India
{
class Hyderabad
{
public void City()
{
System.Console.WriteLine("India.Hyderabad");
}
}
}
namespace Pakisthan
{
class Hyderabad
{
public void City()
{
System.Console.WriteLine("Pakisthan.Hyderabad");
}
}
}
namespace UsingAliasExample
{
class Program
{
static void Main()
{
i.Hyderabad h1 = new i.Hyderabad();
p.Hyderabad h2 = new p.Hyderabad();
h1.City();
h2.City();
System.Console.ReadKey();
}
}
}
Output
Separate Files
• In realtime applications, it is recommended to create a class in its own separate file, instead
of creating all the classes in the same file.
• Class files make the large project easy to understand and maintain.
• To add a class file, open the solution explorer; right click on the project name and click on
“Add” – “New Item”; select “Class”; type the class name as “Filename.cs”; click on “Add”.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
• Open Solution Explorer. Right click on the project name (SeparateFilesExample) and click
on “Add” – “New Item”. Click on “Code” – “Class”. Type the file name as “BankAccount.cs”.
BankAccount.cs
//Create a child namespace called "SavingsBanking" in a parent namespace
called "ICICIBank"
namespace ICICIBank.SavingsBanking
{
class BankAccount
{
public void Deposit()
{
System.Console.WriteLine("ICICIBank.SavingsBanking.
BankAccount.Deposit");
}
}
}
Program.cs
namespace mynamespace
{
class Program
{
static void Main()
{
//create reference variable
ICICIBank.SavingsBanking.BankAccount c1;
//create object
c1 = new ICICIBank.SavingsBanking.BankAccount();
//call the method
c1.Deposit();
System.Console.ReadKey();
}
}
}
Output
Partial Classes
Partial Classes
• Partial classes are used to split a large class into multiple files.
• In real time, one part of the class will be created by one programmer and other part of the
class will be created by other programmer; sometimes one part of the class will be
automatically generated by visual studio and other part of the class will be created by the
programmer.
• All the partial classes that should have a same name, should have “partial” keyword, and
should be inside a same namespace.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
• Open Solution Explorer. Right click on the project and click on “Add” – “New Item”. Select
• Open Solution Explorer. Right click on the project and click on “Add” – “New Item”. Select
File1.cs
//create a parent namespace called "ICICIBank" and create a child
namespace called "SavingsBanking" in the parent namespace
namespace ICICIBank.SavingsBanking
{
//create a class called "BankAccount" in "ICICIBank.SavingsBanking"
namespace. This is a partial class. So at compilation time, the code for
File2.cs also will be combined with this class.
partial class BankAccount
{
//Fields
public int accountnumber = 1234;
public string accountholdername = "John";
public double currentbalance = 10000;
//Deposit method
public void Deposit(double amount)
{
currentbalance = currentbalance + amount;
}
}
}
File2.cs
//create a parent namespace called "ICICIBank" and create a child
namespace called "SavingsBanking" in the parent namespace
namespace ICICIBank.SavingsBanking
{
//Continue the definition of "BankAccount" class, which is defined at
"File1.cs".
partial class BankAccount
{
//Withdraw method
public void Withdraw(double amount)
{
currentbalance = currentbalance - amount;
}
}
}
Program.cs
namespace PartialClassesExample
{
class Program
{
static void Main()
{
//create reference variable
ICICIBank.SavingsBanking.BankAccount c1;
//create object
c1 = new ICICIBank.SavingsBanking.BankAccount();
//deposit
c1.Deposit(5000);
System.Console.WriteLine(c1.currentbalance);
System.Console.ReadKey();
//withdraw
c1.Withdraw(2000);
System.Console.WriteLine(c1.currentbalance);
System.Console.ReadKey();
}
}
}
Output
Enumerations
Enumerations
• Enumerations are used to avoid the entry of wrong values into the variable. It allows any
one of the specific list of values.
• Based on enumeration, we can create enumeration variables (as a Field or local variable).
enum Enumerationname
{
Constant1, Constant2, …
}
Enumerations - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
//create a namespace called "EnumerationExample"
namespace EnumerationExample
{
//create an enumeration called "GenderEnumeration" inside a namespace
called "EnumerationExample"
enum GenderEnumeration
{
Male, Female
}
//create a class called "Person"
class Person
{
//Field of "String" data type
public string PersonName;
class Program
{
static void Main()
{
//create reference variable of Person type
Person p;
//create an object of Person type
p = new Person();
//set data into PersonName
p.PersonName = "Scott";
//set data into "Gender". It accepts "Male" or "Female" only, as it is
"GenderEnumeration" type.
p.Gender = GenderEnumeration.Male;
//get data from Fields
Console.WriteLine(p.PersonName);
Console.WriteLine(p.Gender);
Console.ReadKey();
}
}
}
Output
Structures
Structures
• Structure is type (data type), which is a collection of members such as Fields, methods,
constructors, properties etc., similar to classes.
• No memory will be allocated for structure. We can create "structure variables" (instance)
based on structure. For structure variables only memory will be allocated. “Structure
variable” stores actual data.
struct Structurename
{
Fields, methods, constructors, properties etc.
}
2 We can create a reference variable based We can’t create a reference variable based on
on class. structure.
3 Classes are “reference-type” data types; Structures are “value-type” data types; because
because “objects” are stored in heap and “structure variables” (data) directly will be
its reference (address) will be stored in stored in stack; there is no “reference”
stack. (address) concept for structures.
4 Classes are little bit slower than Structures are little bit faster than classes;
structures; because to reach an object, we because to reach a structure variable, there is
have to go through stack and find out the no need to search for the address.
object based on the address stored in the
reference variable.
5 Classes support “inheritance” and many Structures doesn’t support inheritance and its
other concepts. related concepts.
6 Classes are suitable for creating complex Structures are suitable for creating simple data
data structures & methods. structures.
7 “String”, “StringBuilder” etc., are pre- All standard data types (except “string”), such
defined classes. as int, float, double, DateTime etc., are
structures.
9 The following syntax creates a reference The following syntax creates a structure
variable for the class: variable (instance) for the structure.
10 The following syntax creates an object The following syntax will not create an instance,
(instance) for the class & also initializes but initializes all the Fields of structure variable
all the Fields of the object: (instance).
If the Field is numerical data type, it If the Field is numerical data type, it initializes
initializes zero (0). If the Field is string zero (0). If the Field is string data type, it
data type, it initializes null. If the Field is initializes null. If the Field is bool data type, it
bool data type, it initializes ‘false’. initializes ‘false’.
Structures - Example
Creating Project
• Open Visual Studio 2019.
Program.cs
using System;
namespace StructuresExample
{
//create structure called "Student"
struct Student
{
//Fields in structure
public int studentid;
public string studentname;
public int marks;
}
class Program
{
static void Main()
{
//create structure variable (instance)
Student s;
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace StructuresWithConstructorsExample
{
//creating a structure
struct Student
{
//Fields in structure
//constructor in structure
public Student(int value1, string value2, int value3)
{
studentid = value1;
studentname = value2;
marks = value3;
grade = "none";
}
//method in structure
public void CalculateGrade()
{
if (marks >= 80 && marks <= 100)
grade = "A grade";
else if (marks >= 60 && marks < 80)
grade = "B grade";
else if (marks >= 50 && marks < 60)
grade = "C grade";
else if (marks >= 35 && marks < 50)
grade = "D grade";
else if (marks < 35)
grade = "Fail";
}
class Program
{
static void Main()
{
//create structure variable (instance)
Student s;
//call method
s.CalculateGrade();
Console.WriteLine("Grade: " + s.grade);
Console.ReadKey();
}
}
}
Output
• The "System.Object" is ultimate base class in .net, based on which all structures and
classes are inherited from.
• When you create a class in .net, automatically it will be treated as child class of the parent
class called “System.Object”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ObjectClassExample
{
class Class1
{
}
class Program
{
static void Main()
{
//create a reference variable of "System.Object" type
System.Object a;
Console.WriteLine("Done");
Console.ReadKey();
}
}
}
Output
• The “System.Object” class provides the following methods to all classes and structures:
▪ The Equals() method compares the actual object and other object whether
both are equal; It returns true if both are equal. It returns false if both are
not equal.
B. int GetHashCode()
C. Type GetType()
▪ The GetType() method returns the class name or structure name to which
the actual object belongs to.
D. string ToString()
▪ The ToString() method returns the class name or structure name to which
the actual object belongs to (similar to GetType method). But it can be
overridden in the child class. If it is overridden, the child class’s method will
run.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ObjectClassMethodsExample
{
//"Class1" is child class of "System.Object" class automatically
class Class1
{
//override the ToString() method, which is the virtual method in
System.Object class
public override string ToString()
{
System.Console.WriteLine(base.GetHashCode());
return "Class1.ToString";
}
}
class Program
{
//call GetType method. This method returns the type (class name) of
the object.
string t = c1.GetType().ToString();
Console.WriteLine(t);
Console.ReadKey();
}
}
}
Output
Boxing
Boxing
• It is a process of converting a value from "value-type data type (any structure)" to
"reference-type data type (System.Object class)".
Boxing - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace BoxingExample
{
class Program
{
static void Main()
{
//creating a variable of "int" data type. "int" is a "structure". All the
structures "value-type data types".
int a = 1000;
//get values
Console.WriteLine(a); //Output: 1000
Console.WriteLine(obj); //Output: 1000
Console.ReadKey();
}
}
}
Output
Unboxing
Unboxing
• It is a process of converting a value from "reference-type data type (System.Object)" to
"value-type data type (any structure)". It should be done manually, by using “type casting”
syntax.
Unboxing - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace UnboxingExample
{
class Program
{
//get values
Console.WriteLine(obj); //Output: 100
Console.WriteLine(a); //Output: 100
Console.ReadKey();
}
}
}
Output
Static Constructors
Static Constructors
• Non-static constructors (normal constructors) initialize non-static Fields and static Fields;
Static constructors initialize static Fields only. Static constructors will be called
automatically when the class is used for the first time in Main method.
1 By default, all the constructors are non- Static constructors are created using
static constructors. These are not created “static” keyword.
with a keyword called “static”.
2 Non-static constructors can access both Static constructors can access only static
non-static members and non-static members. Static constructors can’t access
members. non-static members. However, if you
create an object for the class in the static
constructor, then you can access any non-
static members though the object, in the
static constructor.
4 Non-static constructor will be called every Static constructor will be called only once
time when we create an object for the in the entire program.
class.
5 We can use “this” keyword in the non- We can’t use “this” keyword in the static
static constructors, because non-static constructor, because static constructor is
constructors are called with an object. called with class only, without an object.
6 A class can have ‘n’ no. of non-static A class can have only one static
constructors. constructor.
7 Use non-static constructors, if you want Use static constructor if you want to
to initialize non-static Fields. initialize static Fields.
8 Non-static constructors can receive ‘n’ no. Static constructor can’t receive any
of arguments. arguments.
9 Non-static constructors can’t return any Static constructor also can’t return any
value. value.
10 Access modifier such as “internal” and Access modifier is not applicable for the
“public” can be applicable for the non- static constructor. By default, they are
static constructor. “public”.
Creating Project
• Open Visual Studio 2019.
Program.cs
using System;
namespace StaticConstructorsExample
{
//creating a class called "Class1"
class Class1
{
//static Fields
public static int a, b;
class Program
{
static void Main()
{
//Note: static constructor will be automatically called here
Console.ReadKey();
}
}
Output
Static Classes
Static Classes
• Static classes can contain only static members (static Fields, static methods, static
constructors, static properties etc.).
2 Can have both non-static members and Can have only static members.
static members also.
3 We can create an object for normal We can't create an object for static class.
class.
Creating Project
• Open Visual Studio 2019.
Program.cs
using System;
namespace StaticClassesExample
{
//static class. A static class contains only static Fields, static properties,
static constructors, and static methods only
static class Class1
{
//static Field
public static string _Message;
//static properties
public static string Message
{
set
{
_Message = value;
}
get
{
return _Message;
}
}
//static constructor
static Class1()
{
Message = "Hello";
//static method
public static void Method1()
{
Console.WriteLine("Class1.Method1");
}
}
class Program
{
static void Main()
{
//Note: .NET automatically allocated memory for static Field here
//Note: static constructor will be called automatically here
Console.ReadKey();
}
}
}
Output
Generic Classes
• Generic class is a class, which contains one or more generic-type Fields.
• Generic classes let you to store different values with respective to different objects in the
same Fields.
• Generic classes let you to decide the data type of a Field, while creating object, rather than
deciding the data type while creating the class.
• While creating an object for the generic class, you have to specify the data type of a Field.
• While creating a re-usable class, instead of you decide the data type of a Field within your
class, if you want to let other programmers decide the data type that they want, you can
make your class as generic class and make your Field as generic Field.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace GenericsExample
{
//generic class with a generic-type parameter called "T"
class Class1<T>
{
//generic Field of generic-type called "T"
public T x;
}
class Program
{
static void Main()
{
//creating first generic object. As per this object "x" is of "int" data
type.
Class1<int> c1;
c1 = new Class1<int>();
c1.x = 100;
Console.WriteLine(c1.x); //Output: 100
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace MultipleGenericsExample
{
//generic class with two generic-type parameters called "T1" and "T2"
class Class1<T1, T2>
{
//generic Field of generic-type called "T1"
public T1 x;
class Program
{
static void Main()
{
//creating first generic object. As per this object "x" is of "int" data
type and "y" is of "bool" data type.
Class1<int, bool> c1;
c1 = new Class1<int, bool>();
c1.x = 100;
c1.y = true;
Console.WriteLine(c1.x); ; //Output: 100
Console.WriteLine(c1.y); ; //Output: true
Console.WriteLine();
Console.ReadKey();
}
}
}
Output
Arrays
Arrays
• An array is a collection of multiple values of same data type.
• For each element, system automatically maintains an index. The index always starts from
zero (0).
Arrays - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysExample
{
class Program
{
static void Main()
{
//create an array with 5 elements.
int[ ] a = new int[5] { 10, 20, 50, 80, 100 };
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithForExample
{
class Program
{
static void Main()
{
//create an array with 5 elements
int[ ] a = new int[5] { 10, 20, 50, 80, 100 };
Console.ReadKey();
}
}
}
Output
• It executes once for one element in the array. Each time, the current element will be stored
in the temporary variable.
• But it is used to read all the values of an array, sequentially. It is not possible to read some
of the values, by using “foreach” loop. It is also not possible to read the elements randomly
or in reverse order.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithForEachExample
{
class Program
{
static void Main()
{
//create an array with 5 elements
int[ ] a = new int[5] { 10, 20, 50, 80, 100 };
Console.ReadKey();
}
}
}
Output
“System.Array” class
“System.Array” class
• The “System.Array” is a pre-defined class. An object of “System.Array” class represents an
array.
1. System.Array.IndexOf()
2. System.Array.BinarySearch()
3. System.Array.Clear()
4. System.Array.Resize()
5. System.Array.Sort()
6. System.Array.Reverse()
7. System.Array.CopyTo()
“System.Array.IndexOf” method
Sl. No Method
array: This parameter represents the array, in which you want to search.
The “IndexOf” method performs linear search. That means it searches all the elements of
an array, until the search value is found. When the search value is found in the array, it
stops searching and returns its index.
The linear search has good performance, if the array is small. But if the array is larger,
Binary search is recommended to improve the performance.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithIndexOfExample
{
class Program
{
static void Main()
{
//create array with
int[ ] a = new int[5] { 100, 2000, 50, 8, 1000 };
//search (linear search) for "50" in array & get its index
int n = Array.IndexOf(a, 50);
Console.WriteLine(n); //Output: 2
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithIndexOfWithNotFound
{
class Program
{
static void Main()
{
//create array
int[] a = new int[5] { 100, 2000, 50, 8, 1000 };
//search (linear search) for "500" in array & get its index. If not found,
it returns -1
int n = Array.IndexOf(a, 500);
Console.WriteLine(n);
Console.ReadKey();
}
}
}
Output
“System.Array.BinarySearch” method
Sl. No Method
array: This parameter represents the array, in which you want to search.
The “BinarySearch” method performs binary search. The “Binary Search” requires an
array, which is already sorted. On unsorted arrays, binary search is not possible.
Binary search means it directly goes to the middle of the array (array size / 2), and
checks that item is less than / greater than the search value. If that item is greater than
the search value, it searches only in the first half of the array. If that item is less than the
search value, it searches only in the second half of the array. Thus it searches only half of
the array. So in this way, it saves performance.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithBinarySearchExample
{
class Program
{
static void Main()
{
//For Binary search, we must need a sorted array (should have the
values in ascending order)
int[ ] a = new int[5] { 10, 20, 50, 80, 100 };
//search (binary search) for "50" in sorted array & get its index
int n = Array.BinarySearch(a, 50);
Console.WriteLine(n);
Console.ReadKey();
}
}
}
Output
“System.Array.Clear” method
Sl. No Method
This method starts with the given index and sets all the “length” no. of elements to zero
(0).
array: This parameter represents the array, in which you want to clear the elements.
index: This parameter represents the index, from which clearing process is to be started.
length: This parameter represents the no. of elements that are to be cleared.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithClearExample
{
class Program
{
static void Main()
{
//create array
int[ ] a = new int[8] { 10, 20, 50, 80, 100, 780, 900, 1000 };
Console.ReadKey();
}
}
}
Output
“System.Array.Resize” method
Sl. No Method
array: This parameter represents the array, which you want to resize.
newSize: This parameter represents the new size of the array, how many elements you
want to store in the array. It can be less than or greater than the current size.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithResizeExample
{
class Program
{
static void Main()
{
//create array (current size of array is "4")
int[ ] a = new int[4] { 10, 20, 50, 80 };
Console.ReadKey();
}
}
}
Output
“System.Array.Sort” method
Sl. No Method
array: This parameter represents the array, which you want to sort.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithSortExample
{
class Program
{
static void Main()
{
//create array
int[ ] a = new int[7] { 50, 20, 100, 30, 500, 150, 300 };
Console.ReadKey();
}
}
}
Output
“System.Array.Reverse” method
Sl. No Method
array: This parameter represents the array, which you want to reverse.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithReverseExample
{
class Program
{
static void Main()
{
//create array
int[ ] a = new int[7] { 50, 20, 100, 30, 500, 150, 300 };
Output
“System.Array.CopyTo” method
Sl. No Method
This method copies all the elements from source array to destination array.
sourceArray: This parameter represents the array, which array you want to copy.
destinationArray: This parameter represents the array, into which you want to copy the
elements of source array.
startIndex: This parameter represents the index of the element, from which you want to
start copying.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ArraysWithCopyToExample
{
class Program
{
static void Main()
{
//create array
int[] a = new int[5] { 10, 20, 50, 80, 100 };
Console.ReadKey();
}
}
}
Output
Multi-Dimensional Array
Multi-dimensional array
• Multi-dimensional arrays are used to store multiple values in a single row of an array.
• Note: You can increase the no. of commas (,) as many as you want.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace MultiDimArraysExample
{
class Program
{
static void Main()
{
//create multi-dim array
int[,] a = new int[4, 3]
{
{ 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 },
{ 100, 110, 120 }
};
Console.ReadKey();
}
}
}
Output
Collections
Limitations of arrays
• Adding or removing elements from array (without a duplicate copy) is not possible.
• We can add, remove values in the collection anywhere within the program.
1. System.Collections.Generic.List
2. System.Collections.Generic.Dictionary
3. System.Collections.Generic.SortedList
4. System.Collections.Hashtable
5. System.Collections.ArrayList
"System.Collections.Generic.Dictionary" etc.
4 If you want to store fixed no. of values, If you want to add or remove elements later,
then use "arrays". then use "collections".
System.Collections.Generic.List
• "List" is a class, in "System.Collections.Generic" namespace.
• It is a generic class; it has a generic type argument called “T”. That means you must pass a
data type as argument to it, while creating an object.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 90, 100 };
Console.ReadKey();
}
}
}
Output
• Syntax to read all elements from the list collection, using for loop:
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithForExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 90, 100 };
Console.ReadKey();
}
}
}
Output
• It executes once for one element in the collection. Each time, the current element will be
stored in the temporary variable.
• But it is used to read all the values of a collection, sequentially. It is not possible to read
some of the values, by using “foreach” loop. It is also not possible to read the elements
randomly or in reverse order.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithForEachExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 90, 100 };
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithAddExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50 };
//get values from list collection
foreach (int item in a)
{
Console.WriteLine(item);
}
Console.WriteLine();
//add "100" at the end of list collection
a.Add(100);
//get values from list collection
foreach (int item in a)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
Output
This method inserts a new value at the specified index in the existing collection.
index: This parameter represents the index, where the value is to be inserted.
"System.Collections.Generic.List.Insert" method -
Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithInsertExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 150, 200 };
Output
3 void AddRange(collection)
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithAddRangeExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 150, 200 };
//add all the elements of "extra" collection at the end of "a" collection
a.AddRange(extra);
Console.ReadKey();
}
}
}
Output
"System.Collections.Generic. List.InsertRange"
method
Sl. No Method
This method inserts an array or collection at the specified index in the existing collection.
index: This parameter represents the index, where the array / collection is to be inserted.
"System.Collections.Generic. List.InsertRange"
method - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithInsertRangeExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 150, 200 };
//get values from list collection
foreach (int item in a)
{
Console.WriteLine(item);
}
Console.WriteLine();
//create another collection called "extra"
List<int> extra = new List<int>() { 60, 70, 80 };
//insert all the elements of "extra" collection into "a" collection at
position no. "3"
a.InsertRange(3, extra);
//get values from list collection
foreach (int item in a)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
Output
This method removes the specified value in the end of existing collection.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithRemoveExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50 };
Output
This method removes the existing value at the specified index in the existing collection.
index: This parameter represents the index, where the value is to be removed.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithRemoveAtExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 120, 200 };
Output
7 void Clear()
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithClearExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int> { 10, 20, 50 };
Console.ReadKey();
}
}
}
Output
The “IndexOf” method performs linear search. That means it searches all the elements of
the collection, until the search value is found. When the search value is found in the
collection, it stops searching and returns its index.
The linear search has good performance, if the array is small. But if the collection is
larger, "Binary search" is recommended to improve the performance.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithIndexOfExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 120, 200 };
//search for "50" in the list collection & get its index
int n = a.IndexOf(50);
Console.WriteLine(n);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithIndexOfNotFound
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int>() { 10, 40, 50, 120, 200 };
//search for "500" in the list collection & get its index
int n = a.IndexOf(500);
Console.WriteLine(n);
Console.ReadKey();
}
}
}
Output
"System.Collections.Generic. List.BinarySearch"
method
Sl. No Method
The “BinarySearch” method performs binary search. The “Binary Search” requires a
collection, which is already sorted. On unsorted collection, binary search is not possible.
Binary search means it directly goes to the middle of the collection (collection size / 2),
and checks that item is less than / greater than the search value. If that item is greater
than the search value, it searches only in the first half of the collection. If that item is less
than the search value, it searches only in the second half of the collection. Thus it
searches only half of the collection. So in this way, it saves performance.
"System.Collections.Generic. List.BinarySearch"
method - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithBinarySearchExample
{
class Program
{
static void Main()
{
//list collection with sorted items (values should in a ascending order)
List<int> a = new List<int> { 10, 20, 50, 80, 100 };
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithContainsExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int> { 10, 20, 50, 80, 100 };
Console.ReadKey();
}
}
}
Output
12 void Reverse()
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithReverseExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int> { 50, 20, 100, 30, 500, 150, 300 };
Output
11 void Sort()
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithSortExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int> { 50, 20, 100, 30, 500, 150, 300 };
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace ListWithSortDescendingExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int> { 50, 20, 100, 30, 500, 150, 300 };
Console.ReadKey();
}
}
}
Output
Collection Filter
• To get elements based on the condition, write a foreach loop to iterate through each
element, check the condition and add the matching element into another collection.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace CollectionFilterExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int> { 50, 27, 105, 34, 55, 80, 100, 133 };
//read all the elements from "a" collection, check the condition, and
add the matching elements into a new collection called "b"
foreach (int item in a)
{
if (item % 2 == 0)
{
b.Add(item);
}
}
//get values from the new collection
foreach (int item in b)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
}
Output
LINQ
Understanding LINQ
• LINQ stands for "Language Integrated Query".
• It is a concept to retrieve conditional data from an array or collection & store the matching
elements in another collection.
➢ The “from clause” represents the variable. Each value from the collection will be
loaded into the variable; and then the where condition will be checked. If the
condition is true, then the value will be added to the result collection.
➢ The “in” clause represents the array / collection from which the data has to be
fetched.
➢ The “select” clause represents the value that has to be added to the result
collection / array.
LINQ - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqExample
{
class Program
{
static void Main()
{
//create list collection
List<int> a = new List<int> { 50, 27, 105, 34, 55, 80, 100, 133 };
//read all the elements from "a" collection, check the condition, and
add the matching elements into a new collection called "b" using LINQ
(Language Integrated Query)
b = (from item in a where (item % 2 == 0) select item).ToList();
Console.ReadKey();
}
}
}
Output
Collection of Objects
• An object stores a set of Fields.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace CollectionOfObjectsExample
{
class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Marks { get; set; }
}
class Program
{
Output
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
Program.cs
using System;
using System.Collections.Generic;
namespace CollectionOfObjectsFilterExample
{
class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Marks { get; set; }
class Program
{
static void Main()
{
//create 4 reference variables for Student class
Student s1, s2, s3, s4;
Console.Write(s.StudentName);
Console.Write(", ");
Console.WriteLine(s.Marks);
}
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace CollectionOfObjectsLinqExample
{
class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
public int Marks { get; set; }
}
class Program
{
static void Main()
{
//create a collection of "Student" type and initialize 4 objects
List<Student> Students = new List<Student>()
{
new Student() { StudentID = 1, StudentName = "scott", Marks = 40 },
new Student() { StudentID = 2, StudentName = "allen", Marks = 25 },
new Student() { StudentID = 3, StudentName = "jones", Marks = 70 },
new Student() { StudentID = 4, StudentName = "john", Marks = 32 }
};
//read all the objects from "Students" collection, check the condition,
and add matching objects into a new collection using LINQ
Output
System.Collections.Generic.Dictionary
• "Dictionary" is a pre-defined class in "System.Collections.Generic" namespace.
• Example:
Key Value
Maths 60
Physics 70
Chemistry 80
• It is also generic class that receives two data types; one is for key; other one is for value.
• We can get the value based on the key, rather than based on index.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace DictionaryExample
{
class Program
{
static void Main()
{
//create reference variable for dictionary collection
Dictionary<string, int> Marks;
Console.ReadKey();
}
}
}
Output
System.Collections.Generic.SortedList
• "SortedList" is a pre-defined class in "System.Collections.Generic" namespace.
• It is also generic class that receives two data types; one is for key, other one is for value.
• It automatically sorts the data while adding elements itself. So that it will be faster while
retrieving the values.
• We can get the value based on the key, rather than based on index.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections.Generic;
namespace SortedListExample
{
class Program
{
static void Main()
{
//create reference variable for SortedList collection
SortedList<string, int> Marks;
Output
System.Collections.Hashtable
• "Hashtable" is a pre-defined class in "System.Collections" namespace.
• Hashtable is similar to Dictionary, but no need to specify the data types for key and value;
so that the key and value can be of any data type.
• We can get the value based on the key, rather than based on index.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections;
namespace HashtableExample
{
class Program
{
static void Main()
{
//create reference variable for Hashtable collection
Hashtable Marks;
Console.ReadKey();
}
}
}
Output
System.Collections.ArrayList
• "ArrayList" is a pre-defined class in "System.Collections" namespace.
• It is similar to List, but no need to specify the data type for value; so that the value can be
of any data type.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections;
namespace ArrayListExample
{
class Program
{
static void Main()
{
//create reference variable for ArrayList collection
ArrayList MyData;
//create object for ArrayList collection
MyData = new ArrayList();
//add items
MyData.Add(100);
MyData.Add(100.2398);
MyData.Add("hyderabad");
MyData.Add(true);
MyData.Add(DateTime.Now);
Output
"typeof" operator:
• The "typeof" operator is used to check the data type of a value.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Collections;
namespace TypeofExample
{
class Program
{
static void Main()
{
//create reference variable for ArrayList collection
ArrayList MyData;
//add items
MyData.Add(100);
MyData.Add(150);
MyData.Add(100.2398);
MyData.Add("hyderabad");
MyData.Add(true);
MyData.Add(DateTime.Now);
{
if (MyData[i].GetType() == typeof(int))
{
int n = Convert.ToInt32(MyData[i]);
Console.WriteLine(n);
}
else if (MyData[i].GetType() == typeof(double))
{
double n = Convert.ToDouble(MyData[i]);
Console.WriteLine(n);
}
else if (MyData[i].GetType() == typeof(string))
{
string n = Convert.ToString(MyData[i]);
Console.WriteLine(n);
}
else if (MyData[i].GetType() == typeof(bool))
{
bool n = Convert.ToBoolean(MyData[i]);
Console.WriteLine(n);
}
else if (MyData[i].GetType() == typeof(DateTime))
{
DateTime n = Convert.ToDateTime(MyData[i]);
Console.WriteLine(n);
}
}
Console.ReadKey();
}
}
}
Output
• The “System.String” class provides a set of properties and methods to manipulate strings.
2) string ToLower()
▪ It returns the part of the string, starting from specified index, up to end of
the string.
▪ It returns the part of the string, starting from specified index, the specified
no. of characters.
▪ It removes the part of the string, starting from specified index, up to end of
the string, and returns the remaining string.
▪ It inserts the given string value in the main string at the specified index and
returns the result string.
▪ It compares the main string and string value, whether those are equal or
not. It returns true if the both are equal. It returns false if both are not
equal.
▪ Same as “Equals” method, but it ignores the case (upper case / lower case).
▪ It returns true if the given value exists at the beginning of string. It returns
false if the give value exists at the beginning of string.
▪ It returns true if the given value exists at the ending of string. It returns
false if the give value not exists at the ending of string.
▪ It returns true if the given value exists in the string. It returns false if the
given value exists in the string.
▪ It searches and returns the index of first character of given value in the
string. It returns -1 if is not found.
▪ It is same as IndexOf() method, but searching starts from end of the string.
(searching will be done from right-to-left).
▪ It splits the string into small strings on each occurrence of given separator
and returns all small strings as a string array.
▪ It substitutes place holders with the arguments, and returns the final
string. It is a static method.
Note: No string method modifies the existing string object. It creates a new string object, stores
the result string in it and returns the same string object.
“System.String.Length” - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace LengthExample
{
class Program
{
static void Main()
{
//create a string
string s = "Hyderabad";
Console.ReadKey();
}
}
}
Output
“System.String.ToUpper” - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ToUpperExample
{
class Program
{
static void Main()
{
//create a string
string s = "Hyderabad";
//display
Console.WriteLine(s); //Output: Hyderabad
Console.WriteLine(s2); //Output: HYDERABAD
Console.ReadKey();
}
}
}
Output
“System.String.ToLower” - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ToLowerExample
{
class Program
{
static void Main()
{
//create a string
string s = "HYDERABAD";
//display
Console.WriteLine(s); //Output: HYDERABAD
Console.WriteLine(s2); //Output: hyderabad
Console.ReadKey();
}
}
}
Output
“System.String.GetChar” - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace GetCharExample
{
class Program
{
//display
Console.WriteLine(ch); //Output: r
Console.ReadKey();
}
}
}
Output
“System.String.Substring” – Example 1
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace SubstringExample1
{
class Program
{
static void Main()
{
//create a string
string s = "Hyderabad";
//get sub string (from 4th character - till end of the string)
string s2 = s.Substring(4);
//display
Console.WriteLine(s2); //Output: rabad
Console.ReadKey();
}
}
}
Output
“System.String.Substring” – Example 2
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace SubstringExample2
{
class Program
{
static void Main()
{
//create a string
string s = "hyderabad";
//get sub string (from 4th character - only 2 characters length)
string s2 = s.Substring(4, 2);
//display
Console.WriteLine(s2); //Output: ra
Console.ReadKey();
}
}
}
Output
“System.String.Remove” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace RemoveExample
{
class Program
{
static void Main()
{
//create string & integer
string s = "Hyderabad";
int ind = 4;
//remove part of the string, starting from index "4" - till the end of
string & return the remaining part of the string.
string s2 = s.Remove(ind);
//display
Console.WriteLine(s2); //Output: Hyde
Console.ReadKey();
}
}
}
Output
“System.String.Remove” – Example 2
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace RemoveExample2
{
class Program
{
static void Main()
{
//create string & integers
string s = "Hyderabad";
int ind = 4;
int len = 3;
//remove part of the string, starting from index "4" - upto "3"
characters length & get the remaining part of the string
string s2 = s.Remove(ind, len);
//display
Console.WriteLine(s2); //Output: Hydead
Console.ReadKey();
}
}
}
Output
“System.String.Insert” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace InsertExample
{
class Program
{
static void Main()
{
//create strings & integer
string s = "Hyderabad";
string s2 = "abc";
int ind = 4;
//display
Console.WriteLine(s3); //Output: Hydeabcrabad
Console.ReadKey();
}
}
}
Output
“System.String.Equals” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace EqualsExample
{
class Program
{
static void Main()
{
//create strings
string s1 = "Hyderabad";
string s2 = "Hyderabad";
//display
Console.WriteLine(b); //Output: True
Console.ReadKey();
}
}
}
Output
“System.StringComparison. OrdinalIgnoreCase” –
Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace IgnoreCaseExample
{
class Program
{
static void Main()
{
//create strings
string s1 = "Hyderabad";
string s2 = "hyderabad";
//display
Console.WriteLine(b); //Output: True
Console.ReadKey();
}
}
}
Output
“System.String.StartsWith” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace StartsWithExample
{
class Program
{
static void Main()
{
//create strings
string s = "hyderabad";
string s2 = "hyd";
//check whether "hyderabad" starting with "hyd" or not
bool b = s.StartsWith(s2);
Console.WriteLine(b); //Output: True
Console.ReadKey();
}
}
}
Output
“System.String.EndsWith” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace EndsWithExample
{
class Program
{
static void Main()
{
//create strings
string s = "hyderabad";
string s2 = "bad";
//check whether "hyderabad" ending with "bad" or not
bool b = s.EndsWith(s2);
Console.WriteLine(b); //Output: True
Console.ReadKey();
}
}
}
Output
“System.String.Contains” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ContainsExample
{
class Program
{
static void Main()
{
//create strings
string s = "Hyderabad";
string s2 = "dera";
//check whether "Hyderabad" contains "dera" or not
bool b = s.Contains(s2);
//display
Console.WriteLine(b); //Output: True
Console.ReadKey();
}
}
}
Output
“System.String.IndexOf” – Example 1
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace IndexOfExample1
{
class Program
{
static void Main()
{
//create strings
string s = "Hyderabad";
string s2 = "dera";
//get the index of "dera" in "Hyderabad"
int ind = s.IndexOf(s2);
//display
Console.WriteLine(ind); //2
Console.ReadKey();
}
}
Output
“System.String.IndexOf” – Example 2
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace IndexOfExample2
{
class Program
{
static void Main()
{
//create strings
string s = "hyderabad";
string s2 = "a";
Console.ReadKey();
}
}
}
Output
“System.String.IndexOf” – Example 3
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace IndexOfExample3
{
class Program
{
static void Main()
{
//create strings
string s = "Hyderabad";
string s2 = "xyz";
//display
Console.WriteLine(ind); //Output: -1
Console.ReadKey();
}
}
}
Output
“System.String.LastIndexOf” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace LastIndexOfExample
{
class Program
{
static void Main()
{
//create strings
string s = "Hyderabad";
string s2 = "a";
//display
Console.WriteLine(ind); //7
Console.ReadKey();
}
}
}
Output
“System.String.Replace” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ReplaceExample
{
class Program
{
static void Main()
{
//create strings
string s = "Apple Smart Phones";
string s2 = "Apple";
string s3 = "Samsung";
Console.ReadKey();
}
}
}
Output
“System.String.ToCharArray” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ToCharArrayExample
{
class Program
{
static void Main()
{
//create string
string s = "hyderabad";
//read each character from the "character array" using for loop
for (int i = 0; i < ch.Length; i++)
{
Console.WriteLine(ch[i]);
}
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace CharArrayToStringExample
{
class Program
{
static void Main()
{
//create character array
char[ ] ch = new char[9] { 'H', 'y', 'd', 'e', 'r', 'a', 'b', 'a', 'd' };
//convert character array to string
string s = new String(ch);
//display string
Console.WriteLine(s); //Output: Hyderabad
Console.ReadKey();
}
}
}
Output
“System.String.Split” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace SplitExample
{
class Program
{
static void Main()
{
//create string and character
string s = "Hyderabad is one of the cities in India";
char ch = ' ';
//convert the "string" into "string array" at each occurrence of " "
(space)
string[ ] s2 = s.Split(ch);
Output
“System.String.Trim” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace TrimExample
{
class Program
{
static void Main()
{
//create string
string s = " Hyderabad ";
//trim the string (remove extra spaces at "most left side" and "most
right side")
string s2 = s.Trim();
int len2 = s2.Length;
Console.WriteLine(s2); //Output: "Hyderabad"
Console.WriteLine(len2); //Output: 9
Console.ReadKey();
}
}
}
Output
“System.String.Format” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace FormatExample
{
class Program
{
static void Main()
{
//create strings
string s1 = "scott";
string s2 = "allen";
string original = "{0} and {1} are now friends";
//Substitute "scott" in {0} place and "allen" in {1} place.
string final = string.Format(original, s1, s2);
Console.WriteLine(final); //Output: scott and allen are now friends.
Console.ReadKey();
}
}
Output
“System.String.Reverse” – Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ReverseExample
{
class Program
{
static void Main()
{
//create strings
string s = "hyderabad";
string s2 = "";
//read each character using for loop and append it to a new string
for (int i = s.Length - 1; i >= 0; i--)
{
s2 = s2 + s[i];
}
Console.WriteLine(s2); //dabaredyh
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace WordsCountExample
{
class Program
{
static void Main()
{
//create a string
string s = "She sells sea shells on the sea shore";
//read each character and check it whether the character is " " (space)
or not. If it is space, increment the counter variable
for (int i = 0; i < s.Length; i++)
{
if (s[i] == ' ')
c++;
}
Console.WriteLine(c); //Output: 8
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace CharacterOccurrenceCountExample
{
class Program
{
static void Main()
{
//create a string
string s = "She sells sea shells on the sea shore";
//create a character
char ch = 's';
Console.WriteLine(c); //Output: 7
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace AlphabetsCountExample
{
class Program
{
static void Main()
{
//create a string
string s = "She sells sea shells on the sea shore";
c++;
}
Console.WriteLine(c); //Output: 30
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace WordOccurrenceCountExample
{
class Program
{
static void Main()
{
//create strings
string s = "She sells sea shells on the sea shore";
string s2 = "sea";
//if all the chracters are matched, increment the counter variable
if (flag == true)
c++;
}
}
Console.WriteLine(c); //Output: 2
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace TitleCaseExample
{
class Program
{
static void Main()
{
//create strings
string s = "she sells sea shells on the sea shore";
string s2 = "";
char ch = ' ';
//converting into "Title Case" (Every word starts with capital letter).
for (int i = 0; i < words.Length; i++)
{
s2 += words[i][0].ToString().ToUpper() +
words[i].Substring(1).ToLower() + " ";
}
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Text;
namespace CurrencyIntoWordsExample
{
class Program
{
static void Main()
{
//actual number that is to be converted into currency
int number = 1234;
//create string
string result;
goto end;
}
int first = 0;
int u, h, t;
//create stringbuilder
StringBuilder sb = new StringBuilder();
if (num[i] != 0)
{
first = i;
break;
}
}
Console.WriteLine(number);
Console.WriteLine(result);
Console.ReadKey();
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace MultipleConcatenationsExample
{
class Program
{
static void Main()
{
//create strings
string s1, s2, s3, s4, result;
s1 = "Hello "; //string object 1
s2 = "how "; //string object 2
s3 = "are "; //string object 3
s4 = "you"; //string object 4
//concatenations
result = s1;
result = result + s2; //string object 5
result = result + s3; //string object 6
Console.ReadKey();
}
}
}
Output
System.Text.StringBuilder
• “StringBuilder” is a pre-defined class in “System.Text” namespace.
• The string builder can be appendable any no. of times, without creating a separate object.
• String concatenation always creates a new object for “System.String” class; but string
builder allows the value to be appended any no. of times. So string builder saves memory
when compared with string concatenation, in case of many appendings.
❖ using System.Text;
❖ StringBuilder sb;
❖ sb = new StringBuilder();
• Append string:
❖ sb.Append(string value);
❖ sb.ToString();
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Text;
namespace StringBuilderExample
{
class Program
{
static void Main()
{
//create strings
string s1, s2, s3, s4;
s1 = "Hello "; //string object 1
s2 = "how "; //string object 2
s3 = "are "; //string object 3
s4 = "you"; //string object 4
Output
2) int Day
3) int Month
4) int Year
5) int Hour
6) int Minute
7) int Second
8) int MilliSecond
9) string DayOfWeek.ToString()
▪ It returns the date in the following format: dddd, MMMM dd, yyyy
▪ It subtracts the main date with given dt2, and returns the difference dates in the
form of TimeSpan.
▪ It adds the ‘n’ no. of days to the main date and returns the result date.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace DateTimeFirstExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
//set value
d = Convert.ToDateTime("2/10/2016 5:30 PM");
//get value
Console.WriteLine(d);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace NowExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
//set system date and time into the variable
d = DateTime.Now;
//get value
Console.WriteLine(d);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace InnerValuesExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
//display values
Console.WriteLine("Day: " + dy);
Console.WriteLine("Month: " + m);
Console.WriteLine("Year: " + y);
Console.WriteLine();
Console.WriteLine("Hour: " + h);
Console.WriteLine("Minute:" + mi);
Console.WriteLine("Second: " + s);
Console.WriteLine();
Console.WriteLine("Milli Second: " + ms);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace DayOfWeekExample
{
class Program
{
static void Main()
{
//create variable of DateTime data type
DateTime d;
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace DayOfYearExample
{
class Program
{
static void Main()
{
//create variable of DateTime data type
DateTime d;
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ShortDateExample
{
class Program
{
static void Main()
{
//create variable of DateTime data type
DateTime d;
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace LongDateExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ShortTimeExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace LongTimeExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace CustomFormatsExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
//display values
Console.WriteLine("d/M/yyyy: " + str1);
Console.WriteLine("yyyy/M/d: " + str2);
Console.WriteLine("h:m:s: " + str3);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace SubtractExample
{
class Program
{
//subtract dt2 from dt1 (get the no. of days between 7/8 /2011 till
date)
TimeSpan ts;
ts = dt1.Subtract(dt2);
//display the no. of days difference between dt1 and dt2 (dt1 - dt2)
string msg = ts.TotalDays + " days";
Console.WriteLine(msg);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace AddDaysExample
{
class Program
{
static void Main()
{
//create a variable of DateTime data type
DateTime d;
//set system date and time into the variable
d = DateTime.Now;
//add 10 days
DateTime temp = d.AddDays(10);
Console.WriteLine(temp);
Console.ReadKey();
}
}
}
Output
▪ It returns the current number without decimal part, if the first digit of the
decimal part is less than 5.
▪ It returns the next number without decimal part, if the first digit of the decimal
part is greater than or equal to 5.
8) double Sqrt(double n)
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace AbsExample
{
class Program
{
static void Main()
{
double n = -100;
double result;
//convert the negetive value into positive value
result = Math.Abs(n);
Console.WriteLine(n);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace FloorExample
{
class Program
{
static void Main()
{
double n = 100.3492;
double result;
//get the floor value (without decimal part)
result = Math.Floor(n);
Console.WriteLine(n);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace CeilingExample
{
class Program
{
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace RoundExample
{
class Program
{
static void Main()
{
double n = 100.3492;
double result;
//get the next number if the first digit in decimal part is greater than
or equal to "5"; get the previous number if the first digit in decimal part is
less than "5".
result = Math.Round(n);
Console.WriteLine(n);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace RoundExample2
{
class Program
{
static void Main()
{
double n = 100.6492;
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace MaxExample
{
class Program
{
static void Main()
{
double n1 = 100, n2 = 200;
double result;
//get the big value among n1 and n2
result = Math.Max(n1, n2);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace MinExample
{
class Program
{
static void Main()
{
double n1 = 100, n2 = 200;
double result;
//get the smaller value among n1 and n2
result = Math.Min(n1, n2);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace PowExample
{
class Program
{
static void Main()
{
double n1 = 10, n2 = 3;
double result;
//get the result of "10" power "3"
result = Math.Pow(n1, n2);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace SqrtExample
{
class Program
{
static void Main()
{
double n = 10;
double result;
//get square root of 10
result = Math.Sqrt(n);
Console.WriteLine(result);
Console.ReadKey();
}
}
}
Output
“System.Diagnostics.Process” class
System.Diagnostics.Process
• “Process” is a pre-defined class in “System.Diagnostics” namespace.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Diagnostics;
namespace ProcessExample
{
class Program
{
static void Main()
{
//call "System.Diagnostics.Process.Start" method to run calculator
Process.Start(@"C:\windows\system32\calc.exe");
//show message
Console.WriteLine("Calculator opened");
Console.ReadKey();
}
}
}
Output
• All the command line arguments will be received by the Main method as a string array.
• This technique is used in most of the windows applications such as Notepad, MS Office
Word, VLC Media Player etc.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace App1
{
class Program
{
static void Main(string[ ] args)
{
if (args.Length >= 2)
{
Console.WriteLine(args[0]);
Console.WriteLine(args[1]);
}
Console.ReadKey();
}
}
}
C:\CSharp\App1\App1\bin\Debug\App1.exe 10 20
• Click on OK.
Output
[or]
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace NullableDataTypesExample
{
class Program
{
static void Main()
{
//create a nullable variable
int? n;
//set "null" value into nullable variable
n = null;
//get the value of nullable variable
Console.WriteLine("n value is: " + n);
Console.ReadKey();
}
}
}
Output
Exception Handling
Exception Handling
• Exception means “run time error”.
• When a statement can’t be executed due to some reason, system treat it as a run time
error (exception).
• Exceptions raise based on different factors like programmer’s mistake, system problem,
database connection or SQL statement execution problem etc.
• When exception is raised, the programs gets terminated un-expectedly (or) abruptly. It is
inconvenience to the user. So the programmer has to use “exception handling” concept to
avoid un-expected closing of the application.
• Exception handling is used to catch the run time errors (exceptions) and display the error
message on the same page, instead of closing the application un-expectedly.
Syntax:
try
{
Code here
}
catch (Exception ex)
{
Code here
}
finally
{
Code here
}
• “Catch” block: Executes only when the exception is raised in try block. It receives the
exception details as “ex” object.
• “Finally” block”: Executes after completion of try block or catch block. Finally block is
optional.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace ExceptionHandlingExample
{
class Program
{
static void Main()
{
try
{
Console.Write("Enter first number: ");
int a = Convert.ToInt32(Console.ReadLine());
int c = a / b;
Console.ReadKey();
}
}
}
Output
Destructor
• Destructor is a special method of the class, which will be automatically called before
deleting each object of the class.
• By using “destructors”, C#.NET allows the programmer to execute any code, just before
deleting an object.
Syntax of destructor:
~classname()
{
}
Destructor - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace DestructorExample
{
class Class1
{
//constructor
public Class1()
{
Console.WriteLine("Constructor");
//Ex: opening the db connection
}
//destructor
~Class1()
{
Console.WriteLine("Destructor");
//Ex: closing the db connection
}
}
class Program
{
static void Main()
{
Class1 c1 = new Class1(); //constructor will be called here
//lot of code
//db work is over
Console.ReadKey();
} //destructor will be called here
}
}
Output
System.IDisposable
• “System.IDisposable” is a pre-defined interface, which contains only one abstract method
called “Dispose”. The “Dispose” method will be called automatically, when “using”
statement is used while creating object. In the “Dipose” method, you can perform any
cleaning process such as closing database connections or closing files etc.
• The benefit of using “Dispose” method instead of “destructor” is: the “Dispose” method will
be called automatically as soon as “using” statement ends; then the cleaning process will be
performed through “Dispose” method; so that we release the resources such as database
connections and file connections; no need to wait until the end of the application.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
Program.cs
using System;
namespace IDisposeExample
{
class Class1 : System.IDisposable
{
public Class1()
{
Console.WriteLine("object created");
//db connection opened
}
public void method1()
{
Console.WriteLine("method1");
}
public void Dispose()
{
Console.WriteLine("disposed");
//db connection closed
}
~Class1()
{
//destructor
Console.WriteLine("destructor");
}
}
class Program
{
static void Main()
{
using (Class1 c1 = new Class1())
{
c1.method1();
} //Dispose
Console.ReadKey();
} //Destructor
}
}
Output
Garbage Collection
• Garbage collection is a process of deleting unreferenced variables or objects from memory.
• Garbage collection will be performed automatically; but it will be performed at the end of
main method only.
• Syntax: System.GC.Collect();
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace GarbageCollectionExample
{
class Class1
{
~Class1()
{
Console.WriteLine("Destructor");
}
}
class Program
{
static void Main()
{
//create two objects
Class1 c1 = new Class1();
Class1 c2 = new Class1();
c1 = null;
Console.ReadKey();
}
}
}
Output
Delegates
Delegates
• Delegate is a reference variable that contains reference of one or more methods that have
same signature.
Creating Project
• Open Visual Studio 2019.
Program.cs
using System;
namespace SingleCastDelegatesExample
{
class Class1
{
//create target method
public void Add(int a, int b)
{
int c = a + b;
Console.WriteLine("Sum is " + c);
}
}
class Program
{
//create object
Class1 c1 = new Class1();
Output
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace MultiCastDelegatesExample
{
class Class1
{
//create target method 1
public void Add(int a, int b)
{
int c = a + b;
Console.WriteLine("Sum is " + c);
}
}
}
class Program
{
static void Main()
{
//create a delegate
MyDelegateType d;
//create object
Class1 c1 = new Class1();
//store the address of Add method into delegate
d = c1.Add;
//store the address of Subtract method also into the delegate
d += c1.Subtract;
//call the Add and Subtract methods using delegate
d(10, 3);
Console.ReadKey();
}
}
}
Output
Events
• Events are used to implement “publisher – subscriber” model.
• “Publisher” is a class that contains an event and also raises the event.
• “Subscriber” is a class that subscribes to the event of publisher class. That means
subscriber class provides an event handler that can be attached to the event.
• When the event is raised in the publisher class, the event handler method will be executed.
• In real time, publisher class will be developed by one programmer and subscriber class will
be developed by other programmer.
class subscriberclassname
{
}
eventname += methodname ;
Events - Example
Creating Project
• Open Visual Studio 2019.
Program.cs
using System;
namespace EventsExample
{
public delegate void mydelegatetypename(string username);
class publisherclass
{
public event mydelegatetypename myevent;
pc.raiseevent("Scott");
pc.raiseevent("Allen");
}
}
class Program
{
static void Main()
{
subscriberclass sc = new subscriberclass();
sc.connect();
Console.ReadKey();
}
}
}
Output
Anonymous Methods
• Anonymous methods are used to quickly create a method inside another method.
• Anonymous method’s address should be stored in a delegate (or) event, through the
delegate or event only we can call it.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace AnonymousMethodsExample
{
class publisherclass
{
public event mydelegatetype myevent;
public int x = 0, y = 0;
class subscriberclass
{
public void dowork()
{
publisherclass pc = new publisherclass();
pc.myevent += delegate(int a, int b)
{
int c = a + b;
Console.WriteLine("Sum is " + c);
};
pc.increment();
}
}
class Program
{
static void Main()
{
subscriberclass sc = new subscriberclass();
sc.dowork();
Console.ReadKey();
}
}
}
Output
Lambda Expressions
• Lambda Expressions are used to quickly create a method inside another method.
• Lambda Expressions’s address should be stored in a delegate (or) event, through the
delegate or event only we can call it.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace LambdaExpressionsExample
{
class publisherclass
{
public event mydelegatetype myevent;
public int x = 0, y = 0;
public void increment()
{
x += 5;
y += 5;
myevent(x, y);
}
}
class subscriberclass
{
public void dowork()
{
publisherclass pc = new publisherclass();
pc.myevent += (a, b) =>
{
int c = a + b;
Console.WriteLine("Sum is " + c);
};
pc.increment();
}
}
}
}
}
Output
• Inline lambda expressions can contain only just a single calculation; can’t contain any other
additional code.
• Inline lambda expressions can receive or more arguments; must return a value.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace InlineLambdaExample
{
class publisherclass
{
public event mydelegatetype myevent;
public int x = 0, y = 0;
class Program
{
static void Main()
{
subscriberclass sc = new subscriberclass();
sc.dowork();
Console.ReadKey();
}
}
}
Output
Inner Classes
• Class inside another class is called as “inner class”.
• Use “inner class”, if you want to specify that the class is a part of the outer class logically.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace InnerClassesExample
{
class Class1
{
public class Class2
{
public void mymethod()
{
Console.WriteLine("mymethod");
}
}
}
class Program
{
static void Main()
{
Class1.Class2 c2 = new Class1.Class2();
c2.mymethod();
Console.ReadKey();
}
}
}
Output
Indexer
Indexer
• Indexer makes it easy to access a member array through the reference variable of a class.
• Indexer overloading is possible. That means we can create multiple indexers in the same
class, with different arguments.
• Mostly indexers are used in pre-defined classes; it’s rare to use indexers in user-defined
classes in real time.
Indexer - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace IndexerExample
{
class Class1
{
//creating an array
public string[] cities = new string[] { "Hyderabad", "Chennai",
"Bangalore" };
public long[] population = new long[] { 9000, 5000, 10000 };
//indexer
public long this[string city]
{
get
{
int n = Array.IndexOf(cities, city);
return population[n];
}
}
}
class Program
{
static void Main()
{
Class1 c1 = new Class1();
long p = c1["Chennai"];
Console.WriteLine(p);
//Console.Write(c1.population[Array.IndexOf(c1.cities, "Chennai")]);
Console.ReadKey();
}
}
}
Output
Assemblies
• In .NET, an “Assembly” is a file that contains “compiled source code (in MSIL language) of
the .net program”.
• Assemblies can’t be run directly based on the operating system; can only by run by CLR
(Common Language Runtime). CLR reads MSIL code from assembly and convert the same
into native machine language automatically, while .net program exection.
1. Executable assemblies
2. Library assemblies
Executable Assemblies
• “Executable assemblies” are “EXE files” that can run directly (based on CLR).
• When you compile the following types of applications, Visual Studio automatically
generates (creates) an “Executable Assembly”:
o Console Application
o Windows Forms Application
o Windows Service
Library Assemblies
• “Library Assemblies” are “DLL files” that can’t run directly. The library assemblies are
always “supporting files” to “Executable Assembly”. Executable assemblies dynamically call
the library assemblies at run time.
• When you compile the following types of applications, Visual Studio automatically
generates (creates) an “Library Assembly”:
o Class Library
o Windows Forms Control Library
1. Private Assemblies
2. Shared Assemblies
Private Assemblies
• Private assemblies (dll files) should be placed in each “application folder”.
• Private assemblies are faster in execution but there is memory wastage, if multiple
applications are consuming the same private assembly and are running on same system.
Shared Assemblies
• Shared assemblies are located in GAC (Global Assembly Cache) folder and can be accessed
by the applications that are running on the same system.
• Shared assemblies save memory, because there is no need of duplicate copies of dll file in
every app’s folder.
GAC
• GAC (Global Assembly Cache) is a special folder in .NET Framework, which contains all the
• The shared dll files that are present at GAC folder can be accessible from any application
• DLL hell: When we install a new version of an application, the dll files of old version of the
application will be overwritten with latest version’s dll files. GAC folder solves this problem
SNK
• An assembly must have “snk” (Strong Name Key) to be placed in GAC folder.
• SNK (Strong Name Key) file is contains “unique code”, which is useful for “unique
• SNK file can be created in visual studio through the “project properties” – “Signing” option.
Class Library
• “Class Library” is a special type of project in Visual Studio.
• When the class library project is compiled, a “library assembly” (DLL file) will be
genereated.
• Click on OK.
Class1.cs
using System;
namespace ClassLibrary1
{
public class Class1
{
public bool CheckEmail(string Email)
{
bool b;
if (Email.Contains(" ") == false && Email.IndexOf("@") > 0)
{
b = true;
}
else
{
b = false;
}
return b;
}
}
}
• Click on OK.
Add reference
• Open solution explorer.
• Right click on the project name (ConsoleApplication1) and click on “Add” – “Reference”.
• Click on “Browse”.
• Then it shows the “ClassLibrary1” in the “References” list in the solution explorer.
Program.cs
using System;
using ClassLibrary1;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
Class1 c1 = new Class1();
string s = "[email protected]";
bool result = c1.CheckEmail(s);
if (result == true)
{
Console.WriteLine(s);
Console.WriteLine("Valid email address");
}
else
{
Console.WriteLine(s);
Console.WriteLine("Invalid email address");
}
Console.ReadKey();
}
}
}
Output
• Click on OK.
Class1.cs
using System;
namespace ClassLibrary2
{
public class Class1
{
public bool CheckEmail(string Email)
{
bool b;
if (Email.Contains(" ") == false && Email.IndexOf("@") > 0)
{
b = true;
}
else
{
b = false;
}
return b;
}
}
}
• Type the file name as “demo”. Uncheck the checkbox “protect my key file with a password”.
Click on OK.
Command Prompt for VS 2015” and click on “Run as administrator”. Click on “Yes”.
gacutil –i "C:\CSharp\ClassLibrary2\ClassLibrary2\bin\Debug\ClassLibrary2.dll"
• Press Enter.
• Click on OK.
Add reference
• Open solution explorer.
• Right click on the project name (ConsoleApplication2) and click on “Add” – “Reference”.
• Click on “Browse”.
• Then it shows the “ClassLibrary2” in the “References” list in the solution explorer.
• Note: You can notice that the “ClassLibrary2.dll” file is not present in
the same folder, because it will be accessed from the GAC folder.
Program.cs
using System;
using ClassLibrary2;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
Class1 c1 = new Class1();
string s = "[email protected]";
bool result = c1.CheckEmail(s);
if (result == true)
{
Console.WriteLine(s);
Console.WriteLine("Valid email address");
}
else
{
Console.WriteLine(s);
Console.WriteLine("Invalid email address");
}
Console.ReadKey();
}
}
}
Output
Documentation Comments
• Documentation comments are used to provide description for the methods and its
arguments, which will be appear while calling the method (while typing the code in visual
studio).
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
namespace DocumentationCommentsExample
{
class Class1
{
/// <summary>Adds two numbers</summary>
/// <param name="firstNumber">First number for adding</param>
/// <param name="secondNumber">Second number for
adding</param>
public void Add(int firstNumber, int secondNumber)
{
//code here
}
}
class Program
{
static void Main()
{
Class1 c1 = new Class1();
c1.Add(10, 20);
Console.ReadKey();
}
}
}
Output
While typing the code in visual studio, it shows the description as tooltip.
Extension Methods
• Extension methods are methods that are indirectly injected into a compiled class, without
modifying its source code.
• Assume, there is a re-usable class in the class library and its reference is added in the client
project.
• From the class library, you can add a new method to the re-usable class, without modifying
the source code of the re-usable class.
• It should have atleas one argument of the target class type with “this” keyword. That
argument represents “this” keyword in the extension method. “This” keyword represents
the current object, based on which the method is called.
• The extension method can have maximum any no. of arguments, but minimum is one.
• Click on OK.
Class1.cs
using System;
namespace ClassLibrary1
{
public class Class1
{
public double getsquare(double n)
{
double sq = n * n;
return sq;
}
}
}
• Click on OK.
Add reference
• Open solution explorer.
• Right click on the project name (ConsoleApplication1) and click on “Add” – “Reference”.
• Click on “Browse”.
• Then it shows the “ClassLibrary1” in the “References” list in the solution explorer.
Program.cs
using System;
using ClassLibrary1;
namespace ConsoleApplication1
{
static class Class2
{
public static double getcube(this Class1 c1, double n)
{
double cb = n * n * n;
return cb;
}
}
class Program
{
static void Main()
{
Class1 c1 = new Class1();
int a = 10;
Output
C# – Console - System.IO
Namespace
2. System.IO.DirectoryInfo
3. System.IO.File
4. System.IO.Directory
5. System.IO.FileStream
6. System.IO.StreamWriter
7. System.IO.StreamReader
System.IO.FileInfo class
• The “FileInfo” is a class in “System.IO” namespace.
o using System.IO;
o FileInfo referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call method:
o referencevariable.methodname ();
Syntax: referencevariable.DirectoryName
2 Name Represents only name of the file with extension (without path).
Syntax: referencevariable.Name
Syntax: referencevariable.Extension
Syntax: referencevariable.FullName
5 Exists Represents whether the current file exists or not. It returns a Boolean
value.
Syntax: referencevariable.Exists
Syntax: referencevariable.Length
Syntax: referencevariable.CreationTime
Syntax: referencevariable.LastAccessTime
Syntax: referencevariable.LastWriteTime
Syntax: referencevariable.Attributes
Syntax: referencevariable.IsReadOnly
1 CopyTo() Copies the current file into the specified destination path.
Syntax: referencevariable.Delete()
3 MoveTo() Movies the current file into the specified destination path.
Creating Project
• Create the following folders and files:
o C:\CSharp
▪ Sample.pdf
• Click on OK.
Program.cs
//Note: Create "C:\CSharp\sample.txt"
using System;
using System.IO;
namespace namespace1
{
class Program
{
static void Main()
{
FileInfo f;
f = new FileInfo(@"c:\CSharp\sample.txt");
Console.WriteLine("Exists: " + f.Exists);
if (f.Exists)
{
Console.WriteLine("Full name: " + f.FullName);
Console.WriteLine("Name: " + f.Name);
Console.WriteLine("Directory name: " + f.DirectoryName);
Console.WriteLine("Extension: " + f.Extension);
Console.WriteLine("Creation date and time: " + f.CreationTime);
Console.WriteLine("Modification date and time: " +
f.LastWriteTime);
Console.WriteLine("Access date and time: " + f.LastAccessTime);
Console.WriteLine("Length: " + f.Length + " bytes");
}
Console.ReadKey();
}
}
}
Output
o using System.IO;
o DirectoryInfo referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call method:
o referencevariable.methodname ();
Syntax: referencevariable.Parent.FullName
2 Name Represents only name of the folder (without parent folder’s path).
Syntax: referencevariable.Name
Syntax: referencevariable.FullName
4 Root.FullName Represents full path of the root folder of the current folder.
Syntax: referencevariable.Root.FullName
Syntax: referencevariable.Exists
Syntax: referencevariable.CreationTime
Syntax: referencevariable.LastAccessTime
Syntax: referencevariable.LastWriteTime
Syntax: referencevariable.Attributes
Syntax: referencevariable.Delete()
2 Delete(true) Deletes the current folder, including all of its files and sub
folders.
Syntax: referencevariable.Delete(true)
3 MoveTo() Movies the current folder into the specified destination path.
Syntax: referencevariable.MoveTo(string
DestinationFolderPath)
Syntax: referencevariable.CreateSubdirectory(string
newfoldername)
Syntax: referencevariable.GetFiles()
Syntax: referencevariable.GetDirectories()
Creating Project
• Create the following folders and files:
o C:\CSharp
▪ sample
• firstfolder (folder)
• secondfolder (folder)
• thirdfolder (folder)
• Click on OK.
Program.cs
using System;
using System.IO;
namespace namespace1
{
class Program
{
static void Main()
{
DirectoryInfo d;
d = new DirectoryInfo(@"c:\CSharp\myfolder");
Console.WriteLine("Exists: " + d.Exists);
if (d.Exists)
{
Console.WriteLine("Full name: " + d.FullName);
Console.WriteLine("Name: " + d.Name);
Console.WriteLine("Directory name: " + d.Parent);
Console.WriteLine("Creation date and time: " + d.CreationTime);
Console.WriteLine("Modification date and time: " +
d.LastWriteTime);
Console.WriteLine("Access date and time: " + d.LastAccessTime);
Console.WriteLine("\nFiles:");
FileInfo[] files = d.GetFiles();
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine(files[i].FullName);
}
Console.WriteLine("\nSub directories:");
DirectoryInfo[] directories = d.GetDirectories();
for (int i = 0; i < directories.Length; i++)
{
Console.WriteLine(directories[i].FullName);
}
}
Console.ReadKey();
}
}
}
Output
• The “Directory” class is a static class, which provides a set of static methods to manipulate
folders.
o using System.IO;
o Directory.method ();
3 Delete() Deletes the specified folder permanently, including all of its sub folders
and files in it.
4 Move() Moves the specified source folder into the specified destination
location.
Rule: Both source and destination location should be in the same drive.
Ex: C: drive
Creating Project
• Create the following folders:
o C:\CSharp
▪ Sample (folder)
• Click on OK.
Program.cs
using System;
using System.IO;
namespace DirectoryExample
{
class Program
{
static void Main()
{
if (Directory.Exists(@"c:\folder1") == true)
{
Directory.Delete(@"C:\folder1", true);
}
if (Directory.Exists(@"c:\folder2") == true)
{
Directory.Delete(@"C:\folder2", true);
}
Directory.CreateDirectory(@"C:\folder1");
Console.WriteLine("folder1 created");
Console.WriteLine("folder1 exists: " + Directory.Exists(@"C:\folder1"));
//Output: True
Directory.Delete(@"C:\folder1");
Console.WriteLine("folder1 deleted");
Console.WriteLine("folder1 exists: " + Directory.Exists(@"C:\folder1"));
//Output: False
Directory.CreateDirectory(@"C:\folder1");
Console.WriteLine("folder1 created");
Directory.Move(@"C:\folder1", @"C:\folder2");
Console.WriteLine("folder1 moved as folder2");
Console.ReadKey();
}
}
}
Output
System.IO.File class
• The “File” is a class in “System.IO” namespace.
• The “File” class is a static class, which provides a set of static methods to manipulate files.
o using System.IO;
o File.method ();
2 Create() Create the specified file and returns corresponding FileStream’s object.
4 Move() Moves the specified source file into the specified destination location.
5 Copy() Copies the specified source file into the specified destination location.
Creating Project
• Create the following folders and files:
o C:\CSharp
Program.cs
using System;
using System.IO;
namespace FileExample
{
class Program
{
static void Main()
{
if (Directory.Exists(@"c:\folder1") == true)
{
Directory.Delete(@"c:\folder1", true);
}
Directory.CreateDirectory(@"c:\folder1");
Console.WriteLine("Folder created");
File.Create(@"c:\folder1\file1.txt").Close();
Console.WriteLine("File created");
File.Copy(@"c:\folder1\file1.txt", @"c:\folder1\file2.txt");
Console.WriteLine("File created");
File.Move(@"c:\folder1\file2.txt", @"c:\folder1\file3.txt");
Console.WriteLine("File moved");
Output
• The “FileStream” class is used to write data to a file (or) read data from an existing file in
byte[ ] format.
• But in fact, it is difficult to deal with byte[ ]. That’s why, often we use StreamWriter or
StreamReader to perform file reading or writing operations.
o “Create” mode: Used to create a new file and write data into the new file.
o using System.IO;
o FileStream referencevariable;
• Create an object:
o using System.IO;
o FileStream referencevariable;
• Create an object:
System.IO.StreamWriter class
• The “StreamWriter” is a class in “System.IO” namespace.
• The “StreamWriter” class is used to write data to a new / existing file in text format.
o using System.IO;
o StreamWriter referencevariable;
• Create an object:
o referencevariable.Close ();
Creating Project
• Create the following folder:
o C:\CSharp
• Click on OK.
Program.cs
//city.txt
using System;
using System.IO;
namespace namespace1
{
class Program
{
static void Main()
{
//delete the file, if it already exists
FileInfo f = new FileInfo(@"c:\CSharp\file1.txt");
if (f.Exists == true)
f.Delete();
Output
System.IO.StreamReader class
• The “StreamReader” is a class in “System.IO” namespace.
• The “StreamReader” class is used to read data from an existing file in text format.
o using System.IO;
o StreamReader referencevariable;
• Create an object:
o referencevariable.Close( );
Creating Project
• Create the following folder:
o C:\CSharp
• Click on OK.
Program.cs
//city.txt
using System;
using System.IO;
namespace namespace1
{
class Program
{
static void Main()
{
//check the file exists or not
FileInfo f = new FileInfo(@"c:\CSharp\file1.txt");
if (f.Exists == true)
{
//open the file
Output
Database Basics
• DBMS (Database Management System): It is a software, which is used to store and
Table Structure
1 EmpID Int
2 EmpName Nvarchar(max)
3 Salary decimal
Table: Employees
1 Scott 5000
2 Allen 6000
3 Jones 7000
4 John 8000
5 Mark 9000
Introduction to ADO.NET
Introduction to ADO.NET
• ADO.NET (ActiveX Data Objects .NET) is a “database technology” or “database
framework”, which is used to connect and interact with databases such as SQL Server,
Oracle, Excel, Access etc.
1. System.Data.SqlClient.SqlConnection
2. System.Data.SqlClient.SqlCommand
3. System.Data.SqlClient.SqlDataReader
4. System.Data.SqlClient.SqlDataAdapter
5. System.Data.SqlClient.SqlParameter
6. System.Data.SqlClient.SqlCommandBuilder
7. System.Data.SqlClient.SqlTransaction
8. System.Data.OleDb.OleDbConnection
9. System.Data.OleDb.OleDbCommand
10. System.Data.OleDb.OleDbDataReader
11. System.Data.OleDb.OleDbDataAdapter
12. System.Data.OleDb.OleDbParameter
13. System.Data.OleDb.OleDbCommandBuilder
14. System.Data.OleDb.OleDbTransaction
15. System.Data.DataSet
16. System.Data.DataTable
17. System.Data.DataRow
18. System.Data.DataColumn
19. System.Data.DataView
System.Data.SqlClient.SqlConnection
• The “SqlConnection” is a class, which is a member of “System.Data.SqlClient” namespace.
Syntax: referencevariable.ConnectionString
= “connection string here”;
Syntax: referencevariable.State
1 Open() void Opens the connection. After opening the connection, SQL
Server listens the requests you made.
Syntax: referencevariable.Open()
2 Close() void Closes the connection. After closing the connection, SQL
Server stops listening the requests you made.
Syntax: referencevariable.Close()
o using System.Data.SqlClient;
o SqlConnection referencevariable;
• Create an object:
o referencevariable.Open( );
o referencevariable.Close( );
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace WindowsAuthExample
{
class Program
{
static void Main()
{
//create reference variable
SqlConnection cn;
//create object
cn = new SqlConnection();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
//calling methods
Console.WriteLine(cn.State); //Output: Closed
cn.Open();
Console.WriteLine(cn.State); //Output: Open
cn.Close();
Console.WriteLine(cn.State); //Output: Closed
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace SqlServerAuthExample
{
class Program
{
static void Main()
{
//create reference variable
SqlConnection cn;
//create object
cn = new SqlConnection();
//calling properties
cn.ConnectionString = "data source=localhost; user id=sa;
password=123; initial catalog=company";
//calling methods
Console.WriteLine(cn.State); //Output: Closed
cn.Open();
Console.WriteLine(cn.State); //Output: Open
cn.Close();
Console.WriteLine(cn.State); //Output: Closed
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• This class’s object is used to execute an SQL statement or stored procedure through
database connection.
Syntax: referencevariable.Connection =
ReferenceVariableOfSqlConnectionClass;
Syntax: referencevariable.CommandType =
System.Data.CommandType.Optionhere;
Syntax:
referencevariable.Parameters.Add(ReferenceVari
ableOfSqlParameter)
Syntax: referencevariable.Transaction =
ReferenceVariableOfSqlTransaction;
Syntax: referencevariable.ExecuteScalar()
Syntax: referencevariable.ExecuteReader()
Syntax:
referencevariable.ExecuteNonQuery()
ADO.NET - ExecuteScalar
ExecuteScalar
• “ExecuteScalar” method is used to execute a “SELECT statement” or “stored procedure”
o using System.Data.SqlClient;
o SqlConnection cn;
o SqlCommand cmd;
• Create objects:
o cn = new SqlConnection();
• Call properties
o cmd.Connection = cn;
• Call methods
o cn.Open();
o cn.Close();
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
Program.cs
using System;
using System.Data.SqlClient;
namespace ExecuteScalarExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select EmpName from Employees where
EmpID=1";
cmd.Connection = cn;
/* call methods */
cn.Open();
object obj = cmd.ExecuteScalar();
cn.Close();
string n = Convert.ToString(obj);
string msg = "Emp Name: " + n;
Console.WriteLine(msg);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace ExecuteScalarExample2
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select count(*) from Employees";
cmd.Connection = cn;
/* call methods */
cn.Open();
object obj = cmd.ExecuteScalar();
cn.Close();
string n = Convert.ToString(obj);
Console.WriteLine("Emps Count: " + n);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• ADO.NET sends request to the database server and gets only one record at-a-time. It
stores the current record in an object of “SqlDataReader” class.
• The connection should be in “Open” status, while retrieving data from database.
• It supports “sequential retrieval of records”. We can’t retrieve a record based on its index.
We can’t retrieve records randomly or in reverse order.
2. System.Data.SqlClient.SqlCommand
3. System.Data.SqlClient.SqlDataReader
• This class’s object is used to store a single record, while retrieving data from database in
“ADO.NET Connection Oriented Model”.
• It occupies the memory, which is enough for storing single database record.
1 [column index] object Retrieves the column value in the current record, based
on the column index.
2 [“column name”] object Retrieves the column value in the current record, based
on the column name.
Syntax: referencevariable.FieldCount
Syntax: referencevariable.HasRows
No constructors
Syntax: referencevariable.Read()
Syntax: referencevariable.GetValue(int
columnindex)
o using System.Data.SqlClient;
o SqlConnection cn;
o SqlCommand cmd;
o SqlDataReader dr;
• Create objects:
o cn = new SqlConnection();
• Call properties
o cmd.Connection = cn;
• Call methods
o cn.Open();
o dr = cmd.ExecuteReader( );
o dr.Read();
o dr[“column name”];
o cn.Close();
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace COMSingleRecordExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
object obj1, obj2, obj3;
obj1 = dr["EmpID"];
obj2 = dr["EmpName"];
obj3 = dr["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine("EmpID: " + eid);
Console.WriteLine("EmpName: " + ename);
Console.WriteLine("Salary: " + sal);
}
cn.Close();
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace COMMultipleRecordsExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
object obj1, obj2, obj3;
obj1 = dr["EmpID"];
obj2 = dr["EmpName"];
obj3 = dr["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine("EmpID: " + eid + "\nEmpName: " + ename +
"\nSalary: " + sal + "\n");
}
cn.Close();
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
System.Data.SqlClient.SqlParameter
• The “SqlParameter” is a pre-defined class in a namespace called “System.Data.SqlClient”.
• This class’s object represents a parameter (name and value), that is to be passed to DBMS
for execution of command.
Syntax: referencevariable.ParameterName
= “parameter name here”
Syntax: referencevariable.Value
Syntax: referencevariable.DbType =
DbType.Optionhere;
Syntax: referencevariable.Direction =
ParameterDirection.Optionhere;
o using System.Data.SqlClient;
o SqlParameter p;
• Create object:
o p = new SqlParameter();
• Call properties
o cmd.Parameters.Add(p);
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace COMSqlParameterExample
{
class Program
{
static void Main()
{
//get empid from keyboard
Console.Write("Emp ID: ");
int n = Convert.ToInt32(Console.ReadLine());
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees where
empid=@EmpID";
cmd.Connection = cn;
p1.ParameterName = "@EmpID";
p1.Value = n;
cmd.Parameters.Add(p1);
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
object obj1, obj2;
obj1 = dr["EmpName"];
obj2 = dr["Salary"];
string ename;
decimal sal;
ename = Convert.ToString(obj1);
sal = Convert.ToDecimal(obj2);
Output
Note: If any database connection problem, it shows exception (run time error).
o Resultset = The data (rows and columns) that is returned from SQL server, after
execution of a SELECT statement.
o DataSet = The data that is stored in .net application memory (RAM) in the form of
objects.
• After loading all records at-once, the connection can be closed. That’s why it is called
“ADO.NET Disconnected Model”.
Properties
▪ SqlCommand SelectCommand: It represents the object of SqlCommand class, based on
which the data is to be retrieved from database.
Methods
▪ Fill(DataSet dataset): It executes the SELECT statement, converts the resultset into
dataset and also stores the data in dataset.
▪ Update(DataSet dataset): It updates the changes made in the dataset to the database.
Constructors
▪ SqlDataAdapter(): It initializes nothing.
DataSet - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
/* Expected data:
Categories:
CategoryID CategoryName
1 ab
2 cd
Products:
ProductID ProductName Cost
101 prod1 400
102 prd2 500
103 prd3 600
*/
using System;
using System.Data;
namespace DataSetExample
{
class Program
{
static void Main()
{
//creating dataset
DataSet ds = new DataSet();
//creating 2 tables
DataTable dt1 = new DataTable() { TableName = "Categories" };
DataTable dt2 = new DataTable() { TableName = "Products" };
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace DisconnectedModelExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “departmentsandemployeesdatabase” database
already.
use departmentsandemployeesdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace MultipleTablesExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt1, dt2;
DataRow drow;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=departmentsandemployeesdatabase";
cmd.CommandText = "select * from Departments select * from
Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
/* departments */
Console.WriteLine("Departments:");
dt1 = ds.Tables[0];
int n = 50;
for (int i = 0; i < dt1.Rows.Count; i++)
{
drow = dt1.Rows[i];
obj3 = drow["Loc"];
int dno;
string dname;
string loc;
dno = Convert.ToInt32(obj1);
dname = Convert.ToString(obj2);
loc = Convert.ToString(obj3);
/* employees */
Console.WriteLine("\nEmployees:");
dt2 = ds.Tables[1];
n += 100;
for (int i = 0; i < dt2.Rows.Count; i++)
{
drow = dt2.Rows[i];
int eid;
string ename;
decimal sal;
int dno;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
dno = Convert.ToInt32(obj4);
Console.WriteLine(eid + ", " + ename + ", " + sal + ", " + dno);
}
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “departmentsandemployeesdatabase” database
already.
use departmentsandemployeesdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace JoinsExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=departmentsandemployeesdatabase";
cmd.CommandText = "select * from employees inner join
departments on employees.deptno=departments.deptno";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
decimal sal;
int dno;
string dname;
string loc;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
dno = Convert.ToInt32(obj4);
dname = Convert.ToString(obj5);
loc = Convert.ToString(obj6);
Console.WriteLine(eid + ", " + ename + ", " + sal + ", " + dno + ", " + loc);
}
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
Program.cs
using System;
using System.Data.SqlClient;
namespace InsertionExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "insert into Employees values(10, 'qwerty',
4500)";
cmd.Connection = cn;
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace UpdationExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "update Employees set EmpName='asdf',
Salary=8900 where EmpID=1";
cmd.Connection = cn;
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace DeletionExample
{
class Program
{
static void Main(string[] args)
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "delete from Employees where EmpID=3";
cmd.Connection = cn;
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace InsertionSqlParameterExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "insert into Employees values(@empid,
@empname, @salary)";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace UpdationSqlParameterExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
//create reference variables
SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "update Employees set empname=@empname,
salary=@salary where empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Console.WriteLine(n + " rows updated");
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace DeletionSqlParameterExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
Output
Note: If any database connection problem, it shows exception (run time error).
• Stored procedures will be compiled once and executes every time when we call it. This is
called “pre-compilation”.
• Stored procedures support to separate work between database developer and .net
developer in real time.
• Stored procedures are best for performing multiple and complex database operations with
a single database call.
Creating Database
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace InsertionWithSPExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "InsertEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
use company
go
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace UpdationWithSPExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "UpdateEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace DeletionWithSPExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
SqlConnection cn;
SqlCommand cmd;
SqlParameter p1;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "DeleteEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p1.Value = empId;
cmd.Parameters.Add(p1);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
ADO.NET - Transactions
ADO.NET Transactions
• A transaction is a “collection of database operations such as insertion, deletion and
updation”.
• ADO.NET transactions are used to roll back the previously executed database operations,
when any database operation is failed in a transaction.
• Example: Funds transfer from one bank account to another bank account.
▪ This method creates and starts a new ado.net transaction. It creates and returns an
object for “SqlTransaction” class.
2. transactionReferenceVariable.Commit()
▪ This method will save (fix) the database operations that are executed during the
current transaction.
3. transactionReferenceVariable.RollBack()
▪ This method will rollback (cancel) all the previously executed database operations
during the current transaction.
Creating Database
• Note: Ignore this step, if you have created “transactionsdatabase” database already.
use transactionsdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
namespace TransactionsExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlTransaction transaction;
SqlCommand cmd1, cmd2;
//create objects
cn = new SqlConnection();
cmd1 = new SqlCommand();
cmd2 = new SqlCommand();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=transactionsdatabase";
cmd1.CommandText = "update AccountsTable set Balance=Balance-
1000 where AccountNo=101";
cmd2.CommandText = "update AccountsTable set
Balance=Balance+1000 were AccountNo=102";
cmd1.Connection = cn;
cmd2.Connection = cn;
//call methods
cn.Open();
transaction = cn.BeginTransaction();
cmd1.Transaction = transaction;
cmd2.Transaction = transaction;
try
{
cmd1.ExecuteNonQuery();
Console.WriteLine("First operation done.");
cmd2.ExecuteNonQuery();
Console.WriteLine("Second operation done.");
transaction.Commit(); //save data
Console.WriteLine("Transaction Complete");
}
catch (Exception)
{
transaction.Rollback(); //first operation will be rollback
Console.WriteLine("Rollback done!");
}
cn.Close();
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• The System.Data.OleDb namespace is used to connect and interact with various databases
like Oracle, Excel, Access etc.
1 System.Data.SqlClient.SqlConnection System.Data.OleDb.OleDbConnection
2 System.Data.SqlClient.SqlCommand System.Data.OleDb.OleDbCommand
3 System.Data.SqlClient.SqlDataReader System.Data.OleDb.OleDbDataReader
4 System.Data.SqlClient.SqlParameter System.Data.OleDb.OleDbParameter
5 System.Data.SqlClient.SqlDataAdapter System.Data.OleDb.OleDbDataAdapter
6 System.Data.SqlClient.SqlCommandBuilder System.Data.OleDb.OleDbCommandBuilder
7 System.Data.SqlClient.SqlTransaction System.Data.OleDb.OleDbTransaction
8 System.Data.DataSet System.Data.DataSet
9 System.Data.DataTable System.Data.DataTable
10 System.Data.DataRow System.Data.DataRow
11 System.Data.DataColumn System.Data.DataColumn
(or)
• Click on “Yes”.
• Click on “Next”.
• Click on “Next”.
• Click on “Next”.
• Click on “Next”.
• Click on “Install”.
• Click on “Finish”.
connect system/123;
commit;
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.OleDb;
using System.Data;
namespace OracleExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new OleDbConnection();
/* call properties */
cn.ConnectionString = "user id=system; password=123;
provider=msdaora.1";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine(eid + ", " + ename + ", " + sal);
}
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Yes”.
• Click on “Next”.
• Click on “Install”.
• Click on OK.
• Click on OK.
• Click on “Create”.
• Click on OK.
• Click on “Yes”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.OleDb;
using System.Data;
namespace MSAccessExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new OleDbConnection();
/* call properties */
cn.ConnectionString = @"provider=Microsoft.Ace.Oledb.12.0; data
source=C:\CSharp\Database1.accdb";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine(eid + ", " + ename + ", " + sal);
}
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Yes”.
• Click on “Next”.
• Click on “Install”.
• Click on OK.
• Click on “Save”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.OleDb;
using System.Data;
namespace MSExcelExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new OleDbConnection();
/* call properties */
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book1.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=1' ";
cmd.CommandText = "select * from [Sheet1$]";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine(eid + ", " + ename + ", " + sal);
}
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
connect system/123;
commit;
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//Copy data from "SqlServer" to "Oracle"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
namespace SqlServerToOracleExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.ReadKey();
}
//create objects
cn = new OleDbConnection();
cmd = new OleDbCommand();
//calling properties
cn.ConnectionString = "user id=system; password=123;
provider=msdaora.1";
cmd.CommandText = string.Format("insert into Employees2
values({0}, '{1}', {2})", eid, ename, sal);
cmd.Connection = cn;
//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Additionally, we have to install “Access Database Engine”, based on the steps explained in
the previous examples.
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Save”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//Copy data from "SqlServer" to "Excel"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
namespace SqlServerToExcelExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.ReadKey();
}
//create objects
cn = new OleDbConnection();
cmd = new OleDbCommand();
//calling properties
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book2.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=3' ";
cmd.CommandText = string.Format("insert into [Sheet1$] values('{0}',
'{1}', '{2}')", eid, ename, sal);
cmd.Connection = cn;
//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
connect system/123;
commit;
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
• Click on OK.
Program.cs
//Copy data from "Oracle" to "SqlServer"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
namespace OracleToSqlServerExample
{
class Program
{
static void Main()
{
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
InsertIntoSqlServer(eid, ename, sal);
}
Console.WriteLine(dt.Rows.Count + " records copied");
Console.ReadKey();
}
cn = new SqlConnection();
cmd = new SqlCommand();
Output
Note: If any database connection problem, it shows exception (run time error).
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Additionally, we have to install “Access Database Engine”, based on the steps explained in
the previous examples.
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Save”.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//Copy data from "Excel" to "SqlServer"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;
namespace ExcelToSqlServerExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book1.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=1' ";
cmd.CommandText = "select * from [Sheet1$]";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = string.Format("insert into Employees2
values({0}, '{1}', {2})", eid, ename, sal);
cmd.Connection = cn;
//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
Program.cs
//Copy data from "SqlServer" to "File"
using System;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
using System.IO;
namespace SqlServerToFileExample
{
class Program
{
static void Main()
{
//create directory if not exists
if (Directory.Exists(@"C:\CSharp") == false)
{
Directory.CreateDirectory(@"C:\CSharp");
}
//create objects
cn = new SqlConnection();
//create objects
fs = new FileStream(@"C:\CSharp\Employees.txt", FileMode.Create,
FileAccess.Write);
sw = new StreamWriter(fs);
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees2";
cmd.Connection = cn;
adp.SelectCommand = cmd;
//call methods
adp.Fill(ds);
//read data
dt = ds.Tables[0];
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
//Copy data from "File" to "SqlServer"
using System;
using System.Data.SqlClient;
using System.IO;
namespace FileToSqlServerExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
FileInfo finfo;
FileStream fs;
StreamReader sr;
SqlParameter p1, p2, p3;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
finfo = new FileInfo(@"C:\CSharp\Employees.txt");
Console.ReadKey();
return;
}
//create objects
fs = new FileStream(@"C:\CSharp\Employees.txt", FileMode.Open,
FileAccess.Read);
sr = new StreamReader(fs);
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "insert into Employees2 values(@empid,
@empname, @salary)";
cmd.Connection = cn;
//call methods
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
p1.ParameterName = "@empid";
p1.Value = eid;
p2.ParameterName = "@empname";
p2.Value = ename;
p3.ParameterName = "@salary";
p3.Value = sal;
if (sr.EndOfStream == true)
break;
}
Output
Note: If any database connection problem, it shows exception (run time error).
System.Data.SqlClient.SqlCommandBuilder
• The “SqlCommandBuilder” is a pre-defined class in a namespace called
“System.Data.SqlClient”.
• This class’s object generates a set of INSERT, UPDATE, DELETE sql statements
automatically, based on the SELECT statement, based on which we can perform DML
operations using DataSet.
Syntax: referencevariable.DataAdapter =
ReferenceVariableSqlDataAdapter ;
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataSetInsertionExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
cmb = new SqlCommandBuilder();
ds = new DataSet();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
cmb.DataAdapter = adp;
//call methods
adp.Fill(ds);
dt = ds.Tables[0];
Console.WriteLine("Inserted");
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataSetUpdationExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
cmb = new SqlCommandBuilder();
ds = new DataSet();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
cmb.DataAdapter = adp;
//call methods
adp.Fill(ds);
dt = ds.Tables[0];
//update
drow["empname"] = empName;
drow["salary"] = sal;
Console.WriteLine("Updated");
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace DataSetDeletionExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
cmb.DataAdapter = adp;
//call methods
adp.Fill(ds);
dt = ds.Tables[0];
Console.WriteLine("Deleted");
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
N-Tier Architecture
3. Presentation Layer: Contains code for displaying the UI and event handling.
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Solution
• Open Visual Studio 2019.
• Click on OK.
• Right click on the solution (CompanySolution) and click on “Add” – “New Project”.
• Click on OK.
• Right click on the solution (CompanySolution) and click on “Add” – “New Project”.
• Click on OK.
• Right click on the solution (CompanySolution) and click on “Add” – “New Project”.
• Click on OK.
Adding references:
• Open Solution Explorer.
CompanyDataAccess\Class1.cs
//Data Access Logic
using System;
using System.Data.SqlClient;
namespace CompanyDataAccess
{
public class EmployeesDataAccess
{
public int InsertEmployee(int EmpID, string EmpName, decimal Salary)
{
SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
return n;
}
}
}
CompanyBusinessLogic\Class1.cs
//Business Logic
using System;
using CompanyDataAccess;
namespace CompanyBusinessLogic
{
public class EmployeesBusinessLogic
{
private int _empid;
private string _empname;
private decimal _salary;
set
{
if (value.Length <= 40)
{
_empname = value;
}
}
get
{
return _empname;
}
}
else
{
return "Error in insertion";
}
}
}
}
CompanyPresentationLogic\Program.cs
//Presentation Logic
using System;
using CompanyBusinessLogic;
namespace CompanyPresentationLogic
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
Output
Note: If any database connection problem, it shows exception (run time error).
LINQ to SQL
• “LINQ to SQL” is a framework, which is used to connect and interact with SQL Server
database.
• “LINQ to SQL” internally uses “ADO.NET” and “SQL”. That means “LINQ to SQL queries”
will be internally converted into “SQL queries” and executed based on ADO.NET classes.
• “LINQ to SQL” works based on mapping classes. A mapping class represents the structure
of the table. A table become as “mapping class” and all the columns become as “Properties”
in the “mapping class”.
-- or –
The ToList() method opens the connection, convert the LINQ query into SQL query, execute the
query, convert the resultset into collection and close the database connection.
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
• Right click on the project (LinqToSqlExample) and click on “Add” – “New Item” – “Data” –
“LINQ to SQL Classes”.
• Click on “Add”.
• Click on OK.
• Drag and drop “Employees” table from Server Explorer into “Object Relational Designer” of
“DataClasses1.dbml” file.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace LinqToSqlExample
{
class Program
{
static void Main()
{
//create reference variables
DataClasses1DataContext db;
//create objects
db = new DataClasses1DataContext();
//LINQ query
List<Employee> emps = db.Employees.ToList();
Output
Note: If any database connection problem, it shows exception (run time error).
• “ADO.NET EF” is a database technology, which is used to connect and interact with
databases.
• “Entity Framework” automatically converts data into collection; so that it will be easy to
read and manipulate the data.
• “Entity Framework” is better compatible with other frameworks such as “WPF” and
“ASP.NET MVC” etc.
o We will read data from collection; not from the dataset / data reader.
Install-package EntityFramework
class modelclassname
{
public datatype property1 { get; set; }
public datatype property2 { get; set; }
…
}
Childclassname referencevariable ;
referencevariable = new Childclassname();
Referencevariable.collectionname
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Install-package EntityFramework
<connectionStrings>
<add name="CompanyDbContext"
connectionString="data source=localhost; integrated
Program.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
namespace EntityFrameworkExample
{
public class Employee
{
[Key]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
class Program
{
static void Main()
{
//create reference variable
CompanyDbContext db;
//create object
db = new CompanyDbContext();
//LINQ query
//List<Employee> emps = db.Employees.ToList();
//List<Employee> emps = db.Employees.Where(temp => temp.Salary
>= 2000).ToList();
List<Employee> emps = db.Employees.OrderBy(temp =>
temp.Salary).ToList();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Install-package EntityFramework
<connectionStrings>
<add name="CompanyDbContext" connectionString="data
source=localhost; integrated security=yes; initial
catalog=company" providerName="System.Data.SqlClient" />
</connectionStrings>
Program.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
namespace FirstOrDefaultExample
{
public class Employee
{
[Key]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
{
public DbSet<Employee> Employees { get; set; }
}
class Program
{
static void Main()
{
//create reference variables
CompanyDbContext db;
//create objects
db = new CompanyDbContext();
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Install-package EntityFramework
<connectionStrings>
<add name="CompanyDbContext" connectionString="data
source=localhost; integrated security=yes; initial
catalog=company" providerName="System.Data.SqlClient" />
</connectionStrings>
Program.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
namespace EfInsertionExample
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
//insertion
CompanyDbContext db = new CompanyDbContext();
Employee emp = new Employee();
emp.EmpID = empId;
emp.EmpName = empName;
emp.Salary = sal;
db.Employees.Add(emp);
db.SaveChanges();
Console.WriteLine("Inserted");
Console.ReadKey();
}
}
}
Output
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Install-package EntityFramework
<connectionStrings>
Program.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
namespace EfUpdationExample
{
public class Employee
{
[Key]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
//updation
CompanyDbContext db = new CompanyDbContext();
Console.WriteLine("Updated");
Console.ReadKey();
}
}
}
Output
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Install-package EntityFramework
<connectionStrings>
Program.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
namespace EfDeletionExample
{
public class Employee
{
[Key]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
//deletion
CompanyDbContext db = new CompanyDbContext();
Employee emp = db.Employees.Where(temp => temp.EmpID ==
empId).FirstOrDefault();
db.Employees.Remove(emp);
db.SaveChanges();
Console.WriteLine("Deleted");
Console.ReadKey();
}
}
}
Output
• A windows form (win form) is a GUI container and a window that contains UI (user
interface), using which the user can interact with the system. Ex: Login form
• Windows forms applications support “local GUI” that runs on windows operating system
locally.
Ex: WindowsFormsApplication1.exe
o The exe file contains compiled source code (in MSIL (Microsoft Intermediate
Language)) of windows forms application.
• .NET provides the following assemblies (dll files) to develop windows forms applications:
1. System.Windows.Forms.dll
2. System.Drawing.dll
System.Windows.Forms.dll
▪ “System.Windows.Forms.dll” assembly
• “System.Windows.Forms” namespace
o “Form” class
o “Label” class
o “Button” class
o “TextBox” class
etc.
• Every form contains basic look and feel such as title bar, minimize box, maximize box, close
box etc.
Syntax:
• “public Classname()”
o It is the constructor that executes as soon as an object for the form class is created
at run time.
• InitializeComponent()
o The InitializeCompoent() method initializes the basic look and feel of the form. The
definition of InitializeCompoent() method is generated in “Form1.Designer.cs” file.
• Program.cs
o In Program.cs, at main method, the following statement will create an object for
the form class.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
Output
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormConstructorExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
MessageBox.Show("Message from Form1 Constructor");
}
}
}
Running the Project
Output
Click on OK
1 Text Represents title of the form that appears in the titlebar of the form.
7 TopMost Determines whether the form should appear always on the top of
other windows.
Syntax: this.WindowState =
System.Windows.Forms.FormWindowState.Maximized;
Syntax: this.FormBorderStyle =
System.Windows.Forms.FormBorderStyle.FixedSingle;
Syntax: this.BackgroundImage =
System.Drawing.Image.FromFile("image file path");
Options: pixels.
Options: pixels
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace TextExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Text = "Hello";
}
}
}
Output
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormShowIconExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.ShowIcon = false;
}
}
}
Output
“System.Windows.Forms.Form. ShowInTaskBar”
property -Example
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormShowInTaskBarExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.ShowInTaskbar = false;
}
}
}
Output
Note: You can notice that the form icon doesn’t appear in the windows taskbar.
“System.Windows.Forms.Form. MinimizeBox”
property - Example
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormMinimizeBoxExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.MinimizeBox = false;
}
}
}
Output
“System.Windows.Forms.Form. MaximizeBox”
property - Example
Creating Project
• Click on OK.
using System;
using System.Windows.Forms;
namespace FormMaximizeBoxExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.MaximizeBox = false;
}
}
}
Output
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormControlBoxExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.ControlBox = false;
}
}
}
• Click on OK.
using System;
using System.Windows.Forms;
namespace FormTopMostExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.TopMost = true;
}
}
}
Output
“System.Windows.Forms.Form. WindowState”
property –Example
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormWindowStateExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
}
}
}
Output
“System.Windows.Forms.Form. FormBorderStyle”
property – Example
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormBorderStyleExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.MinimizeBox = false;
this.MaximizeBox = false;
this.FormBorderStyle = FormBorderStyle.FixedSingle;
}
}
}
Output
Form1.cs
using System;
using System.Windows.Forms;
namespace FormCursorExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Cursor = Cursors.Hand;
}
}
}
Output
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FormBackColorExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.BackColor = Color.Green;
}
}
}
Output
“System.Windows.Forms.Form. BackgroundImage”
property – Example
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FormBackgroundImageExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string s = @"C:\CSharp\img1.jpg";
this.BackgroundImage = Image.FromFile(s);
this.BackgroundImageLayout = ImageLayout.Stretch;
}
}
}
Output
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FormSizeExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Size = new Size(600, 350);
}
}
}
Output
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace FormLocationExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Location = new Point(300, 200);
this.StartPosition = FormStartPosition.Manual;
}
}
}
Output
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FormIconExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Icon = new Icon(@"C:\CSharp\Sample.ico");
}
}
}
Output
• Events are used to make the form to display output based on the input.
1 Load Executes after loading the form object into memory at run time.
5 MouseClick Same as “Click” event; but we can identify the mouse pointer position
also in this event.
6 MouseMove Executes when the user moves the mouse pointer from one place to
another place within the same form.
6 KeyPress Executes when the user presses any key on the keyboard.
7 FormClosing Executes when the user clicks on the “close” button of the form.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormLoadExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += Form1_Load;
}
Output
Form1.cs
using System;
using System.Windows.Forms;
namespace FormShownExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Shown += Form1_Shown;
}
private void Form1_Shown(object sender, EventArgs e)
{
MessageBox.Show("Message from Form1 Shown event");
}
}
}
First the form appears and then the message box appears.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormClickExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Size = new System.Drawing.Size(600, 300);
this.Click += Form1_Click;
}
Output
When the user clicks on the form, it shows the “You have clicked the form at …” message, in the
form title bar.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormDoubleClickExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Size = new System.Drawing.Size(600, 200);
this.DoubleClick += Form1_DoubleClick;
}
Output
When the user double clicks on the form, it shows “You have double clicked the form at …”
message, in the form title bar.
“System.Windows.Forms.Form.MouseClick” event -
Example
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormMouseClickExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Size = new System.Drawing.Size(600, 200);
this.MouseClick += Form1_MouseClick;
}
Output
When the user clicks on the form, it shows the X and Y co-ordinates of the mouse pointer.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormMouseMoveExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.MouseMove += Form1_MouseMove;
}
{
int x = e.X;
int y = e.Y;
this.Text = x + ", " + y;
}
}
}
Output
When the user moves the mouse pointer across the form, it shows the X and Y co-ordinates of the
mouse pointer.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormKeyPressExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.KeyPress += Form1_KeyPress;
}
Output
When the user presses any character in the keyboard, it shows the same in the form title bar.
using System;
using System.Windows.Forms;
namespace FormClosingExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
}
Output
When you click on “Close (X)” button of the form, it shows the following message:
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormClosingExample2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
}
if (r == DialogResult.Yes)
e.Cancel = false;
else
e.Cancel = true;
}
}
}
Output
When you click on “Close (X)” button of the form, it shows the confirmation message as follows:
Syntax: this.Hide( );
Syntax: this.Show( );
Syntax: this.Close( );
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormHideExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Click += Form1_Click;
}
Output
When you click on the form, the form will be automatically hidden.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormShowExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Click += Form1_Click;
}
Output
When you click on the form, the form will be automatically hidden, it automatically appears again in
3 seconds.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace FormCloseExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Click += Form1_Click;
}
Output
• In windows applications, we use “windows forms controls” to take input from the user and
provide output to the user.
• Windows operating system provides a set of controls such as Label, Button, TextBox etc.
• .NET provides a set of pre-defined classes to create controls in a .net windows forms
application. Each class represent a control. All those classes are called as “Control Classes”.
All the control classes are present in “System.Windows.Forms” namespace.
• “System.Windows.Forms.dll” assembly:
o “System.Windows.Forms” namespace:
1. “Label” class
2. “Button” class
3. “TextBox” class
4. “NumericUpDown” class
5. “DateTimePicker” class
6. “MonthCalendar” class
7. “MaskedTextBox” class
8. “ErrorProvider” class
9. “CheckBox” class
“System.Windows.Forms.Label” class
The “System.Windows.Forms.Label” class
• The “Label” class / control is used to display a message in the windows form.
o using System.Windows.Forms;
o Label referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
4 AutoSize True: The control will take the essential size automatically.
False: The control will not take the size automatically; we need to set the
size manually.
Options: pixels
2 MouseEnter Executes when the user moves the mouse pointer from outside to
inside the control.
3 MouseLeave Executes when the user moves the mouse pointer from inside to
outside the control.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace LabelExample
{
public partial class Form1 : Form
{
//create a reference variable
Label lbl;
public Form1()
{
InitializeComponent();
//create an object
lbl = new Label();
//set properties
lbl.Text = "Hello";
lbl.Font = new System.Drawing.Font("Tahoma", 30);
lbl.BackColor = System.Drawing.Color.DarkRed;
lbl.ForeColor = System.Drawing.Color.Yellow;
lbl.Size = new System.Drawing.Size(140, 50);
lbl.Location = new System.Drawing.Point(84, 76);
lbl.Cursor = Cursors.Hand;
//add event
lbl.Click += Lbl_Click;
lbl.MouseEnter += Lbl_MouseEnter;
lbl.MouseLeave += Lbl_MouseLeave;
Output
When you place the mouse pointer on the label, background color and foreground colors will
change.
• The “Button” class / control is used to display an option on the windows form. Ex: OK,
Cancel etc.
o using System.Windows.Forms;
o Button referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
4 AutoSize True: The control will take the essential size automatically.
False: The control will not take the size automatically; we need to set the
size manually.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by
the user.
Syntax: referencevariable.ImageAlign =
System.Drawing.ContentAlignment.TopLeft;
Syntax: referencevariable.TextAlign =
System.Drawing.ContentAlignment.TopLeft;
2 MouseEnter Executes when the user moves the mouse pointer from outside to
inside the control.
3 MouseLeave Executes when the user moves the mouse pointer from inside to
outside the control.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace ButtonExample
{
public partial class Form1 : Form
{
//create a reference variable
Button button1;
public Form1()
{
InitializeComponent();
//form properties
this.Size = new System.Drawing.Size(500, 300);
this.Text = "Button Example";
//create an object
button1 = new Button();
button1.MouseLeave += Button1_MouseLeave;
//add button to the form
this.Controls.Add(button1);
}
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Clicked";
}
private void Button1_MouseEnter(object sender, EventArgs e)
{
button1.BackColor = System.Drawing.Color.LightGreen;
}
private void Button1_MouseLeave(object sender, EventArgs e)
{
button1.BackColor = System.Drawing.SystemColors.Control;
}
}
}
Output
When you place the mouse pointer on the button, background color will change.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace ButtonWithImageExample
{
public partial class Form1 : Form
{
//create a reference variable
Button button1;
public Form1()
{
InitializeComponent();
//create an object
button1 = new Button();
//set properties
button1.Text = "Exit";
button1.Font = new System.Drawing.Font("Tahoma", 30);
button1.Size = new System.Drawing.Size(140, 70);
button1.Location = new System.Drawing.Point(100, 100);
button1.Cursor = Cursors.Hand;
button1.Image =
System.Drawing.Image.FromFile(@"C:\csharp\exit.png");
button1.ImageAlign =
System.Drawing.ContentAlignment.MiddleLeft;
button1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
Output
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ButtonWithLabelExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/*form properties*/
this.Size = new Size(1000, 400);
/* creating label1 */
label1 = new Label();
label1.Text = "Hello";
label1.AutoSize = true;
label1.Font = new Font("Tahoma", 30);
label1.BackColor = Color.DarkRed;
label1.ForeColor = Color.Yellow;
label1.Location = new Point(84, 76);
this.Controls.Add(label1);
/* creating button1 */
button1 = new Button();
button1.Text = "Set Text";
button1.Font = new Font("Tahoma", 18);
button1.Size = new Size(150, 50);
button1.Location = new Point(80, 220);
button1.Click += button1_Click;
this.Controls.Add(button1);
/* creating button2 */
button2 = new Button();
button2.Text = "Set Font";
button2.Font = new Font("Tahoma", 18);
button2.Size = new Size(150, 50);
button2.Location = new Point(280, 220);
button2.Click += button2_Click;
this.Controls.Add(button2);
/* creating button3 */
button3 = new Button();
button3.Text = "Set Colors";
button3.Font = new Font("Tahoma", 18);
button3.Size = new Size(150, 50);
button3.Location = new Point(480, 220);
button3.Click += button3_Click;
this.Controls.Add(button3);
/* creating button4 */
button4 = new Button();
button4.Text = "Set Location";
button4.Font = new Font("Tahoma", 18);
button4.Size = new Size(170, 50);
button4.Location = new Point(680, 220);
button4.Click += button4_Click;
this.Controls.Add(button4);
}
Output
• The “TextBox” class / control is used to accept a string from the user. Ex: Username,
password etc.
o using System.Windows.Forms;
o TextBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
Syntax: referencevariable.Cursor =
System.Windows.Forms.Cursors.Hand;
Syntax: referencevariable.BackColor =
System.Drawing.Color.Green;
Syntax: referencevariable.ForeColor =
System.Drawing.Color.Green;
Syntax: referencevariable.TextAlign =
System.Windows.Forms.HorizontalAlignment.Left;
Syntax: referencevariable.AutoCompleteSource =
System.Windows.Forms.AutoCompleteSource.FileSyste
m;
Syntax: referencevariable.AutoCompleteMode =
System.Windows.Forms.AutoCompleteMode.Suggest;
Syntax: referencevariable.AutoCompleteCustomSource
= new
System.Windows.Forms.AutoCompleteStringCollection(
) { “value1”, “value2”, …. };
5 KeyPress Executes when the user presses any key on the keyboard (before
accepting the character into the textbox).
Syntax: referencevariable.Clear();
Syntax: referencevariable.SelectAll();
Syntax: referencevariable.Cut();
Syntax: referencevariable.Copy();
Syntax: referencevariable.Paste()
Syntax: referencevariable.Undo()
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TextBoxExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
TextBox textbox1, textbox2;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "TextBox Example";
this.Size = new Size(500, 250);
this.Font = new Font("Tahoma", 20);
/* creating label1 */
label1 = new Label();
label1.Text = "Source text:";
label1.AutoSize = true;
label1.Location = new Point(84, 76);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Destnation text:";
label2.AutoSize = true;
label2.Location = new Point(84, 220);
this.Controls.Add(label2);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(300, 73);
textbox1.MaxLength = 30;
textbox1.TextChanged += Textbox1_TextChanged;
this.Controls.Add(textbox1);
/* creating textbox2 */
Output
When you type something in the first textbox, it automatically copied into the second textbox.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace AutoCompleteExample
{
public partial class Form1 : Form
{
Label label1, label2;
TextBox textbox1;
public Form1()
{
InitializeComponent();
/* creating label1 */
label1 = new Label();
label1.Text = "Type any file path: ";
label1.AutoSize = true;
label1.Location = new Point(84, 76);
this.Controls.Add(label1);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(400, 50);
textbox1.Location = new Point(280, 73);
textbox1.AutoCompleteSource = AutoCompleteSource.FileSystem;
textbox1.AutoCompleteMode = AutoCompleteMode.Suggest;
this.Controls.Add(textbox1);
/* creating label2 */
label2 = new Label();
label2.Text = @"Ex: C:\Windows\system32\calc.exe";
label2.AutoSize = true;
label2.Location = new Point(280, 120);
this.Controls.Add(label2);
}
}
}
Output
When you start typing a file path in the textbox, it automatically shows all folders and files.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace AutoCompleteExample2
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
TextBox textbox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "TextBox with AutoComplete Example - with Custom
Source";
this.Size = new Size(1000, 300);
this.Font = new Font("Tahoma", 14);
/* creating label1 */
label1 = new Label();
Output
When you start typing a character in the textbox, it automatically shows the matching names.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace KeyPressEventExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1;
TextBox textbox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "TextBox with KeyPress Example";
this.Size = new Size(700, 250);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Name (Alphabets only): ";
label1.AutoSize = true;
label1.Location = new Point(84, 76);
this.Controls.Add(label1);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 50);
Output
If you type numbers and special symbols, it will not be accepted in the textbox.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace KeyPressEventExample2
{
public partial class Form1 : Form
{
//create reference variables
Label label1;
TextBox textbox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "TextBox with KeyPress Example 2";
this.Size = new Size(550, 250);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Name (Numbers only): ";
label1.AutoSize = true;
label1.Location = new Point(84, 76);
this.Controls.Add(label1);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 50);
textbox1.Location = new Point(360, 73);
textbox1.KeyPress += textBox1_KeyPress;
this.Controls.Add(textbox1);
}
else
e.Handled = true;
}
}
}
Output
If you type alphabets and special symbols, it will not be accepted in the textbox.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace EnterLeaveExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2, label3, label4;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "TextBox - with Enter and Leave - Example";
this.Size = new Size(800, 250);
this.Font = new Font("Tahoma", 20);
/* creating label1 */
label1 = new Label();
label1.Text = "Mobile:";
label1.AutoSize = true;
label1.Location = new Point(84, 76);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Email:";
label2.AutoSize = true;
label2.Location = new Point(84, 150);
this.Controls.Add(label2);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(200, 73);
textbox1.Enter += Textbox1_Enter;
textbox1.Leave += Textbox1_Leave;
this.Controls.Add(textbox1);
/* creating textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(200, 150);
textbox2.Enter += Textbox2_Enter;
textbox2.Leave += Textbox2_Leave;
this.Controls.Add(textbox2);
/* creating label3 */
label3 = new Label();
label3.Text = "Ex: 9898989898";
label3.AutoSize = true;
label3.Location = new Point(520, 76);
label3.Visible = false;
this.Controls.Add(label3);
/* creating label4 */
label4 = new Label();
label4.Text = "Ex: [email protected]";
label4.AutoSize = true;
label4.Location = new Point(520, 150);
label4.Visible = false;
this.Controls.Add(label4);
}
Output
When the cursor is inside mobile textbox, it shows example for mobile number.
When the cursor is inside email textbox, it shows example for email.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace TabIndexExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2, label3;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "TabIndex Example";
this.Size = new Size(430, 170);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Name: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Landline: ";
label2.AutoSize = true;
label2.Location = new Point(50, 150);
this.Controls.Add(label2);
/* creating label3 */
label3 = new Label();
label3.Text = "Mobile: ";
label3.AutoSize = true;
label3.Location = new Point(450, 150);
this.Controls.Add(label3);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 30);
textbox1.Location = new Point(200, 50);
textbox1.TabIndex = 1;
this.Controls.Add(textbox1);
/* creating textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(200, 30);
textbox2.Location = new Point(200, 150);
textbox2.TabIndex = 3;
this.Controls.Add(textbox2);
/* creating textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(200, 30);
textbox3.Location = new Point(600, 150);
textbox3.TabIndex = 2;
this.Controls.Add(textbox3);
}
}
}
Output
The cursor sequence will be: Name, Mobile and then Landline.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace AddSubtractMultiplyDivideExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1, button2, button3, button4;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "Add, Subtract, Multiply and Divide";
this.Size = new Size(390, 220);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Enter First number: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Enter Second number: ";
label2.AutoSize = true;
label2.Location = new Point(50, 150);
this.Controls.Add(label2);
/* creating label3 */
label3 = new Label();
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 30);
textbox1.Location = new Point(320, 50);
this.Controls.Add(textbox1);
/* creating textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(200, 30);
textbox2.Location = new Point(320, 150);
this.Controls.Add(textbox2);
/* creating textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(200, 30);
textbox3.Location = new Point(320, 300);
textbox3.ReadOnly = true;
this.Controls.Add(textbox3);
/* creating button1 */
button1 = new Button();
button1.Size = new Size(150, 40);
button1.Text = "Add";
button1.Location = new Point(70, 220);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* creating button2 */
button2 = new Button();
button2.Size = new Size(150, 40);
button2.Text = "Subtract";
/* creating button3 */
button3 = new Button();
button3.Size = new Size(150, 40);
button3.Text = "Multiply";
button3.Location = new Point(410, 220);
button3.Click += Button3_Click;
this.Controls.Add(button3);
/* creating button4 */
button4 = new Button();
button4.Size = new Size(150, 40);
button4.Text = "Divide";
button4.Location = new Point(580, 220);
button4.Click += Button4_Click;
this.Controls.Add(button4);
}
Output
Enter any first number and second number and click on “Add”, “Subtract”, “Multiply” and “Divide”
buttons.
• The “NumericUpDown” class / control is used to accept a number from the user. It doesn’t
accept alphabets.
o using System.Windows.Forms;
o NumericUpDown referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event = method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by
the user.
Syntax: referencevariable.TextAlign =
System.Windows.Forms.HorizontalAlignment.Left;
1 ValueChanged Executes when the user types some number in the control.
5 KeyPress Executes when the user presses any key on the keyboard (before
accepting the character into the control).
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace NumericUpDownExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "NumericUpDown Example";
this.Size = new Size(350, 180);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Amount (10000 to 50000): ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected number here";
label2.AutoSize = true;
label2.Location = new Point(50, 150);
this.Controls.Add(label2);
/* creating numericupdown1 */
numericupdown1 = new NumericUpDown();
numericupdown1.Size = new Size(200, 30);
numericupdown1.Location = new Point(380, 50);
numericupdown1.Minimum = 10000;
numericupdown1.Maximum = 50000;
numericupdown1.Increment = 100;
numericupdown1.DecimalPlaces = 2;
numericupdown1.ValueChanged += Numericupdown1_ValueChanged;
this.Controls.Add(numericupdown1);
}
Output
• The “DateTimePicker” class / control is used to accept a date or time from the user. It
automatically shows popup calendar.
o using System.Windows.Forms;
o DateTimePicker referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event = method ;
o this.Controls.Add( referencevariable );
1 Value Represents the currently selected date & time of the control.
4 MinDate Represents the minimum date that can be selected in the control.
5 MaxDate Represents the maximum date that can be selected in the control.
Options: pixels.
Options: pixels
Syntax: referencevariable.Cursor =
System.Windows.Forms.Cursors.Hand;
False: The control doesn’t work. That means, the control can’t be used by
the user.
4 KeyPress Executes when the user presses any key on the keyboard (before
accepting the character into the control).
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace DateTimePickerExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
DateTimePicker datetimepicker1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "DateTimePicker Example";
this.Size = new Size(350, 180);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Date: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected date here";
label2.AutoSize = true;
label2.Location = new Point(50, 120);
this.Controls.Add(label2);
/* creating datetimepicker1 */
datetimepicker1 = new DateTimePicker();
datetimepicker1.Size = new Size(200, 30);
datetimepicker1.Location = new Point(180, 50);
datetimepicker1.Format = DateTimePickerFormat.Short;
datetimepicker1.ValueChanged += Datetimepicker1_ValueChanged;
this.Controls.Add(datetimepicker1);
}
private void Datetimepicker1_ValueChanged(object sender, EventArgs e)
{
DateTime dt = datetimepicker1.Value;
label2.Text = dt.ToShortDateString();
}
}
}
Output
• The “MonthCalendar” class / control is used to show a calendar and allow the user to
select a date. It shows calendar directly (without dropdown button).
o using System.Windows.Forms;
o MonthCalendar referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event = method ;
o this.Controls.Add( referencevariable );
3 MaxSelectionCount Represents the maximum no. of dates that can be selected in the
control. Default: 7
4 MinDate Represents the minimum date that can be selected in the control.
5 MaxDate Represents the maximum date that can be selected in the control.
Options: pixels.
Options: pixels
Syntax: referencevariable.Cursor =
System.Windows.Forms.Cursors.Hand;
False: The control doesn’t work. That means, the control can’t be
used by the user.
4 KeyPress Executes when the user presses any key on the keyboard (before
accepting the character into the control).
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace MonthCalendarExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
MonthCalendar monthcalendar1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "MonthCalendar Example";
this.Size = new Size(300, 200);
/* creating label1 */
label1 = new Label();
label1.Text = "Choose a date: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected date here";
label2.AutoSize = true;
label2.Location = new Point(50, 280);
this.Controls.Add(label2);
/* creating monthcalendar1 */
monthcalendar1 = new MonthCalendar();
monthcalendar1.Location = new Point(50, 90);
monthcalendar1.DateSelected += Monthcalendar1_DateSelected;
this.Controls.Add(monthcalendar1);
}
Output
• The “ToolTip” class / control is used to display a tooltip message (help message) to the
user when the user places the mouse pointer on a control.
o using System.Windows.Forms;
o ToolTip referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Set tooltip
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TooltipExample
{
public partial class Form1 : Form
{
//create a reference variables
Button button1;
ToolTip tt;
public Form1()
{
InitializeComponent();
//form properties
this.Font = new Font("Tahoma", 25);
this.Size = new Size(500, 300);
this.Text = "Tooltip Example";
//button1
button1 = new Button();
button1.Text = "Tooltip Example";
button1.AutoSize = true;
button1.Location = new Point(100, 100);
this.Controls.Add(button1);
//tooltip
tt = new ToolTip();
tt.IsBalloon = true;
tt.ToolTipTitle = "Hello";
tt.SetToolTip(button1, "Please click the button");
}
}
}
When you place the mouse pointer on the button, it shows the tooltip message.
• “Validation” is a process of checking the form values whether those are correct or not.
o using System.Windows.Forms;
o ErrorProvider referencevariable ;
• Create an object:
• Set properties:
o referencevariable.property = value ;
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace ErrorProviderExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1;
TextBox textbox1;
Button button1;
ErrorProvider errorprovider1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "ErrorProvider Example";
this.Size = new Size(350, 180);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Name (required): ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 30);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* creating button1 */
button1 = new Button();
button1.Text = "OK";
button1.Size = new Size(100, 50);
button1.Location = new Point(300, 100);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* creating errorprovider1 */
Output
When you click on OK button without entering the name, it shows blinking “!” symbol. When you
place the mouse pointer on “!” icon it shows error message.
• It is useful in validations. Ex: Alphabets only allowed, Numbers only allowed, email address
only allowed, Mobile number only allowed etc.
o using System.Text.RegularExpressions;
o Regex referencevariable ;
• Create an object:
o referencevariable.Match(value);
1 Match Checks whether the value is matching with given expression or not.
Syntax: referencevariable.Match(value);
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Text.RegularExpressions;
namespace RegularExpressionsExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1;
TextBox textbox1;
Button button1;
ErrorProvider errorprovider1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "ErrorProvider Example";
this.Size = new Size(350, 180);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Name (alphabets only): ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 30);
textbox1.Location = new Point(330, 50);
this.Controls.Add(textbox1);
/* creating button1 */
button1 = new Button();
button1.Text = "OK";
button1.Size = new Size(100, 50);
button1.Location = new Point(330, 100);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* creating errorprovider1 */
errorprovider1 = new ErrorProvider();
errorprovider1.BlinkStyle = ErrorBlinkStyle.AlwaysBlink;
}
Output
When you type alphabets and numbers and then click on OK button, it shows blinking “!” symbol.
When you place the mouse pointer on “!” icon it shows error message. If you enter alphabets only,
it hides the “!” symbol. That means it is accepted.
• The “MaskedTextBox” class / control is used to accept a value from the user, based on a
specific pattern (__/__/____). Ex: Date
o using System.Windows.Forms;
o MaskedTextBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
Syntax: referencevariable.TextAlign =
System.Windows.Forms.HorizontalAlignment.Left;
14 PromptChar Represents the character, which should be shown to the user in place of a
character.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace MaskedTextBoxExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
MaskedTextBox maskedtextbox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "MaskedTextBox Example";
this.Font = new System.Drawing.Font("Tahoma", 20);
this.Size = new System.Drawing.Size(750, 380);
/* creating label1 */
label1 = new Label();
label1.Text = "Date: ";
label1.AutoSize = true;
/* creating label2 */
label2 = new Label();
label2.Text = "Selected date here";
label2.AutoSize = true;
label2.Location = new System.Drawing.Point(50, 120);
this.Controls.Add(label2);
/* creating maskedtextbox1 */
maskedtextbox1 = new MaskedTextBox();
maskedtextbox1.Size = new System.Drawing.Size(200, 30);
maskedtextbox1.Location = new System.Drawing.Point(180, 50);
maskedtextbox1.Mask = "00/00/0000";
maskedtextbox1.TextChanged += Maskedtextbox1_TextChanged;
maskedtextbox1.PromptChar = '_';
this.Controls.Add(maskedtextbox1);
}
Output
• The “CheckBox” class / control is used to accept Yes / No type of option to the user. Ex:
Accept license agreement
o using System.Windows.Forms;
o CheckBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable);
Properties of “CheckBox” class:
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CheckBoxExample
{
public partial class Form1 : Form
{
//create reference variables
CheckBox checkbox1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "CheckBox Example";
this.Font = new Font("Tahoma", 25);
this.Size = new Size(750, 480);
/* creating label1 */
checkbox1 = new CheckBox();
checkbox1.Text = "I accept license agreement";
checkbox1.AutoSize = true;
checkbox1.Location = new Point(50, 50);
checkbox1.CheckedChanged += Checkbox1_CheckedChanged;
this.Controls.Add(checkbox1);
/* creating button1 */
button1 = new Button();
button1.Text = "OK";
button1.Size = new Size(150, 50);
button1.Location = new Point(50, 140);
button1.Enabled = false;
this.Controls.Add(button1);
}
Output
• The “RadioButton” class / control is used to display a set of options to the user and allow
the user to select any one of them. Ex: Male, Female.
o using System.Windows.Forms;
o RadioButton referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
1 CheckedChanged Executes when the user checks / unchecks the radio button.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace RadioButtonExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
RadioButton radiobutton1, radiobutton2;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "RadioButton Example";
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 380);
/* creating label1 */
label1 = new Label();
label1.Text = "Gender: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected option here";
label2.AutoSize = true;
label2.Location = new Point(50, 120);
this.Controls.Add(label2);
/* creating radiobutton1 */
radiobutton1 = new RadioButton();
radiobutton1.Text = "Male";
radiobutton1.AutoSize = true;
radiobutton1.Location = new Point(180, 50);
radiobutton1.CheckedChanged += Radiobutton1_CheckedChanged;
this.Controls.Add(radiobutton1);
/* creating radiobutton2 */
radiobutton2 = new RadioButton();
radiobutton2.Text = "Female";
radiobutton2.AutoSize = true;
radiobutton2.Location = new Point(280, 50);
radiobutton2.CheckedChanged += Radiobutton2_CheckedChanged;
this.Controls.Add(radiobutton2);
}
else
label2.Text = "Female selected";
}
Output
• The “ComboBox” class / control is used to display a set of options to the user and allow the
user to select any one of them. Ex: Countries: India, UK, USA etc.
o using System.Windows.Forms;
o ComboBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable);
Options: pixels.
Options: pixels
Syntax: referencevariable.Cursor =
System.Windows.Forms.Cursors.Hand;
False: The control doesn’t work. That means, the control can’t be used by
the user.
11 Items Represents the collection of items, that should be appear in the combo
box.
Syntax: referencevariable.DropDownStyle =
System.Windows.Forms.ComboBoxStyle.option here;
14 SelectedIndex Represents the index of currently selected item in the combo box. Index
starts from 0.
1 SelectedIndexChanged Executes when the user selects an item in the combo box.
Syntax: referencevariable.SelectedIndexChanged +=
methodname;
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace ComboBoxExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2, label3;
ComboBox combobox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "ComboBox Example";
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
/* creating label1 */
label1 = new Label();
label1.Text = "Country: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected item here";
label2.AutoSize = true;
label2.Location = new Point(180, 120);
this.Controls.Add(label2);
/* creating label3 */
label3 = new Label();
label3.Text = "Selected index here";
label3.AutoSize = true;
label3.Location = new Point(180, 170);
this.Controls.Add(label3);
/* creating combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(200, 40);
combobox1.Location = new Point(180, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
string[] countries = new string[] { "India", "China", "UK", "USA", "Japan"
};
combobox1.Items.AddRange(countries);
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
}
Output
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
namespace CascadingComboBoxExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
ComboBox combobox1, combobox2;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "Cascading ComboBox Example";
this.Font = new System.Drawing.Font("Tahoma", 20);
this.Size = new System.Drawing.Size(550, 280);
/* creating label1 */
label1 = new Label();
label1.Text = "Country: ";
label1.AutoSize = true;
label1.Location = new System.Drawing.Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "State: ";
label2.AutoSize = true;
/* creating combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new System.Drawing.Size(200, 40);
combobox1.Location = new System.Drawing.Point(180, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.Items.AddRange(new string[] { "India", "UK", "USA" });
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* creating combobox2 */
combobox2 = new ComboBox();
combobox2.Size = new System.Drawing.Size(200, 40);
combobox2.Location = new System.Drawing.Point(180, 120);
combobox2.DropDownStyle = ComboBoxStyle.DropDownList;
this.Controls.Add(combobox2);
}
combobox2.Items.Clear();
combobox2.Items.AddRange(new string[] { "G", "H", "I" });
}
}
}
}
Output
When you select a country in the first combo box, it shows its list of states in the second combo
box.
• The “ListBox” class / control displays a set of options to the user and allow the user to
select one or more them. Ex: Countries: India, UK, USA etc.
o using System.Windows.Forms;
o ListBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by
the user.
11 Items Represents the collection of items, that should be appear in the listbox.
Syntax: referencevariable.SelectedItems
Syntax: referencevariable.SelectedIndexChanged +=
methodname;
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace ListBoxExample
{
public partial class Form1 : Form
{
//create reference variables
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "ListBox Example";
this.Font = new Font("Tahoma", 18);
this.Size = new Size(750, 380);
/* creating label1 */
label1 = new Label();
label1.Text = "Country: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected Countries:";
label2.AutoSize = true;
label2.Location = new Point(350, 50);
this.Controls.Add(label2);
/* creating listbox1 */
listbox1 = new ListBox();
listbox1.Size = new Size(200, 200);
listbox1.Location = new Point(55, 90);
listbox1.SelectionMode = SelectionMode.MultiSimple;
listbox1.Items.AddRange(new string[] { "India", "China", "Japan", "UK",
"USA" });
listbox1.SelectedIndexChanged += Listbox1_SelectedIndexChanged; ;
this.Controls.Add(listbox1);
/* creating listbox2 */
listbox2 = new ListBox();
listbox2.Size = new Size(200, 200);
listbox2.Location = new Point(360, 90);
this.Controls.Add(listbox2);
}
private void Listbox1_SelectedIndexChanged(object sender, EventArgs e)
{
listbox2.Items.Clear();
for (int i = 0; i < listbox1.SelectedItems.Count; i++)
{
listbox2.Items.Add(listbox1.SelectedItems[i]);
}
}
}
}
Output
When you select any country names in the first listbox, only the selected names will appear in the
second listbox.
• The “CheckedListBox” class / control is used to display a set of options to the user and
allow the user to select one or more them. Ex: Countries: India, UK, USA etc. It shows
checkbox for each item.
o using System.Windows.Forms;
o CheckedListBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
11 Items Represents the collection of items, that should be appear in the checked list
box.
Syntax: referencevariable.CheckedItems
13 CheckOnClick True: The checkbox will be checked when the user clicks on the item.
False: The checkbox will checked when the user only clicks on the actual
checkbox (not item).
Syntax: referencevariable.SelectedIndexChanged +=
methodname;
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace CheckedListBoxExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
ListBox listbox1;
CheckedListBox checkedlistbox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "CheckedListBox Example";
this.Size = new Size(350, 180);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Country: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected Countries:";
label2.AutoSize = true;
label2.Location = new Point(350, 50);
this.Controls.Add(label2);
/* creating checkedlistbox1 */
checkedlistbox1 = new CheckedListBox();
checkedlistbox1.Size = new Size(200, 200);
checkedlistbox1.Location = new Point(55, 90);
checkedlistbox1.Items.AddRange(new string[] { "India", "China",
"Japan", "UK", "USA" });
checkedlistbox1.CheckOnClick = true;
checkedlistbox1.SelectedIndexChanged +=
Checkedlistbox1_SelectedIndexChanged;
this.Controls.Add(checkedlistbox1);
/* creating listbox1 */
listbox1 = new ListBox();
listbox1.Size = new Size(200, 200);
listbox1.Location = new Point(360, 90);
this.Controls.Add(listbox1);
}
Output
When you select any country names in the first checked listbox, only the selected names will
appear in the second listbox.
• The “TreeView” class / control is used to display a set of options in tree structure (parent
and child structure). Ex: Folders and files.
• Each option (item) is called as “Node”. A node can have ‘n’ no. of child nodes.
o using System.Windows.Forms;
o TreeView referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by
the user.
9 Nodes Represents the collection of nodes, that should be appear in the tree view.
Syntax: referencevariable.Nodes[index];
Syntax: referencevariable.Nodes[index].FullPath
3 Index Represents index of the current node. Index starts from zero (0).
Syntax: referencevariable.Nodes[index].Index
4 Level Represents level of the current node. Index starts from zero (0).
Syntax: referencevariable.Nodes[index].Level
5 Nodes Represents the collection of nodes, that should be appear in the tree view.
Syntax: referencevariable.Nodes[index]
6 Checked Represents the current status of the checkbox of current tree node.
Syntax: referencevariable.Nodes[index].BackColor =
System.Drawing.Color.Green;
Syntax: referencevariable.Nodes[index].ForeColor =
System.Drawing.Color.Green;
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
namespace TreeViewExample
{
public partial class Form1 : Form
{
//create reference variables
Label label1, label2;
ListBox listbox1;
TreeView treeview1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "TreeView Example";
this.Size = new Size(400, 270);
this.Font = new Font("Tahoma", 18);
/* creating label1 */
label1 = new Label();
label1.Text = "Products: ";
label1.AutoSize = true;
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* creating label2 */
label2 = new Label();
label2.Text = "Selected Products:";
label2.AutoSize = true;
label2.Location = new Point(380, 50);
this.Controls.Add(label2);
/* creating treeview1 */
treeview1 = new TreeView();
treeview1.Size = new Size(300, 300);
treeview1.Location = new Point(55, 90);
treeview1.Nodes.Add("Mobiles");
treeview1.Nodes.Add("Laptops");
treeview1.Nodes[0].Nodes.Add("Samsung Mobiles");
treeview1.Nodes[0].Nodes.Add("iPhones");
treeview1.Nodes[0].Nodes.Add("Windows Phones");
treeview1.Nodes[1].Nodes.Add("Dell Laptops");
treeview1.Nodes[1].Nodes.Add("Lenovo Laptops");
treeview1.Nodes[1].Nodes.Add("HP Laptops");
treeview1.ExpandAll();
treeview1.CheckBoxes = true;
treeview1.AfterCheck += Treeview1_AfterCheck;
this.Controls.Add(treeview1);
/* creating listbox1 */
listbox1 = new ListBox();
listbox1.Size = new Size(300, 300);
listbox1.Location = new Point(390, 90);
this.Controls.Add(listbox1);
}
}
}
}
Output
When you select any node in the first treeview, only the selected names will appear in the second
listbox.
• The “PictureBox” class / control is used to display an image in the windows form.
• Note: You must copy and paste the image into a specific folder. Ex: C:\CSharp
o using System.Windows.Forms;
o PictureBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
Syntax: referencevariable.SizeMode =
System.Windows.Forms.PictureBoxSizeMode.optionhere;
Creating Project
• Create a folder called “CSharp” in “C:\”. Copy and paste “img1.jpg” into “C:\CSharp” folder.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PictureBoxExample
{
public partial class Form1 : Form
{
PictureBox pb1;
public Form1()
{
InitializeComponent();
this.Size = new Size(600, 400);
pb1 = new PictureBox();
pb1.Size = new Size(300, 200);
pb1.Location = new Point(50, 50);
pb1.Image = Image.FromFile(@"C:\CSharp\img1.jpg");
pb1.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(pb1);
}
}
}
Creating Project
• Create a folder called “CSharp” in “C:\”. Copy and paste “img1.jpg” to “img10.jpg” into
“C:\CSharp” folder.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PictureBoxExample2
{
public partial class Form1 : Form
{
PictureBox pictureBox1;
Button button1, button2;
Label lbl1;
string[] myimages = new string[] { @"C:\CSharp\img1.jpg",
@"C:\CSharp\img2.jpg", @"C:\CSharp\img3.jpg", @"C:\CSharp\img4.jpg",
@"C:\CSharp\img5.jpg", @"C:\CSharp\img6.jpg", @"C:\CSharp\img7.jpg",
@"C:\CSharp\img8.jpg", @"C:\CSharp\img9.jpg", @"C:\CSharp\img10.jpg" };
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(800, 400);
/*picturebox*/
pictureBox1 = new PictureBox();
pictureBox1.Size = new Size(300, 200);
pictureBox1.Location = new Point(200, 50);
pictureBox1.Image = Image.FromFile(myimages[0]);
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
this.Controls.Add(pictureBox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Previous";
button1.Location = new Point(50, 100);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* button2 */
button2 = new Button();
button2.AutoSize = true;
button2.Text = "Next";
button2.Location = new Point(550, 100);
button2.Click += Button2_Click;
this.Controls.Add(button2);
/* lbl1 */
lbl1 = new Label();
lbl1.AutoSize = true;
lbl1.Text = "0";
lbl1.Location = new Point(320, 270);
this.Controls.Add(lbl1);
}
private void Button1_Click(object sender, EventArgs e)
{
int n = Convert.ToInt32(lbl1.Text);
n--;
if (n < 0)
{
n = 0;
MessageBox.Show("Already at first image");
}
lbl1.Text = Convert.ToString(n);
Output
• The “Panel” class / control is used to display a container in the windows form. Inside the
panel, you can place any controls.
o using System.Windows.Forms;
o Panel referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
9 Controls Represents the collection of controls that should be appear inside the panel.
Syntax: referencevariable.Controls[index]
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PanelExample
{
public partial class Form1 : Form
{
Panel panel1;
Label lbl1;
TextBox txt1;
Button btn1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(800, 400);
/* panel1 */
panel1 = new Panel();
panel1.Size = new Size(600, 70);
panel1.Location = new Point(100, 100);
panel1.BackColor = Color.LightGreen;
this.Controls.Add(panel1);
/* lbl1 */
lbl1 = new Label();
lbl1.AutoSize = true;
lbl1.Text = "Search:";
lbl1.Location = new Point(30, 20);
panel1.Controls.Add(lbl1);
/* txt1 */
txt1 = new TextBox();
txt1.Location = new Point(150, 16);
txt1.Size = new Size(250, 40);
panel1.Controls.Add(txt1);
/* btn1 */
btn1 = new Button();
btn1.Text = "OK";
btn1.Location = new Point(420, 16);
Output
• The “GroupBox” class / control is used to display a container in the windows form. Inside
the groupbox, you can place any controls.
o using System.Windows.Forms;
o GroupBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
10 Controls Represents the collection of controls that should be appear inside the
groupbox.
Syntax: referencevariable.Controls[index]
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GroupBoxExample
{
public partial class Form1 : Form
{
GroupBox groupbox1;
TextBox txt1;
Button btn1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(800, 400);
/* panel1 */
groupbox1 = new GroupBox();
groupbox1.Text = "Search";
groupbox1.Size = new Size(600, 100);
groupbox1.Location = new Point(100, 100);
this.Controls.Add(groupbox1);
/* txt1 */
txt1 = new TextBox();
txt1.Location = new Point(20, 40);
txt1.Size = new Size(450, 44);
groupbox1.Controls.Add(txt1);
/* btn1 */
btn1 = new Button();
btn1.Text = "OK";
btn1.Location = new Point(480, 36);
btn1.Size = new Size(100, 48);
groupbox1.Controls.Add(btn1);
}
}
}
• The “SplitContainer” class / control is used to divide the form as two parts and allow the
user two resize the parts.
• Inside the SplitContainer two panels (panel1 and panel2) will be created automatically; you
can place any controls in panel1 or panel2.
o using System.Windows.Forms;
o SplitContainer referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Syntax: referencevariable.Panel1
Syntax: referencevariable.Panel2
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by
the user.
11 Controls Represents the collection of controls that should be appear inside the
groupbox.
Syntax: referencevariable.Controls[index]
12 Dock Displays the splitcontainer at most top / right / bottom / left side / full
screen of the form.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SplitContainerExample
{
public partial class Form1 : Form
{
SplitContainer splitcontainer1;
Label lbl1, lbl2;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(800, 400);
/* panel1 */
splitcontainer1 = new SplitContainer();
splitcontainer1.Size = new Size(600, 100);
splitcontainer1.Location = new Point(100, 100);
splitcontainer1.Panel1.BackColor = Color.LightBlue;
splitcontainer1.Panel2.BackColor = Color.LightGreen;
splitcontainer1.Panel1.AutoScroll = true;
splitcontainer1.Panel2.AutoScroll = true;
splitcontainer1.Dock = DockStyle.Fill;
this.Controls.Add(splitcontainer1);
/* lbl1 */
lbl1 = new Label();
lbl1.AutoSize = true;
lbl1.Text = "Label1 in Panel1";
lbl1.Location = new Point(20, 20);
splitcontainer1.Panel1.Controls.Add(lbl1);
/* lbl2 */
lbl2 = new Label();
lbl2.AutoSize = true;
lbl2.Text = "Label2 in Panel1";
lbl2.Location = new Point(20, 20);
splitcontainer1.Panel2.Controls.Add(lbl2);
}
}
}
Output
• The “TabControl” class / control is used to divide the form as two tabs and displays only
one tab at-a-time on the screen.
o using System.Windows.Forms;
o TabControl referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
7 Controls Represents the collection of controls that should be appear inside the
tabcontrol.
Syntax: referencevariable.Controls[index]
8 Dock Displays the tabcontrol at most top / right / bottom / left side / full screen of
the form.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TabControlExample
{
public partial class Form1 : Form
{
TabControl tabcontrol1;
TabPage tabpage1, tabpage2, tabpage3;
Label lbl1, lbl2, lbl3;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 450);
/* tabcontrol1 */
tabcontrol1 = new TabControl();
tabcontrol1.Dock = DockStyle.Fill;
this.Controls.Add(tabcontrol1);
/* tabpage1 */
tabpage1 = new TabPage();
tabpage1.Text = "Home";
tabcontrol1.Controls.Add(tabpage1);
/* tabpage2 */
tabpage2 = new TabPage();
tabpage2.Text = "About";
tabcontrol1.Controls.Add(tabpage2);
/* tabpage3 */
tabpage3 = new TabPage();
tabpage3.Text = "Contact";
tabcontrol1.Controls.Add(tabpage3);
/* lbl1 */
lbl1 = new Label();
lbl1.Text = "Home content here";
lbl1.AutoSize = true;
tabpage1.Controls.Add(lbl1);
/* lbl2 */
lbl2 = new Label();
lbl2.Text = "About content here";
lbl2.AutoSize = true;
tabpage2.Controls.Add(lbl2);
/* lbl3 */
lbl3 = new Label();
lbl3.Text = "Contact content here";
lbl3.AutoSize = true;
tabpage3.Controls.Add(lbl3);
}
}
}
Output
• The “FlowLayoutPanel” class / control is same as panel, but it arranges the controls side-
by-side automatically. When a row is over, it automatically moves the control to the next
line.
o using System.Windows.Forms;
o FlowLayoutPanel referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by
the user.
7 Controls Represents the collection of controls that should be appear inside the
tabcontrol.
Syntax: referencevariable.Controls[index]
8 Dock Displays the tabcontrol at most top / right / bottom / left side / full screen
of the form.
Syntax: referencevariable.FlowDirection =
System.Windows.Forms.FlowDirection.option here;
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FlowLayoutPanelExample
{
public partial class Form1 : Form
{
FlowLayoutPanel flowlayoutpanel1;
Label lbl1, lbl2, lbl3;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 450);
/* flowlayoutpanel1 */
flowlayoutpanel1 = new FlowLayoutPanel();
flowlayoutpanel1.BackColor = Color.LightBlue;
flowlayoutpanel1.Size = new Size(600, 300);
flowlayoutpanel1.Location = new Point(50, 50);
flowlayoutpanel1.FlowDirection = FlowDirection.LeftToRight;
this.Controls.Add(flowlayoutpanel1);
/* lbl1 */
lbl1 = new Label();
lbl1.Text = "Label1";
lbl1.AutoSize = true;
flowlayoutpanel1.Controls.Add(lbl1);
/* lbl2 */
lbl2 = new Label();
lbl2.Text = "Label2";
lbl2.AutoSize = true;
flowlayoutpanel1.Controls.Add(lbl2);
/* lbl3 */
lbl3 = new Label();
lbl3.Text = "Label3";
lbl3.AutoSize = true;
flowlayoutpanel1.Controls.Add(lbl3);
}
}
}
Output
o using System.Windows.Forms;
o LinkLabel referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
4 AutoSize True: The control will take the essential size automatically.
False: The control will not take the size automatically; we need to set
the size manually.
Options: pixels
Syntax: referencevariable.Cursor =
System.Windows.Forms.Cursors.Hand;
False: The control doesn’t work. That means, the control can’t be used
by the user.
2 MouseEnter Executes when the user moves the mouse pointer from outside to
inside the control.
3 MouseLeave Executes when the user moves the mouse pointer from inside to
outside the control.
Creating Project
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace LinkLabelExample
{
public partial class Form1 : Form
{
LinkLabel linklabel1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 350);
/* linklabel1 */
linklabel1 = new LinkLabel();
linklabel1.Text = "Click me";
linklabel1.AutoSize = true;
linklabel1.Location = new Point(200, 100);
linklabel1.LinkClicked += Linklabel1_LinkClicked;
this.Controls.Add(linklabel1);
}
private void Linklabel1_LinkClicked(object sender,
LinkLabelLinkClickedEventArgs e)
{
linklabel1.Text = "Clicked";
}
}
}
Output
• The “WebBrowser” class / control is used to display a web page in the form.
o using System.Windows.Forms;
o WebBrowser referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
Syntax: referencevariable.Navigate(“url”)
Syntax: referencevariable.GoBack()
Syntax: referencevariable.GoForward()
Creating Project
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WebBrowserExample
{
public partial class Form1 : Form
{
Button btn1, btn2;
WebBrowser webbrowser1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(1000, 700);
/* btn1 */
btn1 = new Button();
btn1.Text = "Google";
btn1.AutoSize = true;
btn1.Location = new Point(50, 50);
btn1.Click += Btn1_Click;
this.Controls.Add(btn1);
/* btn2 */
/* webbrowser1 */
webbrowser1 = new WebBrowser();
webbrowser1.Navigate("http://www.google.com");
webbrowser1.Size = new Size(900, 500);
webbrowser1.Location = new Point(50, 130);
this.Controls.Add(webbrowser1);
}
Output
“System.Windows.Forms.Timer” class
The “System.Windows.Forms.Timer” class
• The “Timer” class / control is used to execute the code repeatedly for every ‘n’ no. of milli
seconds..
o using System.Windows.Forms;
o Timer referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
1 Interval Represents no. of milli seconds, based on which the timer’s code should
execute.
2 Enabled True: Timer is actived. It calls Tick event at the specified milli seconds.
False: Timer is deactivated. It doesn’t call Tick event at the specified milli
seconds.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TimerExample
{
public partial class Form1 : Form
{
Timer timer1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 350);
/* timer1 */
timer1 = new Timer();
timer1.Enabled = true;
timer1.Interval = 3000;
timer1.Tick += Timer1_Tick;
}
Output
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TimerWithTimeExample
{
public partial class Form1 : Form
{
Timer timer1;
Label lbl1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(800, 350);
/* lbl1 */
lbl1 = new Label();
lbl1.AutoSize = true;
lbl1.Text = "Time appears here";
lbl1.Location = new Point(100, 100);
lbl1.Font = new Font("Tahoma", 40);
this.Controls.Add(lbl1);
/* timer1 */
timer1 = new Timer();
timer1.Enabled = true;
timer1.Interval = 1000;
timer1.Tick += Timer1_Tick;
}
Output
It shows the system date and time in the label. It automatically updates for every second-by-
second.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TimerWithCounterExample
{
public partial class Form1 : Form
{
Timer timer1;
Label lbl1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(800, 350);
/* lbl1 */
lbl1 = new Label();
lbl1.AutoSize = true;
lbl1.Text = "1";
lbl1.Location = new Point(100, 100);
lbl1.Font = new Font("Tahoma", 40);
this.Controls.Add(lbl1);
/* timer1 */
timer1 = new Timer();
timer1.Enabled = true;
timer1.Interval = 100;
timer1.Tick += Timer1_Tick;
}
Output
It automatically increments the number in the label, for every 100 milli seconds.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace TimerSlideShowExample
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 450);
/* lbl1 */
lbl1 = new Label();
lbl1.AutoSize = true;
lbl1.Text = "0";
lbl1.Location = new Point(100, 50);
lbl1.Font = new Font("Tahoma", 40);
this.Controls.Add(lbl1);
/* timer1 */
timer1 = new Timer();
timer1.Enabled = true;
timer1.Interval = 1000;
timer1.Tick += Timer1_Tick;
/* picturebox1 */
picturebox1 = new PictureBox();
picturebox1.Size = new Size(300, 230);
picturebox1.Location = new Point(100, 130);
picturebox1.SizeMode = PictureBoxSizeMode.StretchImage;
picturebox1.Image = Image.FromFile(MyImages[0]);
this.Controls.Add(picturebox1);
}
if (n == MyImages.Count)
{
timer1.Enabled = false;
MessageBox.Show("Done");
return;
}
Output
• Look and feel depends on the operating system. Ex: Windows 7, Windows 8.1, Windows 10
etc.
o using System.Windows.Forms;
o ProgressBar referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
2 MouseEnter Executes when the user moves the mouse pointer from outside to inside
the control.
3 MouseLeave Executes when the user moves the mouse pointer from inside to outside
the control.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ProgressBarExample
{
public partial class Form1 : Form
{
ProgressBar progressbar1;
Timer timer1;
Label lbl1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 350);
/* lbl1 */
lbl1 = new Label();
lbl1.AutoSize = true;
lbl1.Text = "0";
Output
• The “NotifyIcon” class / control is used to display an icon in the windows taskbar, while the
form is running.
o using System.Windows.Forms;
o NotifyIcon referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
1 Icon Represents the icon that should be appear in the windows taskbar.
1 ShowBalloonTip Shows a balloon tip message from the icon at windows taskbar.
1 Click Executes when the user clicks on the icon at windows taskbar.
2 BalloonTipClicked Executes when the user clicks on the balloon tip message at
windows taskbar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace NotifyIconExample
{
public partial class Form1 : Form
{
Button button1;
NotifyIcon notifyicon1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 350);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Show Notification";
button1.Location = new Point(100, 100);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* notifyicon1 */
notifyicon1 = new NotifyIcon();
notifyicon1.Icon = new Icon(@"C:\CSharp\Sample.ico");
notifyicon1.Visible = true;
}
Output
When the user clicks on the button, it shows tooltip message from the icon.
Popup Boxes
To display popup boxes:
• Set essential properties to the form such as “MinimizeBox”, “MaximizeBox” etc., to the
Form2.
• To exchange data between Form1 and Form2, use a static class called “Common”.
PopupBoxes - Example
Expected Output
Creating Project
• Click on OK.
• Open solution explorer. Right click on the project name (PopupBoxesExample) and click on
“Add” – “New Item”. Click on “Windows Forms” – “Windows Form”. Enter the form name as
• Open solution explorer. Right click on the project name (PopupBoxesExample) and click on
“Add” – “New Item”. Click on “Code” – “Class”. Enter the form name as “Common.cs”. Click
on “Add”.
Common.cs
using System;
namespace PopupWindowsExample
{
static class Common
{
public static string Username { get; set; }
}
}
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PopupWindowsExample
{
public partial class Form1 : Form
{
Button button1;
Label label1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Open Popup window";
button1.Location = new Point(100, 100);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Name appears here";
Form2.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace PopupWindowsExample
{
public partial class Form2 : Form
{
Label label1;
TextBox textbox1;
Button button1, button2;
public Form2()
{
InitializeComponent();
/* form properties */
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Name: ";
label1.Location = new Point(100, 100);
this.Controls.Add(label1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 30);
textbox1.Location = new Point(220, 97);
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "OK";
button1.Location = new Point(220, 150);
button1.Click += Button1_Click;
button1.DialogResult = DialogResult.OK;
this.Controls.Add(button1);
this.AcceptButton = button1;
/* button2 */
button2 = new Button();
button2.AutoSize = true;
button2.Text = "Cancel";
button2.Location = new Point(320, 150);
button2.Click += Button2_Click;
button2.DialogResult = DialogResult.Cancel;
this.Controls.Add(button2);
this.CancelButton = button2;
}
Output
• The “ColorDialog” class / control is used to display a color dialogbox (popupbox) on the
form, which allows the user to select a color.
o using System.Windows.Forms;
o ColorDialog referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call methods:
o referencevariable.method ();
1 ShowDialog() Displays the color dialogbox on the form. It returns the clicked button
name (OK or Cancel) as “DialogResult”.
Syntax: referencevariable.ShowDialog()
Syntax: referencevariable.Reset();
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ColorDialogExample
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 400);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Text = "Text here";
textbox1.Size = new Size(500, 30);
textbox1.Location = new Point(100, 50);
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Back color";
button1.Location = new Point(100, 150);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* button2 */
button2 = new Button();
button2.AutoSize = true;
button2.Text = "Fore color";
button2.Location = new Point(320, 150);
button2.Click += Button2_Click;
this.Controls.Add(button2);
/* colordialog1 */
colordialog1 = new ColorDialog();
}
Output
• The “FontDialog” class / control is used to display a font dialogbox (popupbox) on the
form, which allows the user to select a font.
o using System.Windows.Forms;
o FontDialog referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call methods:
o referencevariable.method ();
1 ShowDialog() Displays the font dialogbox on the form. It returns the clicked button
name (OK or Cancel) as “DialogResult”.
Syntax: referencevariable.ShowDialog()
Syntax: referencevariable.Reset();
Creating Project
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FontDialogExample
{
public partial class Form1 : Form
{
TextBox textbox1;
Button button1;
FontDialog fontdialog1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(900, 400);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Text = "Text here";
textbox1.Size = new Size(500, 30);
textbox1.Location = new Point(100, 50);
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Font";
button1.Location = new Point(100, 250);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* fontdialog1 */
fontdialog1 = new FontDialog();
}
}
}
}
}
Output
o using System.Windows.Forms;
o FolderBrowserDialog referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call methods:
o referencevariable.method ();
1 ShowDialog() Displays the folder browser dialogbox on the form. It returns the
clicked button name (OK or Cancel) as “DialogResult”.
Syntax: referencevariable.ShowDialog()
Syntax: referencevariable.Reset();
Creating Project
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace FolderBrowserDialogExample
{
public partial class Form1 : Form
{
Label label1;
Button button1;
FolderBrowserDialog folderbrowserdialog1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 16);
this.Size = new Size(900, 400);
/* textbox1 */
label1 = new Label();
label1.Text = "Selected folder path here";
label1.AutoSize = true;
label1.Location = new Point(100, 50);
this.Controls.Add(label1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
/* folderbrowserdialog1 */
folderbrowserdialog1 = new FolderBrowserDialog();
}
Output
Click on “Select a folder” and select any folder and click on OK.
• The “OpenFileDialog” class / control is used to display a open file dialogbox (popupbox) on
the form, which allows the user to select an existing file.
o using System.Windows.Forms;
o OpenFileDialog referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call methods:
o referencevariable.method ();
1 FileName Represents currently selected file name of the open file dialogbox.
2 FileNames Represents currently selected file names of the open file dialogbox.
4 MultiSelect True/False
1 ShowDialog() Displays the open file dialogbox on the form. It returns the clicked
button name (OK or Cancel) as “DialogResult”.
Syntax: referencevariable.ShowDialog()
Syntax: referencevariable.Reset();
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace OpenFileDialogExample
{
public partial class Form1 : Form
{
Label label1;
Button button1;
OpenFileDialog openfiledialog1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 16);
this.Size = new Size(900, 400);
/* textbox1 */
label1 = new Label();
label1.Text = "Selected file path here";
label1.AutoSize = true;
label1.Location = new Point(100, 50);
this.Controls.Add(label1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Open (Select an existing file)";
button1.Location = new Point(100, 150);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* openfiledialog1 */
openfiledialog1 = new OpenFileDialog();
openfiledialog1.Multiselect = false;
openfiledialog1.Filter = "All Files|*.*|Text Files|*.txt";
}
private void Button1_Click(object sender, EventArgs e)
{
if (openfiledialog1.ShowDialog() == DialogResult.OK)
{
label1.Text = openfiledialog1.FileName;
}
}
}
}
Output
• The “SaveFileDialog” class / control is used to display a save file dialogbox (popupbox) on
the form, which allows the user to select a new file.
o using System.Windows.Forms;
o SaveFileDialog referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call methods:
o referencevariable.method ();
1 FileName Represents currently selected file name of the save file dialogbox.
1 ShowDialog() Displays the save file dialogbox on the form. It returns the clicked
button name (OK or Cancel) as “DialogResult”.
Syntax: referencevariable.ShowDialog()
Syntax: referencevariable.Reset();
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace SaveFileDialogExample
{
public partial class Form1 : Form
{
Label label1;
Button button1;
SaveFileDialog savefiledialog1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 16);
this.Size = new Size(900, 400);
/* textbox1 */
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Save (Select a new file)";
button1.Location = new Point(100, 150);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* savefiledialog1 */
savefiledialog1 = new SaveFileDialog();
savefiledialog1.Filter = "All Files|*.*|Text Files|*.txt";
}
private void Button1_Click(object sender, EventArgs e)
{
if (savefiledialog1.ShowDialog() == DialogResult.OK)
{
label1.Text = savefiledialog1.FileName;
}
}
}
}
Output
Type any new file name and click on “Save”. The specified file name appears in the label.
• The “MenuStrip” class / control is used to display a menu bar at the top of the form.
o using System.Windows.Forms;
o MenuStrip referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call methods:
o referencevariable.method ();
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
1 Dock Displays the control at most top / left / right / bottom side of the form.
Syntax: referencevariable.Dock =
System.Windows.Forms.DockStyle.Optionhere;
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
1 ItemClicked Executes when the user clicks any item in the menubar.
Options: pixels.
Syntax: referencevariable.Image =
System.Drawing.Image.FromFile(“image file path here”);
False: The control doesn’t work. That means, the control can’t be used by
the user.
2 MouseEnter Executes when the user places the mouse pointer on the menu item.
3 MouseLeave Executes when the user moves the mouse pointer out of the menu item.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace MenuStripExample
{
public partial class Form1 : Form
{
MenuStrip menustrip1;
ToolStripMenuItem parentmenuitem1, menuitem1, menuitem2,
menuitem3, menuitem4;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(900, 400);
/* menustrip1 */
menustrip1 = new MenuStrip();
menustrip1.Dock = DockStyle.Top;
menustrip1.BackColor = Color.LightGreen;
this.Controls.Add(menustrip1);
/* parentmenuitem1 */
parentmenuitem1 = new ToolStripMenuItem();
parentmenuitem1.Text = "Background color";
menustrip1.Items.Add(parentmenuitem1);
/* menuitem1 */
menuitem1 = new ToolStripMenuItem();
menuitem1.Text = "Red";
menuitem1.ShortcutKeys = (Keys)(Keys.Control | Keys.R);
menuitem1.ForeColor = Color.Red;
menuitem1.Click += Menuitem1_Click;
parentmenuitem1.DropDownItems.Add(menuitem1);
/* menuitem2 */
menuitem2 = new ToolStripMenuItem();
menuitem2.Text = "Green";
menuitem2.ShortcutKeys = (Keys)(Keys.Control | Keys.G);
menuitem2.ForeColor = Color.Green;
menuitem2.Click += Menuitem2_Click;
parentmenuitem1.DropDownItems.Add(menuitem2);
/* menuitem3 */
menuitem3 = new ToolStripMenuItem();
menuitem3.Text = "Blue";
menuitem3.ShortcutKeys = (Keys)(Keys.Control | Keys.B);
menuitem3.ForeColor = Color.Blue;
menuitem3.Click += Menuitem3_Click;
parentmenuitem1.DropDownItems.Add(menuitem3);
/* menuitem4 */
menuitem4 = new ToolStripMenuItem();
menuitem4.Text = "Exit";
menuitem4.ShortcutKeys = Keys.F7;
menuitem4.Click += Menuitem4_Click;
parentmenuitem1.DropDownItems.Add(menuitem4);
}
}
}
}
Output
Go to “Background color” menu and click on “Red”, “Green”, “Blue” and “Exit” options.
• The “ContextMenuStrip” class / control is used to display a right click menu for a form or
any control.
o using System.Windows.Forms;
o ContextMenuStrip referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
False: The control doesn’t work. That means, the control can’t be used by the
user.
1 ItemClicked Executes when the user clicks any item in the context menu.
Creating Project
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ContextMenuStripExample
{
public partial class Form1 : Form
{
TextBox textbox1;
ContextMenuStrip contextmenustrip1;
ToolStripMenuItem menuitem1, menuitem2, menuitem3, menuitem4;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 400);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 40);
textbox1.Location = new Point(200, 100);
textbox1.Text = "Hello";
this.Controls.Add(textbox1);
/* contextmenustrip1 */
/* menuitem1 */
menuitem1 = new ToolStripMenuItem();
menuitem1.Text = "Cut";
menuitem1.ShortcutKeys = (Keys)(Keys.Control | Keys.X);
menuitem1.Click += Menuitem1_Click;
contextmenustrip1.Items.Add(menuitem1);
/* menuitem2 */
menuitem2 = new ToolStripMenuItem();
menuitem2.Text = "Copy";
menuitem2.ShortcutKeys = (Keys)(Keys.Control | Keys.C);
menuitem2.Click += Menuitem2_Click;
contextmenustrip1.Items.Add(menuitem2);
/* menuitem3 */
menuitem3 = new ToolStripMenuItem();
menuitem3.Text = "Paste";
menuitem3.ShortcutKeys = (Keys)(Keys.Control | Keys.V);
menuitem3.Click += Menuitem3_Click;
contextmenustrip1.Items.Add(menuitem3);
/* menuitem4 */
menuitem4 = new ToolStripMenuItem();
menuitem4.Text = "Clear";
menuitem4.Click += Menuitem4_Click;
contextmenustrip1.Items.Add(menuitem4);
}
textbox1.Copy();
}
private void Menuitem3_Click(object sender, EventArgs e)
{
textbox1.Paste();
}
private void Menuitem4_Click(object sender, EventArgs e)
{
textbox1.Clear();
}
}
}
Output
Type some text and right click on the textbox. Click on “Cut”, “Copy”, “Paste”, “Clear”.
• The “ToolStrip” class / control is used to display a toolbar at the top of the form.
o using System.Windows.Forms;
o ToolStrip referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
1 Dock Displays the control at most top / left / right / bottom side of the form.
Syntax: referencevariable.Dock =
System.Windows.Forms.DockStyle.Optionhere;
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
1 ItemClicked Executes when the user clicks any item in the toolbar.
Options: pixels.
Syntax: referencevariable.Image =
System.Drawing.Image.FromFile(“image file path here”);
False: The control doesn’t work. That means, the control can’t be used by
the user.
2 MouseEnter Executes when the user places the mouse pointer on the toolstrip
button.
3 MouseLeave Executes when the user moves the mouse pointer out of the toolstrip
button.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace ToolStripExample
{
public partial class Form1 : Form
{
TextBox textbox1;
ToolStrip toolstrip1;
ToolStripButton menuitem1, menuitem2, menuitem3;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(900, 400);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 40);
textbox1.Location = new Point(200, 100);
textbox1.Text = "Your text here";
this.Controls.Add(textbox1);
/* toolstrip1 */
toolstrip1 = new ToolStrip();
toolstrip1.Dock = DockStyle.Top;
toolstrip1.BackColor = Color.LightGreen;
this.Controls.Add(toolstrip1);
/* menuitem1 */
menuitem1 = new ToolStripButton();
menuitem1.Text = "Bold";
menuitem1.Image = Image.FromFile(@"C:\CSharp\b.png");
menuitem1.Click += Menuitem1_Click;
toolstrip1.Items.Add(menuitem1);
/* menuitem2 */
menuitem2 = new ToolStripButton();
menuitem2.Text = "Italic";
menuitem2.Image = Image.FromFile(@"C:\CSharp\i.png");
menuitem2.Click += Menuitem2_Click;
toolstrip1.Items.Add(menuitem2);
/* menuitem3 */
menuitem3 = new ToolStripButton();
menuitem3.Text = "Underline";
menuitem3.Image = Image.FromFile(@"C:\CSharp\u.png");
menuitem3.Click += Menuitem3_Click;
toolstrip1.Items.Add(menuitem3);
}
private void Menuitem1_Click(object sender, EventArgs e)
{
textbox1.Font = new Font("Tahoma", 20, FontStyle.Bold);
}
private void Menuitem2_Click(object sender, EventArgs e)
{
textbox1.Font = new Font("Tahoma", 20, FontStyle.Italic);
}
private void Menuitem3_Click(object sender, EventArgs e)
{
textbox1.Font = new Font("Tahoma", 20, FontStyle.Underline);
}
}
}
Output
• The “StatusStrip” class / control is used to display a statusbar at the top of the form.
o using System.Windows.Forms;
o StatusStrip referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
1 Dock Displays the control at most top / left / right / bottom side of the form.
Syntax: referencevariable.Dock =
System.Windows.Forms.DockStyle.Optionhere;
Options: pixels.
Options: pixels
False: The control doesn’t work. That means, the control can’t be used by the
user.
1 ItemClicked Executes when the user clicks any item in the statusbar.
Options: pixels.
Syntax: referencevariable.Image =
System.Drawing.Image.FromFile(“image file path here”);
False: The control doesn’t work. That means, the control can’t be used by
the user.
1 Click Executes when the user clicks on the toolstrip status label.
2 MouseEnter Executes when the user places the mouse pointer on the toolstrip
status label.
3 MouseLeave Executes when the user moves the mouse pointer out of the toolstrip
status label.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace StatusStripExample
{
public partial class Form1 : Form
{
TextBox textbox1;
StatusStrip statusstrip1;
ToolStripStatusLabel toolstripstatuslabel1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(900, 400);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 40);
textbox1.Location = new Point(200, 100);
/* statusstrip1 */
statusstrip1 = new StatusStrip();
statusstrip1.Dock = DockStyle.Bottom;
statusstrip1.BackColor = Color.LightGreen;
statusstrip1.Font = new Font("Tahoma", 14);
this.Controls.Add(statusstrip1);
/* toolstripstatuslabel1 */
toolstripstatuslabel1 = new ToolStripStatusLabel();
toolstripstatuslabel1.Text = "Ready";
statusstrip1.Items.Add(toolstripstatuslabel1);
}
Output
Type something in the textbox, it shows the same in the status bar.
• The “RichTextBox” class / control is used to create a text editor application such as
“Wordpad”.
o using System.Windows.Forms;
o RichTextBox referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Add event:
o referencevariable.event += method ;
o this.Controls.Add( referencevariable );
Options: pixels.
Options: pixels
Syntax: referencevariable.Cursor =
System.Windows.Forms.Cursors.Hand;
False: The control doesn’t work. That means, the control can’t be used
by the user.
13 Dock Displays the control at most top / left / right / bottom side of the
form.
Syntax: referencevariable.Dock =
System.Windows.Forms.DockStyle.Optionhere;
Syntax: referencevariable.SelectionBackColor =
System.Drawing.Color.Green;
Syntax: referencevariable.SelectionColor =
System.Drawing.Color.Green;
5 KeyPress Executes when the user presses any key on the keyboard (before
accepting the character into the textbox).
Syntax: referencevariable.Clear();
Syntax: referencevariable.SelectAll();
Syntax: referencevariable.Cut();
Syntax: referencevariable.Copy();
Syntax: referencevariable.Paste()
Syntax: referencevariable.Undo()
Syntax: referencevariable.Undo()
8 LoadFile() Opens an existing rtf file and displays the text in the richtextbox.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace RichTextBoxExample
{
public partial class Form1 : Form
{
string filename = "Untitled";
RichTextBox richtextbox1;
MenuStrip menustrip1;
ToolStripMenuItem filetoolstripmenuitem, newtoolstripmenuitem,
opentoolstripmenuitem, savetoolstripmenuitem, exittoolstripmenuitem,
edittoolstripmenuitem, undotoolstripmenuitem, redotoolstripmenuitem,
cuttoolstripmenuitem, copytoolstripmenuitem, pastetoolstripmenuitem,
selectalltoolstripmenuitem, formattoolstripmenuitem,
fonttoolstripmenuitem, backgroundcolortoolstripmenuitem,
foregroundcolortoolstripmenuitem;
OpenFileDialog openfiledialog1;
SaveFileDialog savefiledialog1;
FontDialog fontdialog1;
ColorDialog colordialog1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.WindowState = FormWindowState.Maximized;
this.Text = filename;
this.FormClosing += Form1_FormClosing;
/* richtextbox */
richtextbox1 = new RichTextBox();
richtextbox1.Dock = DockStyle.Fill;
richtextbox1.TextChanged += Richtextbox1_TextChanged;
this.Controls.Add(richtextbox1);
/* menustrip1 */
menustrip1 = new MenuStrip();
this.Controls.Add(menustrip1);
/* filetoolstripmenuitem */
filetoolstripmenuitem = new ToolStripMenuItem();
filetoolstripmenuitem.Text = "&File";
menustrip1.Items.Add(filetoolstripmenuitem);
/* edittoolstripmenuitem */
edittoolstripmenuitem = new ToolStripMenuItem();
edittoolstripmenuitem.Text = "&Edit";
menustrip1.Items.Add(edittoolstripmenuitem);
/* formattoolstripmenuitem */
formattoolstripmenuitem = new ToolStripMenuItem();
formattoolstripmenuitem.Text = "F&ormat";
menustrip1.Items.Add(formattoolstripmenuitem);
/* newtoolstripmenuitem */
newtoolstripmenuitem = new ToolStripMenuItem();
newtoolstripmenuitem.Text = "&New";
newtoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control | Keys.N);
newtoolstripmenuitem.Click += Newtoolstripmenuitem_Click;
filetoolstripmenuitem.DropDownItems.Add(newtoolstripmenuitem);
/* opentoolstripmenuitem */
opentoolstripmenuitem = new ToolStripMenuItem();
opentoolstripmenuitem.Text = "&Open";
opentoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control |
Keys.O);
opentoolstripmenuitem.Click += Opentoolstripmenuitem_Click;
filetoolstripmenuitem.DropDownItems.Add(opentoolstripmenuitem);
/* savetoolstripmenuitem */
savetoolstripmenuitem = new ToolStripMenuItem();
savetoolstripmenuitem.Text = "&Save";
savetoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control | Keys.S);
savetoolstripmenuitem.Click += Savetoolstripmenuitem_Click;
filetoolstripmenuitem.DropDownItems.Add(savetoolstripmenuitem);
/* exittoolstripmenuitem */
exittoolstripmenuitem = new ToolStripMenuItem();
exittoolstripmenuitem.Text = "E&xit";
exittoolstripmenuitem.Click += Exittoolstripmenuitem_Click;
filetoolstripmenuitem.DropDownItems.Add(exittoolstripmenuitem);
/* undotoolstripmenuitem */
undotoolstripmenuitem = new ToolStripMenuItem();
undotoolstripmenuitem.Text = "&Undo";
undotoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control |
Keys.Z);
undotoolstripmenuitem.Click += Undotoolstripmenuitem_Click;
edittoolstripmenuitem.DropDownItems.Add(undotoolstripmenuitem);
/* redotoolstripmenuitem */
redotoolstripmenuitem = new ToolStripMenuItem();
redotoolstripmenuitem.Text = "&Redo";
redotoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control | Keys.Y);
redotoolstripmenuitem.Click += Redotoolstripmenuitem_Click;
edittoolstripmenuitem.DropDownItems.Add(redotoolstripmenuitem);
/* cuttoolstripmenuitem */
cuttoolstripmenuitem = new ToolStripMenuItem();
cuttoolstripmenuitem.Text = "Cu&t";
cuttoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control | Keys.X);
cuttoolstripmenuitem.Click += Cuttoolstripmenuitem_Click;
edittoolstripmenuitem.DropDownItems.Add(cuttoolstripmenuitem);
/* copytoolstripmenuitem */
copytoolstripmenuitem = new ToolStripMenuItem();
copytoolstripmenuitem.Text = "&Copy";
copytoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control | Keys.C);
copytoolstripmenuitem.Click += Copytoolstripmenuitem_Click;
edittoolstripmenuitem.DropDownItems.Add(copytoolstripmenuitem);
/* pastetoolstripmenuitem */
pastetoolstripmenuitem = new ToolStripMenuItem();
pastetoolstripmenuitem.Text = "&Paste";
pastetoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control |
Keys.V);
pastetoolstripmenuitem.Click += Pastetoolstripmenuitem_Click;
edittoolstripmenuitem.DropDownItems.Add(pastetoolstripmenuitem);
/* selectalltoolstripmenuitem */
selectalltoolstripmenuitem = new ToolStripMenuItem();
selectalltoolstripmenuitem.Text = "Select &All";
selectalltoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control |
Keys.A);
selectalltoolstripmenuitem.Click += Selectalltoolstripmenuitem_Click;
edittoolstripmenuitem.DropDownItems.Add(selectalltoolstripmenuitem);
/* fonttoolstripmenuitem */
fonttoolstripmenuitem = new ToolStripMenuItem();
fonttoolstripmenuitem.Text = "&Font";
fonttoolstripmenuitem.ShortcutKeys = (Keys)(Keys.Control | Keys.F);
fonttoolstripmenuitem.Click += Fonttoolstripmenuitem_Click;
formattoolstripmenuitem.DropDownItems.Add(fonttoolstripmenuitem);
/* backgroundcolortoolstripmenuitem */
backgroundcolortoolstripmenuitem = new ToolStripMenuItem();
backgroundcolortoolstripmenuitem.Text = "&Background Color";
backgroundcolortoolstripmenuitem.Click +=
Backgroundcolortoolstripmenuitem_Click;
formattoolstripmenuitem.DropDownItems.Add(backgroundcolortoolstrip
menuitem);
/* foregroundcolortoolstripmenuitem */
foregroundcolortoolstripmenuitem = new ToolStripMenuItem();
foregroundcolortoolstripmenuitem.Text = "&Foreground Color";
foregroundcolortoolstripmenuitem.Click +=
Foregroundcolortoolstripmenuitem_Click;
formattoolstripmenuitem.DropDownItems.Add(foregroundcolortoolstrip
menuitem);
/* openfiledialog1 */
openfiledialog1 = new OpenFileDialog();
openfiledialog1.Filter = "Rich Text Files|*.rtf|Text Files|*.txt";
openfiledialog1.FilterIndex = 0;
/* savefiledialog1 */
savefiledialog1 = new SaveFileDialog();
savefiledialog1.Filter = "Rich Text Files|*.rtf|Text Files|*.txt";
savefiledialog1.FilterIndex = 0;
/* fontdialog1 */
fontdialog1 = new FontDialog();
/* colordialog1 */
colordialog1 = new ColorDialog();
}
richtextbox1.Clear();
filename = "Untitled";
this.Text = filename;
}
else if (dr == DialogResult.No)
{
richtextbox1.Clear();
filename = "Untitled";
this.Text = filename;
}
else if (dr == DialogResult.Cancel)
{
//empty
}
}
else
{
richtextbox1.Clear();
filename = "Untitled";
this.Text = filename;
}
}
private void Opentoolstripmenuitem_Click(object sender, EventArgs e)
{
if (this.Text.EndsWith("*") == true)
{
DialogResult dr = MessageBox.Show("Do you want to save
changes?", "RichTextBox Example", MessageBoxButtons.YesNoCancel);
if (dr == DialogResult.Yes)
{
save();
this.Text = filename;
}
}
}
private void Savetoolstripmenuitem_Click(object sender, EventArgs e)
{
save();
}
}
private void Selectalltoolstripmenuitem_Click(object sender,
EventArgs e)
{
richtextbox1.SelectAll();
}
}
}
Output
User Controls
UserControls
• .NET provides a set of pre-defined controls, which are enough for most of the regular
application development. In large-scale applications, we may want to customize the
existing controls. Then we will create child classes for existing control classes such as
Label, TextBox, ComboBox.
• The UserControls are child classes that are created based on existing control classes such
as Label, TextBox, ComboBox etc.
• In the user controls, we can define additional properties, methods, events and also override
existing properties and methods.
Creating Project
• Click on OK.
• Open solution explorer. Right click on the project name (UserControlsExample) and click
on “Add” – “New Item” – “Windows Forms” – “User Control”. Type the file name as
“AlphabeticTextBox.cs”. Click on “Add”. Right click on the user control and click on “View
Code”.
AlphabeticTextBox.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace UserControlsExample
{
public partial class AlphabeticTextBox : TextBox
{
public AlphabeticTextBox()
{
InitializeComponent();
this.KeyPress += AlphabeticTextBox_KeyPress;
}
AlphabeticTextBox.Designer.cs
“AlphabeticTextBox.Designer.cs”.
namespace UserControlsExample
{
partial class AlphabeticTextBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be
disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
//this.AutoScaleMode =
System.Windows.Forms.AutoScaleMode.Font;
}
#endregion
}
}
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace UserControlsExample
{
public partial class Form1 : Form
{
Label label1;
AlphabeticTextBox alphabetictextbox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(750, 400);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Location = new Point(100, 100);
label1.Text = "Alphabets only: ";
this.Controls.Add(label1);
/* alphabetictextbox1 */
alphabetictextbox1 = new AlphabeticTextBox();
alphabetictextbox1.Location = new Point(330, 100);
alphabetictextbox1.Size = new Size(300, 100);
this.Controls.Add(alphabetictextbox1);
}
}
}
Output
• “Windows Forms Control Library” is a collection of user controls, which can be used in
• Windows Forms Control Library will be compiled into a dll file. We can add the reference of
the dll (Dynamic Link Library) file into the windows forms applications & call all the user
• Click on OK.
• Open solution explorer. Right click on the user control file (UserControl1.cs) and click on
“Rename”. Type the file name as “YearComboBox.cs” and press Enter. Right click on the
YearComboBox.cs
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsControlLibrary1
{
public partial class YearComboBox: ComboBox
{
public YearComboBox()
{
InitializeComponent();
this.Items.AddRange(years.ToArray());
}
}
}
YearComboBox.Designer.cs
“YearComboBox.Designer.cs”.
namespace WindowsFormsControlLibrary1
{
partial class YearComboBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be
disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
//this.AutoScaleMode =
System.Windows.Forms.AutoScaleMode.Font;
}
#endregion
}
}
C:\CSharp\WindowsFormsControlLibrary1\WindowsFormsControlLibrary1\bin\
Debug\WindowsFormsControlLibrary1.dll
• Click on OK.
• Open solution explorer. Right click on the project name (WindowsFormsApplication1) and
“C:\CSharp\WindowsFormsControlLibrary1\WindowsFormsControlLibrary1\bin\Debug\
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using WindowsFormsControlLibrary1;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
YearComboBox yearcombobox;
public Form1()
{
InitializeComponent();
/* yearcombobox1 */
yearcombobox = new YearComboBox();
yearcombobox.DropDownStyle = ComboBoxStyle.DropDownList;
yearcombobox.Location = new Point(50, 50);
yearcombobox.Size = new Size(100, 50);
this.Controls.Add(yearcombobox);
}
}
}
Output
“System.Net.Mail.SmtpClient” class
The “System.Net.Mail.SmtpClient” class
1 EnableSsl Enables “Security Socket Layer (SSL)”, that means “HTTPS” (HTTP with
Security).
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
namespace SmtpExample
{
public partial class Form1 : Form
{
Label labelFromEmail, labelFromPassword, labelToEmail, labelSubject,
labelBody;
TextBox textboxFromEmail, textboxFromPassword, textboxToEmail,
textboxSubject, textboxBody;
Button buttonSend;
public Form1()
{
InitializeComponent();
/* labelFromEmail */
labelFromEmail = new Label();
labelFromEmail.Text = "From Email:";
labelFromEmail.AutoSize = true;
labelFromEmail.Location = new Point(50, 50);
this.Controls.Add(labelFromEmail);
/* labelFromPassword */
labelFromPassword = new Label();
labelFromPassword.Text = "From Password:";
labelFromPassword.AutoSize = true;
labelFromPassword.Location = new Point(50, 120);
this.Controls.Add(labelFromPassword);
/* labelToEmail */
labelToEmail = new Label();
labelToEmail.Text = "To Email:";
labelToEmail.AutoSize = true;
labelToEmail.Location = new Point(50, 190);
this.Controls.Add(labelToEmail);
/* labelSubject */
labelSubject = new Label();
labelSubject.Text = "Subject:";
labelSubject.AutoSize = true;
labelSubject.Location = new Point(50, 260);
this.Controls.Add(labelSubject);
/* labelBody */
labelBody = new Label();
labelBody.Text = "Body:";
labelBody.AutoSize = true;
labelBody.Location = new Point(50, 330);
this.Controls.Add(labelBody);
/* textboxFromEmail */
textboxFromEmail = new TextBox();
textboxFromEmail.Size = new Size(400, 50);
textboxFromEmail.Location = new Point(300, 50);
this.Controls.Add(textboxFromEmail);
/* textboxFromPassword */
textboxFromPassword = new TextBox();
textboxFromPassword.Size = new Size(400, 50);
/* textboxToEmail */
textboxToEmail = new TextBox();
textboxToEmail.Size = new Size(400, 50);
textboxToEmail.Location = new Point(300, 190);
this.Controls.Add(textboxToEmail);
/* textboxSubject */
textboxSubject = new TextBox();
textboxSubject.Size = new Size(400, 50);
textboxSubject.Location = new Point(300, 260);
this.Controls.Add(textboxSubject);
/* textboxBody */
textboxBody = new TextBox();
textboxBody.Size = new Size(400, 150);
textboxBody.Location = new Point(300, 330);
textboxBody.Multiline = true;
textboxBody.ScrollBars = ScrollBars.Vertical;
this.Controls.Add(textboxBody);
/* buttonSend */
buttonSend = new Button();
buttonSend.Text = "Send";
buttonSend.Size = new Size(200, 50);
buttonSend.Location = new Point(300, 500);
buttonSend.Click += ButtonSend_Click;
this.Controls.Add(buttonSend);
}
sc.Port = 587;
sc.Credentials = new NetworkCredential(textboxFromEmail.Text,
textboxFromPassword.Text);
sc.Send(textboxFromEmail.Text, textboxToEmail.Text,
textboxSubject.Text, textboxBody.Text);
MessageBox.Show("Sent");
}
}
}
Output
Multi-Threading
Multi Threading
• A “thread” represents a method, that can be executed in background, without effecting the
• Example 1: Calculating folder size in the folder properties dialog box in windows explorer.
o using System.Threading;
o Thread referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call method:
o referencevariable.methodname ();
2 CurrentCulture Represents current culture of the current thread. This is useful for
“Internationalization” only.
Syntax: referencevariable.CurrentCulture;
Syntax: referencevariable.CurrentUICulture
Syntax: referencevariable.Priority =
System.Threading.ThreadPriority.OptionHere;
Syntax: referencevariable.Start();
Syntax: referencevariable.Suspend();
Syntax: referencevariable.Resume();
Syntax: referencevariable.Stop();
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Threading;
using System.Drawing;
namespace MultiThreadingExample
{
public partial class Form1 : Form
{
Thread th;
Label lbl;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 30);
this.Size = new Size(800, 400);
this.Load += Form1_Load;
/* label1 */
lbl = new Label();
lbl.Text = "1";
lbl.AutoSize = true;
lbl.Location = new Point(100, 100);
lbl.Font = new Font("Tahoma", 40);
this.Controls.Add(lbl);
}
private void Form1_Load(object sender, EventArgs e)
{
/* multi threading */
th = new Thread(mymethod);
th.IsBackground = true;
th.Start();
}
{
}
}
}
public void mymethod2()
{
int n = Convert.ToInt32(lbl.Text);
n++;
lbl.Text = Convert.ToString(n);
}
}
}
Output
background.
• “Task Parallel Library” is similar to “Multi Threading”; but “TPL” gives best performance in
• Example 1: Calculating folder size in the folder properties dialog box in windows explorer.
o using System.Threading.Tasks;
o Task referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call method:
o referencevariable.methodname ();
Syntax: referencevariable.Task
1 Start() Starts the task execution. That means it calls the method that is associated
with the task.
Syntax: referencevariable.Start()
Creating Project
Form1.cs
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TplExample
{
public partial class Form1 : Form
{
Task t;
Label lbl;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 30);
this.Size = new Size(800, 400);
this.Load += Form1_Load;
/* label1 */
lbl = new Label();
lbl.Text = "1";
lbl.AutoSize = true;
lbl.Location = new Point(100, 100);
lbl.Font = new Font("Tahoma", 40);
this.Controls.Add(lbl);
}
Output
Windows Services
• Windows Services are non-gui background applications that run in background, even
• Windows services are two types that “starts automatically” and “starts manually”.
o The first type of windows services starts automatically along with windows
o The other type of windows services will be started manually going to Control Panel
– System and Security – Administrative Tools – Services and right click on the
• Windows services are used to perform any continuous work such as sending e-mails for
• Examples of built-in windows services: Anti-virus programs, windows time, windows audio,
“System.ServiceProcess.ServiceBase” class.
• The “ServiceBase” class provides two virtual methods that can be implemented in the child
class:
1. OnStart(): This method executes when the user starts the windows service
automatically / manually.
2. OnStop(): This method executes when the user stops the windows service
automatically / manually.
• Click on OK.
Service1.cs
using System;
using System.Net;
using System.Net.Mail;
using System.ServiceProcess;
using System.Threading;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
Thread th1;
Adding “ProjectInstaller.cs”
• Go to “Service1.cs [Design]”.
• Right click on the empty area and click on “Add Installer”. It automatically creates
“ProjectInstaller.cs” file.
o serviceInstaller1
o serviceProcessInstaller1
• Right click on “serviceInstaller1” and click on “Properties”. Set the following properties:
o StartType = Manual
properties:
o Account = LocalSystem
C:\CSharp\WindowsService1\WindowsService1\bin\Debug\WindowsService1.exe
Command Prompt for VS 2015” and click on “Run as administrator”. Click on “Yes”.
o Press Enter.
• It shows “Automatic Emails Service”. Right click on the “Automatic Emails Service”
windows service and click on “Start”. The windows service will be started within few
seconds.
▪ Password: training123#
“Services”.
• It shows “Automatic Emails Service”. Right click on the “Automatic Emails Service”
windows service and click on “Stop”. The windows service will be stopped within few
seconds.
Command Prompt for VS 2015” and click on “Run as administrator”. Click on “Yes”.
o Press Enter.
C#.NET – WinForms –
System.IO Namespace
o C:\CSharp
▪ Sample.pdf
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace FileInfoExample
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.WindowState = FormWindowState.Maximized;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "label1";
label1.Location = new Point(100, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "label2";
label2.Location = new Point(100, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "label3";
label3.Location = new Point(100, 150);
this.Controls.Add(label3);
/* label4 */
label4 = new Label();
label4.AutoSize = true;
label4.Text = "label4";
label4.Location = new Point(100, 200);
this.Controls.Add(label4);
/* label5 */
label5 = new Label();
label5.AutoSize = true;
label5.Text = "label5";
label5.Location = new Point(100, 250);
this.Controls.Add(label5);
/* label6 */
label6 = new Label();
label6.AutoSize = true;
label6.Text = "label6";
label6.Location = new Point(100, 300);
this.Controls.Add(label6);
/* label7 */
label7 = new Label();
label7.AutoSize = true;
label7.Text = "label7";
label7.Location = new Point(100, 350);
this.Controls.Add(label7);
/* label8 */
label8 = new Label();
label8.AutoSize = true;
label8.Text = "label8";
label8.Location = new Point(100, 400);
this.Controls.Add(label8);
/* label9 */
label9 = new Label();
label9.AutoSize = true;
label9.Text = "label9";
label9.Location = new Point(100, 450);
this.Controls.Add(label9);
/* label10 */
label10 = new Label();
label10.AutoSize = true;
label10.Text = "label10";
label10.Location = new Point(100, 500);
this.Controls.Add(label10);
/* label11 */
label11 = new Label();
label11.AutoSize = true;
label11.Text = "label11";
label11.Location = new Point(100, 550);
this.Controls.Add(label11);
/* FileInfo */
FileInfo finfo = new FileInfo(@"C:\CSharp\Sample.pdf");
string a = finfo.DirectoryName;
string b = finfo.Name;
string c = finfo.Extension;
string d = finfo.FullName;
bool e = finfo.Exists;
long f = finfo.Length;
DateTime g = finfo.CreationTime;
DateTime h = finfo.LastAccessTime;
DateTime i = finfo.LastWriteTime;
string j = finfo.Attributes.ToString();
bool k = finfo.IsReadOnly;
Output
o C:\CSharp
▪ sample
• firstfolder (folder)
• secondfolder (folder)
• thirdfolder (folder)
• Click on OK.
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace DirectoryInfoExample
{
public partial class Form1 : Form
{
Label label1, label2, label3, label4, label5, label6, label7, label8, label9,
label10, label11;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.WindowState = FormWindowState.Maximized;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "label1";
label1.Location = new Point(100, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "label2";
label2.Location = new Point(100, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "label3";
label3.Location = new Point(100, 150);
this.Controls.Add(label3);
/* label4 */
label4 = new Label();
label4.AutoSize = true;
label4.Text = "label4";
label4.Location = new Point(100, 200);
this.Controls.Add(label4);
/* label5 */
label5 = new Label();
label5.AutoSize = true;
label5.Text = "label5";
label5.Location = new Point(100, 250);
this.Controls.Add(label5);
/* label6 */
label6 = new Label();
label6.AutoSize = true;
label6.Text = "label6";
label6.Location = new Point(100, 300);
this.Controls.Add(label6);
/* label7 */
label7 = new Label();
label7.AutoSize = true;
label7.Text = "label7";
label7.Location = new Point(100, 350);
this.Controls.Add(label7);
/* label8 */
label8 = new Label();
label8.AutoSize = true;
label8.Text = "label8";
label8.Location = new Point(100, 400);
this.Controls.Add(label8);
/* label9 */
label9 = new Label();
label9.AutoSize = true;
label9.Text = "label9";
label9.Location = new Point(100, 450);
this.Controls.Add(label9);
/* label10 */
label10 = new Label();
label10.AutoSize = true;
label10.Text = "label10";
label10.Location = new Point(100, 500);
this.Controls.Add(label10);
/* label11 */
label11 = new Label();
label11.AutoSize = true;
label11.Text = "label11";
label11.Location = new Point(100, 550);
this.Controls.Add(label11);
/* DirectoryInfo */
DirectoryInfo dinfo = new DirectoryInfo(@"C:\CSharp\myfolder");
string a = dinfo.Parent.FullName;
string b = dinfo.Name;
string c = dinfo.FullName;
string d = dinfo.Root.FullName;
bool e = dinfo.Exists;
DateTime f = dinfo.CreationTime;
DateTime g = dinfo.LastAccessTime;
DateTime h = dinfo.LastWriteTime;
string i = dinfo.Attributes.ToString();
string temp1 = "", temp2 = "";
FileInfo[] files = dinfo.GetFiles();
DirectoryInfo[] directories = dinfo.GetDirectories();
foreach (FileInfo file in files)
{
temp1 = temp1 + file.Name + ", ";
}
foreach (DirectoryInfo directory in directories)
{
temp2 = temp2 + directory.Name + ", ";
}
Output
o C:\CSharp
▪ Sample (folder)
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace DirectoryExample
{
public partial class Form1 : Form
{
Button button1, button2, button3;
string folderpath = @"C:\CSharp\Sample";
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 400);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Create";
button1.Location = new Point(50, 150);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* button2 */
button2 = new Button();
button2.AutoSize = true;
button2.Text = "Delete";
button2.Location = new Point(200, 150);
button2.Click += Button2_Click;
this.Controls.Add(button2);
/* button3 */
button3 = new Button();
button3.AutoSize = true;
button3.Text = "Move";
button3.Location = new Point(350, 150);
button3.Click += Button3_Click;
this.Controls.Add(button3);
}
if (Directory.Exists(folderpath) == true)
{
MessageBox.Show("Folder already exists");
}
else
{
Directory.CreateDirectory(folderpath);
MessageBox.Show("Folder created");
}
}
}
Directory.Move(folderpath, @"C:\CSharp\folder2\sample");
MessageBox.Show("Folder moved");
}
else
{
MessageBox.Show("Folder not exists. Create the Folder first.");
}
}
}
}
Output
o C:\CSharp
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace FileExample
{
public partial class Form1 : Form
{
Button button1, button2, button3, button4;
string filepath = @"C:\CSharp\Sample.txt";
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 400);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Create";
button1.Location = new Point(50, 150);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* button2 */
button2 = new Button();
button2.AutoSize = true;
button2.Text = "Delete";
button2.Location = new Point(200, 150);
button2.Click += Button2_Click;
this.Controls.Add(button2);
/* button3 */
button3 = new Button();
button3.AutoSize = true;
button3.Text = "Move";
button3.Location = new Point(350, 150);
button3.Click += Button3_Click;
this.Controls.Add(button3);
/* button4 */
button4 = new Button();
button4.AutoSize = true;
button4.Text = "Copy";
button4.Location = new Point(500, 150);
button4.Click += Button4_Click;
this.Controls.Add(button4);
}
private void Button1_Click(object sender, EventArgs e)
{
/* Create File */
if (File.Exists(filepath) == true)
{
MessageBox.Show("File already exists");
}
else
{
FileStream fs = File.Create(filepath);
fs.Close();
MessageBox.Show("File created");
}
}
private void Button2_Click(object sender, EventArgs e)
{
/* Delete File */
if (File.Exists(filepath) == true)
{
File.Delete(filepath);
MessageBox.Show("File deleted");
}
else
{
MessageBox.Show("File not exists. Create the file first.");
}
}
private void Button3_Click(object sender, EventArgs e)
{
/* Move File */
if (File.Exists(filepath) == true)
{
if (Directory.Exists(@"C:\CSharp\folder2") == false)
{
Directory.CreateDirectory(@"C:\CSharp\folder2");
}
if (File.Exists(@"C:\CSharp\folder2\sample.txt") == true)
{
File.Delete(@"C:\CSharp\folder2\sample.txt");
}
File.Move(filepath, @"C:\CSharp\folder2\sample.txt");
MessageBox.Show("File moved");
}
else
{
MessageBox.Show("File not exists. Create the file first.");
}
}
private void Button4_Click(object sender, EventArgs e)
{
/* Copy File */
if (File.Exists(filepath) == true)
{
if (Directory.Exists(@"C:\CSharp\folder2") == false)
{
Directory.CreateDirectory(@"C:\CSharp\folder2");
}
if (File.Exists(@"C:\CSharp\folder2\sample.txt") == true)
{
File.Delete(@"C:\CSharp\folder2\sample.txt");
}
File.Copy(filepath, @"C:\CSharp\folder2\sample.txt");
MessageBox.Show("File copied");
}
else
{
MessageBox.Show("File not exists. Create the file first.");
}
}
}
}
Output
o C:\CSharp
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace StreamWriterExample
{
public partial class Form1 : Form
{
Label label1;
TextBox textbox1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(900, 600);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Enter your file content here:";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(800, 340);
textbox1.Location = new Point(50, 100);
textbox1.Multiline = true;
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.Text = "Save";
button1.AutoSize = true;
button1.Location = new Point(50, 480);
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
private void Button1_Click(object sender, EventArgs e)
{
string filepath = @"C:\CSharp\sample.txt";
FileInfo finfo = new FileInfo(filepath);
if (finfo.Exists == true)
{
finfo.Delete();
}
FileStream fs = new FileStream(filepath, FileMode.Create,
FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write(textbox1.Text);
sw.Close();
MessageBox.Show("Saved");
}
}
}
Output
o C:\CSharp
Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace StreamReaderExample
{
public partial class Form1 : Form
{
Label label1;
TextBox textbox1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(900, 600);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Enter your file content appears here:";
label1.Location = new Point(50, 100);
this.Controls.Add(label1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(800, 340);
textbox1.Location = new Point(50, 150);
textbox1.Multiline = true;
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.Text = "Open";
button1.AutoSize = true;
button1.Location = new Point(50, 20);
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
Output
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace WindowsAuthExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "SqlConnection - Windows Authentication";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Connect to SQL Server";
button1.AutoSize = true;
button1.Location = new Point(100, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
//create object
cn = new SqlConnection();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
//calling methods
MessageBox.Show(cn.State.ToString()); //Output: Closed
cn.Open();
MessageBox.Show(cn.State.ToString()); //Output: Open
cn.Close();
MessageBox.Show(cn.State.ToString()); //Output: Closed
}
}
}
Running the Project
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace SqlServerAuthExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "SqlConnection - SqlServer Authentication";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Connect to SQL Server";
button1.AutoSize = true;
button1.Location = new Point(100, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
//create object
cn = new SqlConnection();
//calling properties
cn.ConnectionString = "data source=localhost; user id=sa;
password=123; initial catalog=company";
//calling methods
MessageBox.Show(cn.State.ToString()); //Output: Closed
cn.Open();
MessageBox.Show(cn.State.ToString()); //Output: Open
cn.Close();
MessageBox.Show(cn.State.ToString()); //Output: Closed
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace ExecuteScalarExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select EmpName from Employees where
EmpID=1";
cmd.Connection = cn;
/* call methods */
cn.Open();
object obj = cmd.ExecuteScalar();
cn.Close();
string n = Convert.ToString(obj);
string msg = "Emp Name: " + n;
MessageBox.Show(msg);
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace ExecuteScalarExample2
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "Execute Scalar";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Execute Scalar";
button1.AutoSize = true;
button1.Location = new Point(130, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
/* call methods */
cn.Open();
object obj = cmd.ExecuteScalar();
cn.Close();
string n = Convert.ToString(obj);
string msg = "Emps Count: " + n;
MessageBox.Show(msg);
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace COMSingleRecordExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees where empid=1";
cmd.Connection = cn;
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
object obj1, obj2, obj3;
obj1 = dr["EmpID"];
obj2 = dr["EmpName"];
obj3 = dr["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
cn.Close();
}
}
}
Output
Click on OK.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace COMMultipleRecordsExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "Connection Oriented Model - Multiple Records";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
MessageBox.Show(msg);
}
cn.Close();
}
}
}
Output
Click on OK.
Click on OK.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace COMMultipleRecordsLabelExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "Connection Oriented Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.AutoScroll = true;
this.Load += Form1_Load;
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
int n = 50;
while (dr.Read())
{
object obj1, obj2, obj3;
obj1 = dr["EmpID"];
obj2 = dr["EmpName"];
obj3 = dr["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Label label1, label2, label3;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = Convert.ToString(eid);
label1.Location = new Point(50, n);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = ename;
label2.Location = new Point(150, n);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = Convert.ToString(sal);
label3.Location = new Point(350, n);
this.Controls.Add(label3);
/* go to next row */
n += 50;
}
cn.Close();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace COMSqlParameterExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 470);
this.Text = "Connection Oriented Model - with SqlParameter";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 200);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary: ";
label3.Location = new Point(50, 300);
this.Controls.Add(label3);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 50);
textbox1.Location = new Point(250, 50);
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "OK";
button1.Location = new Point(250, 100);
button1.Click += Button1_Click;
this.AcceptButton = button1;
this.Controls.Add(button1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(200, 50);
textbox2.Location = new Point(250, 200);
textbox2.ReadOnly = true;
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(200, 50);
textbox3.Location = new Point(250, 300);
textbox3.ReadOnly = true;
this.Controls.Add(textbox3);
}
SqlDataReader dr;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees where
empid=@EmpID";
cmd.Connection = cn;
p1.ParameterName = "@EmpID";
p1.Value = textbox1.Text;
cmd.Parameters.Add(p1);
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
object obj1, obj2;
obj1 = dr["EmpName"];
obj2 = dr["Salary"];
string ename;
decimal sal;
ename = Convert.ToString(obj1);
sal = Convert.ToDecimal(obj2);
textbox2.Text = ename;
textbox3.Text = Convert.ToString(sal);
}
else
{
textbox2.Text = "";
textbox3.Text = "";
MessageBox.Show("No data found");
}
cn.Close();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace COMWithComboBoxExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
ComboBox combobox1;
TextBox textbox1, textbox2;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 470);
this.Text = "Connection Oriented Model - with SqlParameter";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 150);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary: ";
label3.Location = new Point(50, 250);
this.Controls.Add(label3);
/* combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(200, 50);
combobox1.Location = new Point(250, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 50);
textbox1.ReadOnly = true;
textbox1.Location = new Point(250, 150);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(200, 50);
textbox2.Location = new Point(250, 250);
textbox2.ReadOnly = true;
this.Controls.Add(textbox2);
}
SqlDataReader dr;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
object obj1;
obj1 = dr["EmpID"];
int eid;
eid = Convert.ToInt32(obj1);
combobox1.Items.Add(eid);
}
cn.Close();
}
/* create objects */
cn = new SqlConnection();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees where
empid=@EmpID";
cmd.Connection = cn;
p1.ParameterName = "@EmpID";
p1.Value = combobox1.SelectedItem;
cmd.Parameters.Add(p1);
/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
object obj1, obj2;
obj1 = dr["EmpName"];
obj2 = dr["Salary"];
string ename;
decimal sal;
ename = Convert.ToString(obj1);
sal = Convert.ToDecimal(obj2);
textbox1.Text = ename;
textbox2.Text = Convert.ToString(sal);
}
else
{
textbox1.Text = "";
textbox2.Text = "";
MessageBox.Show("No data found");
cn.Close();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
DataSet - Example
Creating Project
• Click on OK.
Form1.cs
/* Expected data:
Categories:
CategoryID CategoryName
1 ab
2 cd
Products:
ProductID ProductName Cost
101 prod1 400
102 prod2 500
103 prd3 600
*/
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
namespace DataSetExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
//creating 2 tables
DataTable dt1 = new DataTable() { TableName = "Categories" };
DataTable dt2 = new DataTable() { TableName = "Products" };
dt1.Columns.Add(col2);
Output
It shows data:
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace DisconnectedModelExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.AutoScroll = true;
this.Load += Form1_Load;
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
int n = 50;
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = Convert.ToString(eid);
label1.Location = new Point(50, n);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = ename;
label2.Location = new Point(150, n);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = Convert.ToString(sal);
label3.Location = new Point(350, n);
this.Controls.Add(label3);
/* go to next row */
n += 50;
}
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
use departmentsandemployeesdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace MultipleTablesExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(700, 500);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.AutoScroll = true;
this.Load += Form1_Load;
}
/* employees */
dt2 = ds.Tables[1];
n += 100;
for (int i = 0; i < dt2.Rows.Count; i++)
{
drow = dt2.Rows[i];
object obj1, obj2, obj3, obj4;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
obj4 = drow["DeptNo"];
int eid;
string ename;
decimal sal;
int dno;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
dno = Convert.ToInt32(obj4);
this.Controls.Add(label3);
/* label4 */
label4 = new Label();
label4.AutoSize = true;
label4.Text = Convert.ToString(dno);
label4.Location = new Point(450, n);
this.Controls.Add(label4);
/* go to next row */
n += 50;
}
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
use departmentsandemployeesdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace JoinsExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(950, 500);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.AutoScroll = true;
this.Load += Form1_Load;
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=departmentsandemployeesdatabase";
cmd.CommandText = "select * from employees inner join
departments on employees.deptno=departments.deptno";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
int n = 50;
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
int dno;
string dname;
string loc;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
dno = Convert.ToInt32(obj4);
dname = Convert.ToString(obj5);
loc = Convert.ToString(obj6);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = Convert.ToString(eid);
label1.Location = new Point(50, n);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = ename;
label2.Location = new Point(150, n);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = Convert.ToString(sal);
label3.Location = new Point(350, n);
this.Controls.Add(label3);
/* label4 */
label4 = new Label();
label4.AutoSize = true;
label4.Text = Convert.ToString(dno);
label4.Location = new Point(450, n);
this.Controls.Add(label4);
/* label5 */
label5 = new Label();
label5.AutoSize = true;
label5.Text = Convert.ToString(dname);
label5.Location = new Point(550, n);
this.Controls.Add(label5);
/* label6 */
label6 = new Label();
label6.AutoSize = true;
label6.Text = Convert.ToString(loc);
label6.Location = new Point(750, n);
this.Controls.Add(label6);
/* go to next row */
n += 50;
}
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace RecordNavigationsExample
{
public partial class Form1 : Form
{
DataTable dt;
DataRow drow;
Label label1, label2, label3, label4;
TextBox textbox1, textbox2, textbox3, textbox4;
Button button1, button2, button3, button4;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Record No: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp ID: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
/* label4 */
label4 = new Label();
label4.AutoSize = true;
label4.Text = "Salary:";
label4.Location = new Point(50, 200);
this.Controls.Add(label4);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.ReadOnly = true;
textbox1.Location = new Point(250, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.ReadOnly = true;
textbox2.Location = new Point(250, 100);
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.ReadOnly = true;
textbox3.Location = new Point(250, 150);
this.Controls.Add(textbox3);
/* textbox4 */
textbox4 = new TextBox();
textbox4.Size = new Size(300, 50);
textbox4.ReadOnly = true;
textbox4.Location = new Point(250, 200);
this.Controls.Add(textbox4);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "First";
button1.Location = new Point(50, 280);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* button2 */
button2 = new Button();
button2.AutoSize = true;
button2.Text = "Previous";
button2.Location = new Point(170, 280);
button2.Click += Button2_Click;
this.Controls.Add(button2);
/* button3 */
button3 = new Button();
button3.AutoSize = true;
button3.Text = "Next";
button3.Location = new Point(350, 280);
button3.Click += Button3_Click;
this.Controls.Add(button3);
/* button4 */
button4 = new Button();
button4.AutoSize = true;
button4.Text = "Last";
button4.Location = new Point(475, 280);
button4.Click += Button4_Click;
this.Controls.Add(button4);
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
//display record
textbox1.Text = "0";
int n = Convert.ToInt32(textbox1.Text);
drow = dt.Rows[n];
textbox2.Text = Convert.ToString(drow["EmpID"]);
textbox3.Text = Convert.ToString(drow["EmpName"]);
textbox4.Text = Convert.ToString(drow["Salary"]);
}
drow = dt.Rows[n];
textbox2.Text = Convert.ToString(drow["EmpID"]);
textbox3.Text = Convert.ToString(drow["EmpName"]);
textbox4.Text = Convert.ToString(drow["Salary"]);
}
textbox4.Text = Convert.ToString(drow["Salary"]);
}
Output
First record appears automatically. Click on “First”, “Previous”, “Next” and “Last” buttons.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace ComboBoxExample
{
public partial class Form1 : Form
{
DataTable dt;
DataRow drow;
Label label1, label2, label3;
TextBox textbox1, textbox2;
ComboBox combobox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(300, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.Location = new Point(250, 50);
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 100);
textbox1.ReadOnly = true;
textbox1.Location = new Point(250, 100);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 150);
textbox2.ReadOnly = true;
textbox2.Location = new Point(250, 150);
this.Controls.Add(textbox2);
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
p1 = new SqlParameter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select empname, salary from Employees where
empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p1.Value = currentempid;
adp.SelectCommand = cmd;
cmd.Parameters.Add(p1);
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
Output
All the EmpID’s appear in the ComboBox. When the user selects an item in the ComboBox, it shows
corresponding EmpName and Salary.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace DataSourceExample
{
public partial class Form1 : Form
{
DataTable dt;
DataRow drow;
Label label1, label2, label3;
TextBox textbox1, textbox2;
ComboBox combobox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(300, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.Location = new Point(250, 50);
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 100);
textbox1.ReadOnly = true;
textbox1.Location = new Point(250, 100);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 150);
textbox2.ReadOnly = true;
textbox2.Location = new Point(250, 150);
this.Controls.Add(textbox2);
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
p1 = new SqlParameter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select empname, salary from Employees where
empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p1.Value = currentempid;
adp.SelectCommand = cmd;
/* call methods */
cmd.Parameters.Add(p1);
adp.Fill(ds);
dt = ds.Tables[0];
Output
All the EmpID’s appear in the ComboBox. When the user selects an item in the ComboBox, it shows
corresponding EmpName and Salary.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace DataGridViewExample
{
public partial class Form1 : Form
{
DataGridView datagridview1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* datagridview1 */
datagridview1 = new DataGridView();
datagridview1.Size = new Size(500, 300);
datagridview1.Location = new Point(50, 50);
datagridview1.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.AllCells;
datagridview1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
this.Controls.Add(datagridview1);
}
private void Form1_Load(object sender, EventArgs e)
{
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace SqlCommandBuilderExample
{
public partial class Form1 : Form
{
SqlDataAdapter adp;
DataTable dt;
DataGridView datagridview1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* datagridview1 */
datagridview1 = new DataGridView();
datagridview1.Size = new Size(500, 200);
datagridview1.Location = new Point(50, 50);
datagridview1.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.AllCells;
datagridview1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
this.Controls.Add(datagridview1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Save";
button1.Location = new Point(470, 280);
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
SqlConnection cn;
SqlCommand cmd;
SqlCommandBuilder cmb;
DataSet ds;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
cmb = new SqlCommandBuilder();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
cmb.DataAdapter = adp;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
Output
Note: If any database connection problem, it shows exception (run time error).
use departmentsandemployeesdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace MasterChildExample
{
public partial class Form1 : Form
{
DataTable dt;
DataGridView datagridview1;
Label label1;
ComboBox combobox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(750, 400);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Dept No: ";
label1.Location = new Point(105, 52);
this.Controls.Add(label1);
/* combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(300, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.Location = new Point(250, 50);
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* datagridview1 */
datagridview1 = new DataGridView();
datagridview1.Size = new Size(600, 200);
datagridview1.Location = new Point(50, 120);
datagridview1.AutoSizeRowsMode =
DataGridViewAutoSizeRowsMode.AllCells;
datagridview1.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
this.Controls.Add(datagridview1);
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=departmentsandemployeesdatabase";
cmd.CommandText = "select * from Departments";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
p1 = new SqlParameter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=departmentsandemployeesdatabase";
cmd.CommandText = "select * from Employees where
DeptNo=@DeptNo";
cmd.Connection = cn;
adp.SelectCommand = cmd;
p1.ParameterName = "@DeptNo";
p1.Value = ((DataRowView)combobox1.SelectedItem)["DeptNo"];
cmd.Parameters.Add(p1);
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
Output
use CountriesAndStatesDatabase
go
CountryName nvarchar(max))
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace CascadingComboBoxExample
{
public partial class Form1 : Form
{
Label label1, label2;
ComboBox combobox1, combobox2;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(750, 400);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Country: ";
label1.Location = new Point(105, 52);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "State: ";
label2.Location = new Point(105, 132);
this.Controls.Add(label2);
/* combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(300, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.Location = new Point(250, 50);
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* combobox2 */
combobox2 = new ComboBox();
combobox2.Size = new Size(300, 50);
combobox2.DropDownStyle = ComboBoxStyle.DropDownList;
combobox2.Location = new Point(250, 130);
this.Controls.Add(combobox2);
}
DataSet ds;
DataTable dt;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=CountriesAndStatesDatabase";
cmd.CommandText = "select * from Countries";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
/*bind data to combobox1*/
combobox1.DataSource = dt;
combobox1.DisplayMember = "CountryName";
combobox1.ValueMember = "CountryID";
}
private void Combobox1_SelectedIndexChanged(object sender,
EventArgs e)
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
SqlParameter p1;
DataSet ds;
DataTable dt;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
p1 = new SqlParameter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=CountriesAndStatesDatabase";
cmd.CommandText = "select * from States where
CountryID=@CountryID";
cmd.Connection = cn;
adp.SelectCommand = cmd;
p1.ParameterName = "@CountryID";
p1.Value = ((DataRowView)combobox1.SelectedItem)["CountryID"];
cmd.Parameters.Add(p1);
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
/*bind data to combobox2*/
combobox2.DataSource = dt;
combobox2.DisplayMember = "StateName";
combobox2.ValueMember = "StateID";
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace InsertionExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "ADO.NET NonQuery";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Insert";
button1.AutoSize = true;
button1.Location = new Point(170, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
Output
Click on “Insert”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
EmpName nvarchar(max),
Salary decimal)
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace UpdationExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "ADO.NET NonQuery";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Update";
button1.AutoSize = true;
button1.Location = new Point(170, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
Output
Click on “Update”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace DeletionExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "ADO.NET NonQuery";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Delete";
button1.AutoSize = true;
button1.Location = new Point(170, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
SqlConnection cn;
SqlCommand cmd;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "delete from Employees where EmpID=3";
cmd.Connection = cn;
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
string msg = n + " rows deleted";
MessageBox.Show(msg);
}
}
}
Output
Click on “Delete”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace InsertionSqlParameterExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "ADO.NET NonQuery - Insertion";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(250, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(250, 150);
this.Controls.Add(textbox3);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Insert";
button1.Location = new Point(250, 200);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace UpdationSqlParameterExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "ADO.NET NonQuery - Updation";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Existing Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(300, 100);
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(300, 150);
this.Controls.Add(textbox3);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Update";
button1.Location = new Point(300, 200);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "update Employees set empname=@empname,
salary=@salary where empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = textbox1.Text;
p2.Value = textbox2.Text;
p3.Value = textbox3.Text;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Enter some existing emp id, new emp name, new salary and click on “Update”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace DeletionSqlParameterExample
{
public partial class Form1 : Form
{
Label label1;
TextBox textbox1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 300);
this.Text = "ADO.NET NonQuery - Deletion";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Existing Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Delete";
button1.Location = new Point(300, 120);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "delete from Employees where empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p1.Value = textbox1.Text;
cmd.Parameters.Add(p1);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace InsertionWithSPExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "ADO.NET NonQuery - Insertion - Stored Procedure";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(250, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(250, 100);
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(250, 150);
this.Controls.Add(textbox3);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Insert";
button1.Location = new Point(250, 200);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
private void Button1_Click(object sender, EventArgs e)
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "InsertEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = textbox1.Text;
p2.Value = textbox2.Text;
p3.Value = textbox3.Text;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show(n + " rows inserted");
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace UpdationWithSPExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "ADO.NET NonQuery - Updation - Stored Procedure";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(300, 100);
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(300, 150);
this.Controls.Add(textbox3);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Update";
button1.Location = new Point(300, 200);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "UpdateEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = textbox1.Text;
p2.Value = textbox2.Text;
p3.Value = textbox3.Text;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Enter some existing emp id, new emp name, new salary and click on “Update”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace DeletionWithSPExample
{
public partial class Form1 : Form
{
Label label1;
TextBox textbox1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 300);
this.Text = "ADO.NET NonQuery - Deletion - Stored Procedure";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Existing Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Delete";
button1.Location = new Point(300, 100);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
SqlParameter p1;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "DeleteEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p1.Value = textbox1.Text;
cmd.Parameters.Add(p1);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
)
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace ComboBoxWithSPExample
{
public partial class Form1 : Form
{
DataTable dt;
DataRow drow;
Label label1, label2, label3;
TextBox textbox1, textbox2;
ComboBox combobox1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "ADO.NET Stored Procedures - ComboBox";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(300, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.Location = new Point(250, 50);
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 100);
textbox1.ReadOnly = true;
textbox1.Location = new Point(250, 100);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 150);
textbox2.ReadOnly = true;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "GetEmployees";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
p1 = new SqlParameter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "GetEmployeeByID";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p1.Value = currentempid;
adp.SelectCommand = cmd;
/* call methods */
cmd.Parameters.Add(p1);
adp.Fill(ds);
dt = ds.Tables[0];
textbox1.Text = Convert.ToString(drow["empname"]);
textbox2.Text = Convert.ToString(drow["salary"]);
}
}
}
Output
All the existing EmpID’s appear in the combobox. Select an EmpID, then it shows corresponding
EmpName and Salary.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace UpdationWithComboBoxExample
{
public partial class Form1 : Form
{
DataTable dt;
DataRow drow;
Label label1, label2, label3;
TextBox textbox1, textbox2;
ComboBox combobox1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "Updation with ComboBox Example";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* combobox1 */
combobox1 = new ComboBox();
combobox1.Size = new Size(300, 50);
combobox1.DropDownStyle = ComboBoxStyle.DropDownList;
combobox1.Location = new Point(250, 50);
combobox1.SelectedIndexChanged +=
Combobox1_SelectedIndexChanged;
this.Controls.Add(combobox1);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 100);
textbox1.Location = new Point(250, 100);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 150);
textbox2.Location = new Point(250, 150);
this.Controls.Add(textbox2);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Update";
button1.Location = new Point(250, 200);
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
}
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
p1 = new SqlParameter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select empname, salary from Employees where
empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p1.Value = currentempid;
adp.SelectCommand = cmd;
/* call methods */
cmd.Parameters.Add(p1);
adp.Fill(ds);
dt = ds.Tables[0];
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "update employees set empname=@empname,
salary=@salary where empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = currentempid;
p2.Value = textbox1.Text;
p3.Value = textbox2.Text;
//calling methods
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
All the existing EmpID’s appear in the combobox. Select an EmpID, then it shows corresponding
EmpName and Salary.
Change the values of EmpName and Salary and then click on “Update”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace CRUDExample
{
public partial class Form1 : Form
{
DataTable dt;
DataRow drow;
Label label1, label2, label3, label4;
TextBox textbox1, textbox2, textbox3, textbox4;
Button button1, button2, button3, button4, button5, button6, button7,
button8;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 450);
this.Text = "Disconnected Model";
this.StartPosition = FormStartPosition.CenterScreen;
this.Load += Form1_Load;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Record No: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp ID: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Emp Name:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* label4 */
label4 = new Label();
label4.AutoSize = true;
label4.Text = "Salary:";
label4.Location = new Point(50, 200);
this.Controls.Add(label4);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(250, 50);
textbox1.ReadOnly = true;
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(250, 100);
textbox2.ReadOnly = true;
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(250, 150);
this.Controls.Add(textbox3);
/* textbox4 */
textbox4 = new TextBox();
textbox4.Size = new Size(300, 50);
textbox4.Location = new Point(250, 200);
this.Controls.Add(textbox4);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "First";
button1.Location = new Point(50, 280);
button1.Click += Button1_Click;
this.Controls.Add(button1);
/* button2 */
button2 = new Button();
button2.AutoSize = true;
button2.Text = "Previous";
button2.Location = new Point(170, 280);
button2.Click += Button2_Click;
this.Controls.Add(button2);
/* button3 */
button3 = new Button();
button3.AutoSize = true;
button3.Text = "Next";
button3.Location = new Point(350, 280);
button3.Click += Button3_Click;
this.Controls.Add(button3);
/* button4 */
/* button5 */
button5 = new Button();
button5.AutoSize = true;
button5.Text = "Create";
button5.Location = new Point(50, 340);
button5.Click += Button5_Click;
this.Controls.Add(button5);
/* button6 */
button6 = new Button();
button6.AutoSize = true;
button6.Text = "Insert";
button6.Location = new Point(170, 340);
button6.Visible = false;
button6.Click += Button6_Click;
this.Controls.Add(button6);
/* button7 */
button7 = new Button();
button7.AutoSize = true;
button7.Text = "Update";
button7.Location = new Point(350, 340);
button7.Click += Button7_Click;
this.Controls.Add(button7);
/* button8 */
button8 = new Button();
button8.AutoSize = true;
button8.Text = "Delete";
button8.Location = new Point(475, 340);
button8.Click += Button8_Click;
this.Controls.Add(button8);
}
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
}
//display record
textbox1.Text = "0";
int n = Convert.ToInt32(textbox1.Text);
drow = dt.Rows[n];
textbox2.Text = Convert.ToString(drow["EmpID"]);
textbox3.Text = Convert.ToString(drow["EmpName"]);
textbox4.Text = Convert.ToString(drow["Salary"]);
}
int n = Convert.ToInt32(textbox1.Text);
n++;
if (n == dt.Rows.Count)
{
n = dt.Rows.Count - 1;
MessageBox.Show("Already at last record");
}
textbox1.Text = Convert.ToString(n);
drow = dt.Rows[n];
textbox2.Text = Convert.ToString(drow["EmpID"]);
textbox3.Text = Convert.ToString(drow["EmpName"]);
textbox4.Text = Convert.ToString(drow["Salary"]);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "insert into Employees values(@empid,
@empname, @salary)";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = textbox2.Text;
p2.Value = textbox3.Text;
p3.Value = textbox4.Text;
//calling methods
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
cn.Open();
int m = cmd.ExecuteNonQuery();
cn.Close();
textbox2.ReadOnly = true;
string msg = m + " rows inserted";
MessageBox.Show(msg);
loaddata();
button5.Visible = true;
button6.Visible = false;
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
//calling methods
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
cn.Open();
int m = cmd.ExecuteNonQuery();
cn.Close();
loaddata();
button5.Visible = true;
button6.Visible = false;
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "delete from Employees where empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p1.Value = textbox2.Text;
//calling methods
cmd.Parameters.Add(p1);
cn.Open();
int m = cmd.ExecuteNonQuery();
cn.Close();
loaddata();
//previous
int n = Convert.ToInt32(textbox1.Text);
n--;
if (n == -1)
{
n = 0;
MessageBox.Show("Already at first record");
}
textbox1.Text = Convert.ToString(n);
drow = dt.Rows[n];
textbox2.Text = Convert.ToString(drow["EmpID"]);
textbox3.Text = Convert.ToString(drow["EmpName"]);
textbox4.Text = Convert.ToString(drow["Salary"]);
}
}
}
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “useraccountsdatabase” database already.
email nvarchar(max))
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace RegistrationFormExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "Registration Form";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Username: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Password: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Confirm Password:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* label4 */
label4 = new Label();
label4.AutoSize = true;
label4.Text = "Email:";
label4.Location = new Point(50, 200);
this.Controls.Add(label4);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(300, 100);
textbox2.PasswordChar = '*';
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(300, 150);
textbox3.PasswordChar = '*';
this.Controls.Add(textbox3);
/* textbox4 */
textbox4 = new TextBox();
textbox4.Size = new Size(300, 50);
textbox4.Location = new Point(300, 200);
this.Controls.Add(textbox4);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Register";
button1.Location = new Point(300, 250);
button1.Click += Button1_Click;
this.AcceptButton = button1;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=useraccountsdatabase";
cmd.CommandText = "insert into Users values(@username,
@password, @email)";
cmd.Connection = cn;
p1.ParameterName = "@username";
p2.ParameterName = "@password";
p3.ParameterName = "@email";
p1.Value = textbox1.Text;
p2.Value = textbox2.Text;
p3.Value = textbox4.Text;
//calling methods
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
string msg;
if (n == 1)
msg = "Successfully Registered";
else
msg = "Registration failed";
MessageBox.Show(msg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
Output
Enter some user details and click on “Register”. The data will be saved in the database.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “useraccountsdatabase” database already.
use useraccountsdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
• Open Solution Explorer. Right click on the project (LoginExample) and click on “Add” –
“New Item” – “Windows Forms” – “Windows Form”. Type the file name as “Form2.cs”. Click
on “Add”.
• Open Solution Explorer. Right click on the project (LoginExample) and click on “Add” –
“New Item” – “Code” – “Class”. Type the file name as “Common.cs”. Click on “Add”.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace LoginExample
{
public partial class Form1 : Form
{
Label label1, label2;
TextBox textbox1, textbox2;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Username: ";
label1.Location = new Point(50, 50);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Password: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(300, 100);
textbox2.PasswordChar = '*';
this.Controls.Add(textbox2);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Login";
button1.Location = new Point(300, 150);
button1.Click += Button1_Click;
this.AcceptButton = button1;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
adp = new SqlDataAdapter();
ds = new DataSet();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=useraccountsdatabase";
cmd.CommandText = "select * from users where
username=@username and password=@password";
cmd.Connection = cn;
p1.ParameterName = "@username";
p1.Value = uname;
p2.ParameterName = "@password";
p2.Value = pwd;
adp.SelectCommand = cmd;
//call methods
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
adp.Fill(ds);
//read data
dt = ds.Tables[0];
if (dt.Rows.Count == 1)
{
object obj1;
drow = dt.Rows[0];
obj1 = drow["email"];
string email = Convert.ToString(obj1);
Common.CurrentEmail = email;
Form2.cs
using System;
using System.Windows.Forms;
namespace LoginExample
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
Common.cs
using System;
namespace LoginExample
{
static class Common
{
public static string CurrentEmail { get; set; }
}
}
Output
Enter “scott” and “scott123” as username and password and click on “Login”.
• Note: Ignore this step, if you have created “transactionsdatabase” database already.
use transactionsdatabase
go
Balance decimal)
GO
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
namespace TransactionsExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "ADO.NET Transactions";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Start Transaction";
button1.AutoSize = true;
button1.Location = new Point(130, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd1 = new SqlCommand();
cmd2 = new SqlCommand();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=transactionsdatabase";
cmd1.CommandText = "update AccountsTable set Balance=Balance-
1000 where AccountNo=101";
//call methods
cn.Open();
transaction = cn.BeginTransaction();
cmd1.Transaction = transaction;
cmd2.Transaction = transaction;
try
{
cmd1.ExecuteNonQuery();
MessageBox.Show("First operation done.");
cmd2.ExecuteNonQuery();
MessageBox.Show("Second operation done.");
transaction.Commit(); //save data
MessageBox.Show("Transaction Complete");
}
catch (Exception)
{
transaction.Rollback(); //first operation will be rollback
MessageBox.Show("Rollback done!");
}
cn.Close();
}
}
}
Output
Click on OK.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have installed “Oracle 11g Express” already.
• Click on “Yes”.
• Click on “Next”.
• Click on “Next”.
• Click on “Next”.
• Click on “Next”.
• Click on “Install”.
• Click on “Finish”.
• Note: Ignore this step, if you have created “employees” table in Oracle already.
connect system/123;
commit;
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.OleDb;
using System.Data;
namespace OracleExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "Oracle";
this.StartPosition = FormStartPosition.CenterScreen;
this.AutoScroll = true;
this.Load += Form1_Load;
}
/* create objects */
cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "user id=system; password=123;
provider=msdaora.1";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
int n = 50;
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = Convert.ToString(eid);
label1.Location = new Point(50, n);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = ename;
label2.Location = new Point(150, n);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = Convert.ToString(sal);
label3.Location = new Point(350, n);
this.Controls.Add(label3);
/* go to next row */
n += 50;
}
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Yes”.
• Click on “Next”.
• Click on “Install”.
• Click on OK.
• Click on OK.
• Click on “Create”.
• Click on OK.
• Click on “Yes”.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.OleDb;
using System.Data;
namespace MSAccessExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "MS Access";
this.StartPosition = FormStartPosition.CenterScreen;
this.AutoScroll = true;
this.Load += Form1_Load;
}
/* create objects */
cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = @"provider=Microsoft.Ace.Oledb.12.0; data
source=C:\CSharp\Database1.accdb";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
int n = 50;
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = Convert.ToString(eid);
label1.Location = new Point(50, n);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = ename;
label2.Location = new Point(150, n);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = Convert.ToString(sal);
label3.Location = new Point(350, n);
this.Controls.Add(label3);
/* go to next row */
n += 50;
}
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Yes”.
• Click on “Next”.
• Click on “Install”.
• Click on OK.
• Click on “Save”.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.OleDb;
using System.Data;
namespace MSExcelExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "MS Excel";
this.StartPosition = FormStartPosition.CenterScreen;
this.AutoScroll = true;
this.Load += Form1_Load;
/* create objects */
cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book1.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=1' ";
cmd.CommandText = "select * from [Sheet1$]";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
int n = 50;
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = Convert.ToString(eid);
label1.Location = new Point(50, n);
this.Controls.Add(label1);
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = ename;
label2.Location = new Point(150, n);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = Convert.ToString(sal);
label3.Location = new Point(350, n);
this.Controls.Add(label3);
/* go to next row */
n += 50;
}
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database in SQL Server, already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Note: Ignore this step, if you have created “employees2” table in Oracle already.
connect system/123;
commit;
Creating Project
• Click on OK.
Form1.cs
namespace SqlServerToOracleExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "SqlServer to Oracle";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "SqlServer to Oracle";
button1.AutoSize = true;
button1.Location = new Point(150, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees2";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
InsertIntoOracle(eid, ename, sal);
}
MessageBox.Show("Done");
}
private void InsertIntoOracle(int eid, string ename, decimal sal)
{
//create reference variables
OleDbConnection cn;
OleDbCommand cmd;
//create objects
cn = new OleDbConnection();
cmd = new OleDbCommand();
//calling properties
cn.ConnectionString = "user id=system; password=123;
provider=msdaora.1";
cmd.CommandText = string.Format("insert into Employees2
values({0}, '{1}', {2})", eid, ename, sal);
cmd.Connection = cn;
//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database in SQL Server, already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US
• Additionally, we have to install “Access Database Engine”, based on the steps explained in
the previous examples.
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Save”.
Creating Project
• Click on OK.
Form1.cs
namespace SqlServerToExcelExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
/* button1 */
button1 = new Button();
button1.Text = "SqlServer to Excel";
button1.AutoSize = true;
button1.Location = new Point(150, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
//create objects
cn = new OleDbConnection();
cmd = new OleDbCommand();
//calling properties
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book1.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=3' ";
cmd.CommandText = string.Format("insert into [Sheet1$] values('{0}',
'{1}', '{2}')", eid, ename, sal);
cmd.Connection = cn;
//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.
go
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Note: Ignore this step, if you have created “employees2” table in Oracle already.
connect system/123;
commit;
Creating Project
Form1.cs
namespace OracleToSqlServerExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "Oracle to SqlServer";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Oracle to SqlServer";
button1.AutoSize = true;
button1.Location = new Point(150, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
/* create objects */
cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();
/* call properties */
cn.ConnectionString = "user id=system; password=123;
provider=msdaora.1";
cmd.CommandText = "select * from Employees2";
cmd.Connection = cn;
adp.SelectCommand = cmd;
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
InsertIntoSqlServer(eid, ename, sal);
}
MessageBox.Show("Done");
}
private void InsertIntoSqlServer(int eid, string ename, decimal sal)
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = string.Format("insert into Employees2
values({0}, '{1}', {2})", eid, ename, sal);
cmd.Connection = cn;
//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US
• Additionally, we have to install “Access Database Engine”, based on the steps explained in
the previous examples.
• Note: Ignore this step, if you have installed “Access Database Engine” already.
Creating Project
• Click on OK.
Form1.cs
namespace ExcelToSqlServerExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "Excel to SqlServer";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
InsertIntoSqlServer(eid, ename, sal);
}
MessageBox.Show("Done");
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
namespace SqlServerToFileExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "SqlServer to File";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "SqlServer to File";
button1.AutoSize = true;
button1.Location = new Point(150, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
if (Directory.Exists(@"C:\CSharp") == false)
{
Directory.CreateDirectory(@"C:\CSharp");
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();
finfo = new FileInfo(@"C:\CSharp\Employees.txt");
//create objects
fs = new FileStream(@"C:\CSharp\Employees.txt", FileMode.Create,
FileAccess.Write);
sw = new StreamWriter(fs);
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees2";
cmd.Connection = cn;
adp.SelectCommand = cmd;
//call methods
adp.Fill(ds);
//read data
dt = ds.Tables[0];
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
namespace FileToSqlServerExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(550, 300);
this.Text = "File to SqlServer";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "File to SqlServer";
button1.AutoSize = true;
button1.Location = new Point(150, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace DataSetInsertionExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "DataSet - Insertion";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Emp ID: ";
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(250, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(250, 100);
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(250, 150);
this.Controls.Add(textbox3);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Insert";
button1.Location = new Point(250, 200);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
cmb = new SqlCommandBuilder();
ds = new DataSet();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
cmb.DataAdapter = adp;
//call methods
adp.Fill(ds);
dt = ds.Tables[0];
MessageBox.Show("Inserted");
}
}
}
Output
Enter some emp id, emp name and salary and click on “Insert”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace DataSetUpdationExample
{
public partial class Form1 : Form
{
Label label1, label2, label3;
TextBox textbox1, textbox2, textbox3;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 400);
this.Text = "DataSet - Updation";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
/* label2 */
label2 = new Label();
label2.AutoSize = true;
label2.Text = "Emp Name: ";
label2.Location = new Point(50, 100);
this.Controls.Add(label2);
/* label3 */
label3 = new Label();
label3.AutoSize = true;
label3.Text = "Salary:";
label3.Location = new Point(50, 150);
this.Controls.Add(label3);
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(300, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* textbox2 */
textbox2 = new TextBox();
textbox2.Size = new Size(300, 50);
textbox2.Location = new Point(300, 100);
this.Controls.Add(textbox2);
/* textbox3 */
textbox3 = new TextBox();
textbox3.Size = new Size(300, 50);
textbox3.Location = new Point(300, 150);
this.Controls.Add(textbox3);
/* button1 */
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
cmb = new SqlCommandBuilder();
ds = new DataSet();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
cmb.DataAdapter = adp;
//call methods
adp.Fill(ds);
dt = ds.Tables[0];
//update
drow["empname"] = textbox2.Text;
drow["salary"] = textbox3.Text;
MessageBox.Show("Updated");
}
}
}
Output
Type some existing emp id, new emp name and new salary and click on “Update”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Click on OK.
Form1.cs
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data.SqlClient;
using System.Data;
namespace DataSetDeletionExample
{
public partial class Form1 : Form
{
Label label1;
TextBox textbox1;
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(650, 300);
this.Text = "ADO.NET NonQuery - Deletion";
this.StartPosition = FormStartPosition.CenterScreen;
/* label1 */
label1 = new Label();
label1.AutoSize = true;
label1.Text = "Existing Emp ID: ";
/* textbox1 */
textbox1 = new TextBox();
textbox1.Size = new Size(200, 50);
textbox1.Location = new Point(300, 50);
this.Controls.Add(textbox1);
/* button1 */
button1 = new Button();
button1.AutoSize = true;
button1.Text = "Delete";
button1.Location = new Point(300, 120);
this.AcceptButton = button1;
button1.Click += Button1_Click;
this.Controls.Add(button1);
}
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
cmb = new SqlCommandBuilder();
ds = new DataSet();
//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;
cmb.DataAdapter = adp;
//call methods
adp.Fill(ds);
dt = ds.Tables[0];
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Solution
• Click on OK.
• Right click on the solution (CompanySolution) and click on “Add” – “New Project”.
• Click on OK.
• Right click on the solution (CompanySolution) and click on “Add” – “New Project”.
• Click on OK.
• Right click on the solution (CompanySolution) and click on “Add” – “New Project”.
• Click on OK.
Adding references:
CompanyDataAccess\Class1.cs
namespace CompanyDataAccess
{
public class EmployeesDataAccess
{
public int InsertEmployee(int EmpID, string EmpName, decimal Salary)
{
SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
return n;
}
}
}
CompanyBusinessLogic\Class1.cs
//Business Logic
using System;
using CompanyDataAccess;
namespace CompanyBusinessLogic
{
public class EmployeesBusinessLogic
{
private int _empid;
private string _empname;
private decimal _salary;
{
set
{
if (value >= 0)
{
_empid = value;
}
}
get
{
return _empid;
}
}
}
get
{
return _salary;
}
}
CompanyPresentationLogic\Form1.cs
//Presentation Logic
using System;
using System.Drawing;
using System.Windows.Forms;
using CompanyBusinessLogic;
namespace CompanyPresentation
{
public partial class Form1 : Form
{
Label lblHeading, lblEmployeeID, lblEmployeeName, lblSalary;
TextBox txtEmployeeID, txtEmployeeName, txtSalary;
Button btnInsert;
public Form1()
{
InitializeComponent();
/* form properties */
this.Text = "N-Tier Architecture";
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 500);
this.StartPosition = FormStartPosition.CenterScreen;
/* lblHeading */
lblHeading = new Label();
lblHeading.Text = "New Employee";
lblHeading.Font = new Font("Comic Sans MS", 30);
lblHeading.AutoSize = true;
lblHeading.BackColor = Color.Gold;
lblHeading.Location = new Point(150, 50);
this.Controls.Add(lblHeading);
/* lblEmployeeID */
lblEmployeeID = new Label();
lblEmployeeID.Text = "Employee ID: ";
lblEmployeeID.AutoSize = true;
lblEmployeeID.Location = new Point(50, 150);
this.Controls.Add(lblEmployeeID);
/* lblEmployeeName */
lblEmployeeName = new Label();
lblEmployeeName.Text = "Employee Name: ";
lblEmployeeName.AutoSize = true;
lblEmployeeName.Location = new Point(50, 220);
this.Controls.Add(lblEmployeeName);
/* lblSalary */
lblSalary = new Label();
lblSalary.Text = "Salary: ";
lblSalary.AutoSize = true;
lblSalary.Location = new Point(50, 290);
this.Controls.Add(lblSalary);
/* txtEmployeeID */
Enter some new emp id, emp name and salary and click on “Insert”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
Salary decimal)
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• Click on OK.
• Right click on the project (LinqToSqlExample) and click on “Add” – “New Item” – “Data” –
“LINQ to SQL Classes”.
• Click on “Add”.
• Click on OK.
• Drag and drop “Employees” table from Server Explorer into “Object Relational Designer” of
“DataClasses1.dbml” file.
Form1.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace LinqToSqlExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
/* button1 */
button1 = new Button();
button1.Text = "Get Data";
button1.AutoSize = true;
button1.Location = new Point(170, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
//create objects
db = new DataClasses1DataContext();
//LINQ query
List<Employee> emps = db.Employees.ToList();
Output
Click on OK.
Click on OK.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Solution Explorer. Right click on the project (EntityFrameworkExample) and click on
“Add” – “New Item” – “Code” – “Class”. Type the filename as “Employee.cs”. Click on “Add”.
Install-package EntityFramework
<connectionStrings>
<add name="CompanyDbContext" connectionString="data
source=localhost; integrated security=yes; initial
catalog=company" providerName="System.Data.SqlClient" />
</connectionStrings>
Employee.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace EntityFrameworkExample
{
public class Employee
{
[Key]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
Form1.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace EntityFrameworkExample
{
public partial class Form1 : Form
{
Button button1;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(500, 300);
this.Text = "ADO.NET Entity Framework";
this.StartPosition = FormStartPosition.CenterScreen;
/* button1 */
button1 = new Button();
button1.Text = "Get Data";
button1.AutoSize = true;
button1.Location = new Point(170, 100);
button1.Click += button1_Click;
this.Controls.Add(button1);
}
CompanyDbContext db;
//create objects
db = new CompanyDbContext();
//LINQ query
//List<Employee> emps = db.Employees.ToList();
//List<Employee> emps = db.Employees.Where(temp => temp.Salary
>= 2000).ToList();
List<Employee> emps = db.Employees.OrderBy(temp =>
temp.Salary).ToList();
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Solution Explorer. Right click on the project (EfInsertionExample) and click on “Add”
– “New Item” – “Code” – “Class”. Type the filename as “Employee.cs”. Click on “Add”.
Install-package EntityFramework
<connectionStrings>
<add name="CompanyDbContext" connectionString="data
source=localhost; integrated security=yes; initial
catalog=company" providerName="System.Data.SqlClient" />
</connectionStrings>
Employee.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EfInsertionExample
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
Form1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
namespace EfInsertionExample
{
public partial class Form1 : Form
{
Label lblEmpID, lblEmpName, lblSalary;
TextBox txtEmpID, txtEmpName, txtSalary;
Button btnOK;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 20);
this.Size = new Size(600, 400);
this.StartPosition = FormStartPosition.CenterScreen;
this.Text = "ADO.NET Entity Framework - Insertion";
/* lblEmpID */
/* lblEmpName */
lblEmpName = new Label();
lblEmpName.Text = "Emp Name: ";
lblEmpName.AutoSize = true;
lblEmpName.Location = new Point(50, 120);
this.Controls.Add(lblEmpName);
/* lblSalary */
lblSalary = new Label();
lblSalary.Text = "Salary: ";
lblSalary.AutoSize = true;
lblSalary.Location = new Point(50, 190);
this.Controls.Add(lblSalary);
/* txtEmpID */
txtEmpID = new TextBox();
txtEmpID.Size = new Size(200, 50);
txtEmpID.Location = new Point(270, 50);
this.Controls.Add(txtEmpID);
/* txtEmpName */
txtEmpName = new TextBox();
txtEmpName.Size = new Size(200, 50);
txtEmpName.Location = new Point(270, 120);
this.Controls.Add(txtEmpName);
/* txtSalary */
txtSalary = new TextBox();
txtSalary.Size = new Size(200, 50);
txtSalary.Location = new Point(270, 190);
this.Controls.Add(txtSalary);
/* btnOK */
btnOK = new Button();
btnOK.Size = new Size(200, 50);
btnOK.Text = "Insert";
btnOK.Location = new Point(270, 270);
this.AcceptButton = btnOK;
btnOK.Click += BtnOK_Click;
this.Controls.Add(btnOK);
}
MessageBox.Show("Inserted");
}
}
}
Output
Enter some emp id, emp name and salary and click on “Insert”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Solution Explorer. Right click on the project (EfUpdationExample) and click on “Add”
– “New Item” – “Code” – “Class”. Type the filename as “Employee.cs”. Click on “Add”.
Install-package EntityFramework
<connectionStrings>
<add name="CompanyDbContext" connectionString="data
source=localhost; integrated security=yes; initial
catalog=company" providerName="System.Data.SqlClient" />
</connectionStrings>
Employee.cs
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EfUpdationExample
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
Form1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
namespace EfUpdationExample
{
public partial class Form1 : Form
{
Label lblEmpID, lblEmpName, lblSalary;
TextBox txtEmpID, txtEmpName, txtSalary;
Button btnOK;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 17);
this.Size = new Size(600, 400);
this.StartPosition = FormStartPosition.CenterScreen;
this.Text = "ADO.NET Entity Framework - Updation";
/* lblEmpID */
lblEmpID = new Label();
lblEmpID.Text = "Existing Emp ID: ";
lblEmpID.AutoSize = true;
lblEmpID.Location = new Point(50, 50);
this.Controls.Add(lblEmpID);
/* lblEmpName */
lblEmpName = new Label();
lblEmpName.Text = "Emp Name: ";
lblEmpName.AutoSize = true;
lblEmpName.Location = new Point(50, 120);
this.Controls.Add(lblEmpName);
/* lblSalary */
lblSalary = new Label();
lblSalary.Text = "Salary: ";
lblSalary.AutoSize = true;
lblSalary.Location = new Point(50, 190);
this.Controls.Add(lblSalary);
/* txtEmpID */
txtEmpID = new TextBox();
txtEmpID.Size = new Size(200, 50);
txtEmpID.Location = new Point(270, 50);
this.Controls.Add(txtEmpID);
/* txtEmpName */
txtEmpName = new TextBox();
txtEmpName.Size = new Size(200, 50);
txtEmpName.Location = new Point(270, 120);
this.Controls.Add(txtEmpName);
/* txtSalary */
txtSalary = new TextBox();
txtSalary.Size = new Size(200, 50);
txtSalary.Location = new Point(270, 190);
this.Controls.Add(txtSalary);
/* btnOK */
btnOK = new Button();
btnOK.Size = new Size(200, 50);
btnOK.Text = "Update";
btnOK.Location = new Point(270, 270);
this.AcceptButton = btnOK;
btnOK.Click += BtnOK_Click;
this.Controls.Add(btnOK);
}
private void BtnOK_Click(object sender, EventArgs e)
{
//updation
CompanyDbContext db = new CompanyDbContext();
int n = Convert.ToInt32(txtEmpID.Text);
Employee emp = db.Employees.Where(temp => temp.EmpID ==
n).FirstOrDefault();
emp.EmpName = txtEmpName.Text;
emp.Salary = Convert.ToDecimal(txtSalary.Text);
db.SaveChanges();
MessageBox.Show("Updated");
}
}
}
Output
Enter some existing emp id, new emp name and new salary and click on “Update”.
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have created “company” database already.
go
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Solution Explorer. Right click on the project (EfDeletionExample) and click on “Add”
– “New Item” – “Code” – “Class”. Type the filename as “Employee.cs”. Click on “Add”.
Install-package EntityFramework
<connectionStrings>
<add name="CompanyDbContext" connectionString="data
source=localhost; integrated security=yes; initial
catalog=company" providerName="System.Data.SqlClient" />
</connectionStrings>
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EfDeletionExample
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EmpID { get; set; }
public string EmpName { get; set; }
public decimal Salary { get; set; }
}
public class CompanyDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
namespace EfDeletionExample
{
public partial class Form1 : Form
{
Label lblEmpID;
TextBox txtEmpID;
Button btnOK;
public Form1()
{
InitializeComponent();
/* form properties */
this.Font = new Font("Tahoma", 17);
this.Size = new Size(600, 250);
this.StartPosition = FormStartPosition.CenterScreen;
this.Text = "ADO.NET Entity Framework - Deletion";
/* lblEmpID */
lblEmpID = new Label();
lblEmpID.Text = "Existing Emp ID: ";
lblEmpID.AutoSize = true;
lblEmpID.Location = new Point(50, 50);
this.Controls.Add(lblEmpID);
/* txtEmpID */
txtEmpID = new TextBox();
txtEmpID.Size = new Size(200, 50);
txtEmpID.Location = new Point(270, 50);
this.Controls.Add(txtEmpID);
/* btnOK */
btnOK = new Button();
btnOK.Size = new Size(200, 50);
btnOK.Text = "Delete";
btnOK.Location = new Point(270, 100);
this.AcceptButton = btnOK;
btnOK.Click += BtnOK_Click;
this.Controls.Add(btnOK);
}
private void BtnOK_Click(object sender, EventArgs e)
{
//updation
CompanyDbContext db = new CompanyDbContext();
int n = Convert.ToInt32(txtEmpID.Text);
Employee emp = db.Employees.Where(temp => temp.EmpID ==
n).FirstOrDefault();
db.Employees.Remove(emp);
db.SaveChanges();
MessageBox.Show("Deleted");
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).