Unit I Framework Components: BCL (Base Class Library)
Unit I Framework Components: BCL (Base Class Library)
For example, in
UNIT I C# we define data type as int, while in VB.NET we define integer as a data type.
The base class library has a rich collection of libraries features and functions that help to
implement many programming languages in the .NET Framework, such as C #, F #, Visual C
++, and more. Furthermore, BCL divides into two parts:
CTS (Common Type System) A .NET assembly is the main building block of the .NET Framework. It is a small unit of code
that contains a logical compiled code in the Common Language infrastructure (CLI), which is
It specifies a standard that represent what type of data and value can be defined and used for deployment, security and versioning. It defines in two parts (process) DLL and
managed in computer memory at runtime. A CTS ensures that programming data defined in library (exe) assemblies. When the .NET program is compiled, it generates a metadata with
Microsoft Intermediate Language, which is stored in a file called Assembly.
1 2
It provides the various system functionality in the .NET Framework, that includes classes,
interfaces and data types, etc. to create multiple functions and different types of application
such as desktop, web, mobile application, etc. In other words, it can be defined as, it
provides a base on which various applications, controls and components are built in .NET
Framework.
************************************************************************
The above figure converts code into native code, which the CPU can execute.
3 4
CLR/CTS supports lots of feature but that does not mean all the languages that target CLR
supports all these feature.
Sometimes there is a need for code written in one language to access another language, but CLSCompliant Attribute
programming languages that target CLR are different from one other, for example C# is case
sensitive but VB is not. This can cause a problem when we access code written in one Before starting with any concrete program/example on CLS, I will explain a useful attrubute
language from another language. So .Net has come up with CLS; i.e., Common Language that needs to be included while writing CLS Compliant Code.
Specification.
Syntax : [assembly:CLSCompliant(true)]
Definition
If you set CLSCompliant attribute to true, it gives a compile time warning if you write any
CLS defines a minimum set of features that must be supported by all languages that target public or protected member which is not CLSCompliant. It will give a warning for only public
CLR. and protected members, not for private, as private members can be accessed only within
that class.
Figure - The below Venn diagram will be helpful to understand CLS. Example 1
C# is case sensitive but VB is not; that's why public members that differ by case will
give you a warning.
1. using System;
2.
3. [assembly: CLSCompliant(true)]
4. namespace CLSExamples
5 6
5. {
6.
7. public class CaseSensitiveExample
8. {
9. static void Main(string[] args)
10. {
11.
12. }
13.
14. public void XYZ()
15. {
16. Console.WriteLine("Inside XYZ");
17. }
18. public void Xyz()
19. {
20. Console.WriteLine("Inside Xyz");
21. }
22. }
23. }
2. Reference Type: A Reference type stores a reference to the value of a memory
address and is allocated on the heap. Heap memory is used for dynamic memory
************************************************************************** allocation. Reference Type does not hold actual data directly but holds the address
of data. Whenever a reference type object is made, it copies the address and not
Common Type System (CTS) actual data. Therefore two variables will refer to the same data. If data of one
Reference Type object is changed, the same is reflected for the other object.
CTS provides guidelines for declaring, using, and managing data types at runtime. It offers Reference types can be self-describing types, pointer types, or interference types.
cross-language communication. For example, VB.NET has an integer data type, and C# has The self-describing types may be string, array, and class types that store metadata
an int data type for managing integers. After compilation, Int32 is used by both data types. about themselves.
So, CTS provides the data types using managed code. A common type system helps in
writing language-independent code. **********************************************************************
1. Value Type: A value type stores the data in memory allocated on the stack or inline Metadata and Assemblies
in a structure. This category of Type holds the data directory. If one variable's value
is copied to another, both the variables store data independently. It can be of inbuilt- Metadata is binary information describing your program that is stored either in a common
language runtime portable executable (PE) file or in memory. When you compile your code
in types, user-defined, or enumerations types. Built-in types are primitive data types
into a PE file, metadata is inserted into one portion of the file, and your code is converted to
like numeric, Boolean, char, and date. Users in the source code create user-defined Microsoft intermediate language (MSIL) and inserted into another portion of the file. Every
types. An enumeration refers to a set of enumerated values represented by labels type and member that is defined and referenced in a module or assembly is described
but stored as a numeric type. within metadata. When code is executed, the runtime loads metadata into memory and
references it to discover information about your code's classes, members, inheritance, and
so on.
7 8
Metadata describes every type and member defined in your code in a language-neutral metadata into .NET files through user-defined custom attributes. For more
manner. Metadata stores the following information: information, see Attributes.
In .NET and .NET Framework, you can build an assembly from one or more source code files.
Benefits of Metadata In .NET Framework, assemblies can contain one or more modules. This way, larger projects
can be planned so that several developers can work on separate source code files or
Metadata is the key to a simpler programming model, and eliminates the need for Interface modules, which are combined to create a single assembly. Assemblies have the following
Definition Language (IDL) files, header files, or any external method of component properties:
reference. Metadata enables .NET languages to describe themselves automatically in a
language-neutral manner, unseen by both the developer and the user. Additionally,
Assemblies are implemented as .exe or .dll files.
metadata is extensible through the use of attributes. Metadata provides the following major
For libraries that target .NET Framework, you can share assemblies between
benefits:
applications by putting them in the global assembly cache (GAC). You must strong-
Self-describing files. name assemblies before you can include them in the GAC. For more information,
see Strong-named assemblies.
Common language runtime modules and assemblies are self-describing. A module's Assemblies are only loaded into memory if they're required. If they aren't used, they
metadata contains everything needed to interact with another module. Metadata
aren't loaded. Therefore, assemblies can be an efficient way to manage resources in
automatically provides the functionality of IDL in COM, so you can use one file for
larger projects.
both definition and implementation. Runtime modules and assemblies do not even
require registration with the operating system. As a result, the descriptions used by You can programmatically obtain information about an assembly by using reflection.
the runtime always reflect the actual code in your compiled file, which increases You can load an assembly just to inspect it by using the MetadataLoadContext class on
application reliability. .NET and .NET Framework. MetadataLoadContext replaces
the Assembly.ReflectionOnlyLoad methods.
Language interoperability and easier component-based design.
********************************************************************************
Metadata provides all the information required about compiled code for you to inherit
a class from a PE file written in a different language. You can create an instance of any
class written in any managed language (any language that targets the common
language runtime) without worrying about explicit marshalling or using custom
interoperability code. .NET Namespaces
Attributes. Namespaces in C# are used to organize too many classes so that it can be easy to handle the
application.
.NET lets you declare specific kinds of metadata, called attributes, in your compiled
file. Attributes can be found throughout .NET and are used to control in more detail In a simple C# program, we use System.Console where System is the namespace and
how your program behaves at run time. Additionally, you can emit your own custom Console is the class. To access the class of a namespace, we need to use
9 10
namespacename.classname. We can use using keyword so that we don't have to use 12. public void sayHello() { Console.WriteLine("Hello Second Namespace"); }
complete name all the time.
13. }
In C#, global namespace is the root namespace. The global::System will always refer to the 14. }
namespace "System" of .Net Framework. 15. public class TestNamespace
16. {
example
17. public static void Main()
simple example of namespace which contains one class "Program". 18. {
19. First.Hello h1 = new First.Hello();
1. using System; 20. Second.Hello h2 = new Second.Hello();
2. namespace ConsoleApplication1 21. h1.sayHello();
3. { 22. h2.sayHello();
4. class Program 23.
5. { 24. }
6. static void Main(string[] args) 25. }
7. {
8. Console.WriteLine("Hello Namespace!"); Output:
9. }
Hello First Namespace
10. } Hello Second Namespace
11. }
***************************************************************************
Output:
Hello Namespace!
The source code is converted into the MSIL by a language-specific compiler in the
compile time of the CLR. Also, along with the MSIL, metadata is also produced in the
compilation. The metadata contains information such as the definition and signature
of the types in the code, runtime information, etc.
A Common Language Infrastructure (CLI) assembly is created by assembling the MSIL.
This assembly is basically a compiled code library that is used for security, deployment,
versioning, etc. and it is of two types i.e. process assembly (EXE) and library assembly
(DLL).
The JIT compiler then converts the Microsoft Intermediate Language(MSIL) into the
machine code that is specific to the computer environment that the JIT compiler runs
on. The MSIL is converted into the machine code on a requirement basis i.e. the JIT
compiler compiles the MSIL as required rather than the whole of it.
The machine code obtained using the JIT compiler is then executed by the processor of
The JIT compiler converts the Microsoft Intermediate Language(MSIL) or Common
the computer.
Intermediate Language(CIL) into the machine code. This is done before the MSIL or CIL can
be executed. The MSIL is converted into machine code on a requirement basis i.e. the JIT
************************************************************************
compiler compiles the MSIL or CIL as required rather than the whole of it. The compiled
MSIL or CIL is stored so that it is available for subsequent calls if required.
Just-In-Time(JIT) Compiler ************************************************************************
13 14
UNIT II
C# - Program Structure
A C# program consists of the following parts −
• Namespace declaration
• A class
• Class methods
• Class attributes
• A Main method
• Statements and Expressions
• Comments
Example
using System;
namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result −
Hello World
***********************************************************************************
C# LITERALS.
Integer Literals
An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the
base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned
and long, respectively. The suffix can be uppercase or lowercase and can be in any
order.
15 1
Here are some examples of integer literals −
\' ' character
212 /* Legal */
215u /* Legal */ \" " character
0xFeeL /* Legal */
A floating-point literal has an integer part, a decimal point, a fractional part, and an
\n Newline
exponent part. You can represent floating point literals either in decimal form or
exponential form.
\r Carriage return
Here are some examples of floating-point literals −
While representing in decimal form, you must include the decimal point, the \xhh . . . Hexadecimal number of one or more digits
exponent, or both; and while representing using exponential form you must include
the integer part, the fractional part, or both. The signed exponent is introduced by e
Following is the example to show few escape sequence characters −
or E.
Live Demo
Character Constants
using System;
Character literals are enclosed in single quotes. For example, 'x' and can be stored in
a simple variable of char type. A character literal can be a plain character (such as 'x'), namespace EscapeChar {
class Program {
an escape sequence (such as '\t'), or a universal character (such as '\u02C0'). static void Main(string[] args) {
There are certain characters in C# when they are preceded by a backslash. They have Console.WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
special meaning and they are used to represent like newline (\n) or tab (\t). Here, is a }
list of some of such escape sequence codes − }
}
Escape sequence Meaning
When the above code is compiled and executed, it produces the following result −
2 3
}
String Literals
When the above code is compiled and executed, it produces the following result −
String literals or constants are enclosed in double quotes "" or with @"". A string
Enter Radius:
contains characters that are similar to character literals: plain characters, escape 3
sequences, and universal characters. Radius: 3, Area: 28.27431
You can break a long line into multiple lines using string literals and separating the
parts using whitespaces. ***********************************************************************************
Here are some examples of string literals. All the three forms are identical strings.
Data Types
"hello, dear"
"hello, \
dear"
Example
"hello, " "d" "ear"
@"hello dear" int myNum = 5; // Integer (whole number)
Constants
string myText = "Hello"; // String
Constants are defined using the const keyword. Syntax for defining a constant is −
const <data_type> <constant_name> = value;
The following program demonstrates defining and using a constant in your program
−
Live Demo
using System;
namespace DeclaringConstants {
class Program {
static void Main(string[] args) {
const double pi = 3.14159;
// constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
} ***********************************************************************************
4 5
Operators static void Main(string[] args)
{
Operators are the foundation of any programming language. Thus the functionality
of C# language is incomplete without the use of operators. Operators allow us to int result;
perform different kinds of operations on operands. In C#, operators Can be int x = 10, y = 5;
categorized based upon their different functionality :
// Addition
• Arithmetic Operators
result = (x + y);
• Relational Operators
Console.WriteLine("Addition Operator: " + result);
• Logical Operators
• Bitwise Operators // Subtraction
• Assignment Operators result = (x - y);
• Conditional Operator Console.WriteLine("Subtraction Operator: " + result);
In C#, Operators can also categorized based upon Number of Operands :
• Unary Operator: Operator that takes one operand to perform the // Multiplication
result = (x * y);
operation.
Console.WriteLine("Multiplication Operator: "+ result);
• Binary Operator: Operator that takes two operands to perform the
operation. // Division
• Ternary Operator: Operator that takes three operands to perform the result = (x / y);
operation. Console.WriteLine("Division Operator: " + result);
// Main Function The Keyword if tells the compiler what follows The Condition Following the
Keyword if is always enclosed within a pair or Parentheses if The Condition id True
6 7
Then the Statements is Executed if the Condition is not true then the Statement is
not Executed For Checking a condition Relational Operators are Used Like > ,< ,==,
>=,<= etc. The if statement is widely used for checking a particular condition Suppose
you want to check the condition and then execute the condition if your condition is
met.
forex:
if(a>b)
then print a is greater then here we first check the condition
that either a is greater than b if yes then execute the condition
if-else if
The if-else if is similar to the if-else but here the first if is used for checking a
condition and the other else if is used for checking a one more condition suppose if
we wants to check the two or more conditions then we can use the if-else if.
if-else
8 9
Nested if ....else statement The value1 is assigned to the variable a in case the condition is true otherwise
value2 is assigned to the variable a.
When an if statement occurs within another if statement, then such type of is
called nested if statement.
Switch Statement
This Statement is Similar to if –else but it uses matching operations rather than
checking a condition if we Wants to Check Many Conditions then the Program will
very Complex So in that Situation We Will use Switch Statement Switch Statement
Uses Many Cases rather and it matches the value with Case where it Matches it will
Execute the Statement But There is Very Necessary to Stop the Execution of Each
Case So that it Doesn't Execute Next Case So that for this Purpose we have to put
the break Statement after Ending of an Each Case We Know if uses Else Statement
if Condition is False or All Conditions are False The Code of Else Statement is
Executed if Code of all if statements is false So that in Switch Default is used when
all Cases are not Matched In other Languages like c and C++ we can Match Only the
Integer or a Character value but in the C# We can also a String in the Switch
Statement.
This operator is an assignment operator that selects one of the two values 1. while
depending on the truth value of given condition. consider the following code
snippet. 2. do-while
A = condition ? value1 : value2;
3. for
10 11
4. foreach
While
While Loop is Known as Entry Controlled Loop because in The while loop
first we initialize the value of variable or Starting point of Execution and then
we check the condition and if the condition is true then it will execute the
statements and then after it increments or decrements the value of a
variable. But in the Will Condition is false then it will never Executes the
Statement.
For
In This loop all the basic operations like initialization ,condition checking
and incrementing or decrementing all these are performed in only one line.
this is similar to the while loop for performing its execution but only different
in its syntax.
Do while
This is Also Called as Exit Controlled Loop we know that in The while loop
the condition is check before the execution of the program but if the condition
is not true then it will not execute the statements so for this purpose we use
the do while loop in this first it executes the statements and then it increments
the value of a variable and then last it checks the condition So in this either
the condition is true or not it Execute the statement at least one time.
Foreach
This is another type of Loops which is provided by C# Language this Loops works
Collection Variables Like Arrays, List and Strings or Any Command Line Arguments.
For each Loop First initialize a first Value which is Stored into the Collection Element
and then as loop do the Next Element will be Assigned to the foreach variable But
Remember we do not have to end foreach loop Explicitly by using Any Statement.
12 13
int[] evenNums; // integer array
C# Arrays Arrays type variables can be declared using var without square
brackets.
A variable is used to store a literal value, whereas an array is used to store multiple
literal values. Example: Array Declaration using var
var evenNums = new int[]{ 2, 4, 6, 8, 10};
An array is the data structure that stores a fixed number of literal values (elements)
of the same data type. Array elements are stored contiguously in the memory. var cities = new string[]{ "Mumbai", "London", "New York" };
In C#, an array can be of three types: single-dimensional, multidimensional, and If you are adding array elements at the time of declaration, then
jagged array. size is optional. The compiler will infer its size based on the number
of elements inside curly braces, as shown below.
Late Initialization
Console.WriteLine(evenNums[i]);
UpdateArray(nums);
16 17
Strings manipulation
In C#, a string is a sequence of characters. For example, "hello" is a string
containing a sequence of characters 'h' , 'e' , 'l' , 'l' , and 'o' .
// create a string
string str = "C# Programming";
Here, we have created a string named str and assigned the text "C#
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "Programiz";
// print string
Console.WriteLine(str1);
Console.WriteLine(str2);
Console.ReadLine();
}
}
}
Output
***********************************************************************************
C# Programming
Programiz
18 19
In the above example, we have created two strings 2. Join two strings in C#
named str1 and str2 and printed them.
We can join two strings in C# using the Concat() method. For example,
using System;
String Operations namespace CsharpString {
class Test {
C# string provides various methods to perform different operations on public static void Main(string [] args) {
strings. We will look into some of the commonly used string operations. // create string
string str1 = "C# ";
1. Get the Length of a string Console.WriteLine("string str1: " + str1);
To find the length of a string, we use the Length property. For example, // create string
string str2 = "Programming";
using System; Console.WriteLine("string str2: " + str2);
namespace CsharpString {
class Test { // join two strings
public static void Main(string [] args) { string joinedString = string.Concat(str1, str2);
In the above example, we have created two strings named str1 and str2 .
Output
Notice the statement,
string: C# Programming
Length: 14 string joinedString = string.Concat(str1, str2);
In the above example, the Length property calculates the total number of Here, the Concat() method joins str1 and str2 and assigns it to
characters in the string and returns it. the joinedString variable.
We can also join two strings using the + operator in C#. To learn more,
visit C# string Concat.
20 21
3. C# compare two strings
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
// create string
string str1 = "C# Programming";
string str2 = "C# Programming";
string str3 = "Programiz";
Console.ReadLine();
}
}
}
***********************************************************************************
Output
Boxing And Unboxing
string str1 and str2 are equal: True
string str1 and str3 are equal: False
Boxing In C#
In the above example, we have created 3 strings named str1 , str2 , • The process of converting a Value Type variable (char, int etc.) to
and str3 . Here, we are using the Equals() method to check if one string is a Reference Type variable (object) is called Boxing.
• Boxing is an implicit conversion process in which object type
equal to another.
(super type) is used.
22 23
• Description : First, we declare a Value Type variable num of the // value of num to be change
type int and initialise it with value 23. Now, we create a Reference num = 100;
Type variable obj of the type Object and assign num to it. This
System.Console.WriteLine
assignment implicitly results in the Value Type variable num to be ("Value - type value of num is : {0}", num);
copied and stored in Reference Type variable obj as shown in System.Console.WriteLine
below figure : ("Object - type value of obj is : {0}", obj);
}
}
Output:
Value - type value of num is : 100
Object - type value of obj is : 2020
Unboxing In C#
24 25
Preprocessor
Preprocessor Directives in C# tell the compiler to process the given information
before actual compilation of the program starts. It begins with a hashtag symbol (#)
and since these preprocessors are not statements so no semi-colon is appended at
the end. The C# compiler does not have a separate preprocessor, yet the directives
are processed as if there was one. There cannot be anything else in a line other than
/ C# implementation to demonstrate the preprocessor directive.
// the Unboxing
using System;
class GFG {
// Main Method
static public void Main()
{
// boxing
object obj = num;
// unboxing
int i = (int)obj;
// Display result
Console.WriteLine("Value of ob object is : " + obj);
Console.WriteLine("Value of i is : " + i);
}
}
namespace Preprocessor {
26 27
class Program { 9. }
10. }
static void Main(string[] args)
{
// Checking if symbol shape exists or not Output:
#if (shape)
11. Hello Namespace!
Console.WriteLine("Shape Exists");
#else
Console.WriteLine("Shape does not Exist");
C# namespace example: by using keyword
// Ending the if directive
Let's see another example of namespace where we are using "using" keyword so that
#endif
} we don't have to use complete name for accessing a namespace program.
}
} 1. using System;
Output: 2. using First;
Shape Exists 3. using Second;
4. namespace First {
5. public class Hello
*********************************************************************************
6. {
7. public void sayHello() { Console.WriteLine("Hello Namespace"); }
C# Namespaces 8. }
9. }
Namespaces in C# are used to organize too many classes so that it can be easy to
10. namespace Second
handle the application.
11. {
In a simple C# program, we use System.Console where System is the namespace and 12. public class Welcome
Console is the class. To access the class of a namespace, we need to use 13. {
namespacename.classname. We can use using keyword so that we don't have to use
14. public void sayWelcome() { Console.WriteLine("Welcome Namespace"); }
complete name all the time.
In C#, global namespace is the root namespace. The global::System will always refer to 15. }
the namespace "System" of .Net Framework. 16. }
17. public class TestNamespace
C# namespace example 18. {
1. using System;
19. public static void Main()
2. namespace ConsoleApplication1
20. {
3. {
21. Hello h1 = new Hello();
4. class Program
22. Welcome w1 = new Welcome();
5. {
23. h1.sayHello();
6. static void Main(string[] args)
24. w1.sayWelcome();
7. {
25. }
8. Console.WriteLine("Hello Namespace!");
28 29
26. } UNIT III
Output: C# Classes and Objects
Hello Namespace
Welcome Namespace Everything in C# is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and
brake.
class Car
Create an Object
An object is created from a class. We have already created the class
named Car, so now we can use this to create objects.
To create an object of Car, specify the class name, followed by the object
name, and use the keyword new:
Example
Create an object called "myObj" and use it to print the value of color:
class Car
30 1
A fully encapsulated class has getter and setter functions that are used to read and ID = 101
write data. This class does not allow data access directly. Name = Mohan Ram
Email = [email protected]
Here, we are creating an example in which we have a class that encapsulates properties
and provides getter and setter functions. ***********************************************************************
2 3
7. } 22. Employee e2 = new Employee(102, "Mahesh", 490000f);
8. public static void Main(string[] args) 23. e1.display();
9. { 24. e2.display();
10. Employee e1 = new Employee(); 25.
11. Employee e2 = new Employee(); 26. }
12. } 27. }
13. }
Output:
Output: 101 Sonoo 890000
Default Constructor Invoked 102 Mahesh 490000
Default Constructor Invoked
***************************************************************************
C# Parameterized Constructor
A constructor which has parameters is called parameterized constructor. It is used to
Inheritance
provide different values to distinct objects.
Inheritance (Derived and Base Class)
1. using System;
In C#, it is possible to inherit fields and methods from one class to another.
2. public class Employee We group the "inheritance concept" into two categories:
3. {
4. public int id; • Derived Class (child) - the class that inherits from another class
• Base Class (parent) - the class being inherited from
5. public String name;
6. public float salary; To inherit from a class, use the : symbol.
7. public Employee(int i, String n,float s)
In the example below, the Car class (child) inherits the fields and methods
8. { from the Vehicle class (parent):
9. id = i;
10. name = n; Example
11. salary = s;
12. } class Vehicle // base class (parent)
4 5
Polymorphism
}
class Car : Vehicle // derived class (child) Polymorphism and Overriding Methods
{ Polymorphism means "many forms", and it occurs when we have many
classes that are related to each other by inheritance.
public string modelName = "Mustang"; // Car field
Like we specified in the previous chapter; Inheritance lets us inherit fields
}
and methods from another class. Polymorphism uses those methods to
perform different tasks. This allows us to perform a single action in different
ways.
class Program
For example, think of a base class called Animal that has a method
{ called animalSound(). Derived classes of Animals could be Pigs, Cats, Dogs,
Birds - And they also have their own implementation of an animal sound (the
static void Main(string[] args) pig oinks, and the cat meows, etc.):
{
Example
// Create a myCar object
class Animal // Base class (parent)
Car myCar = new Car();
{
}
// Display the value of the brand field (from the Vehicle class) }
and the value of the modelName from the Car class
6 7
class Dog : Animal // Derived class (child) void run(); // interface method (does not have a body)
{ }
}
Example
// Interface
The output will be:
interface IAnimal
The animal makes a sound
{
********************************************* {
Another way to achieve abstraction in C#, is with interfaces. // The body of animalSound() is provided here
An interface is a completely "abstract class", which can only contain Console.WriteLine("The pig says: wee wee");
abstract methods and properties (with empty bodies):
}
Example }
// interface
class Program
interface Animal
{
{
static void Main(string[] args)
void animalSound(); // interface method (does not have a body)
{
8 9
myPig.animalSound();
} From the example above, it is not possible to create an object of the Animal
class:
***********************************************************************
Animal myObj = new Animal(); // Will generate an error (Cannot create
an instance of the abstract class or interface 'Animal')
Data abstraction is the process of hiding certain details and showing only
essential information to the user.
Abstraction can be achieved with either abstract Operator Overloading
classes or interfaces (which you will learn more about in the next chapter).
The concept of overloading a function can also be applied to operators.
The abstract keyword is used for classes and methods: Operator overloading gives the ability to use the same operator to do various
• Abstract class: is a restricted class that cannot be used to create
operations. It provides additional capabilities to C# operators when they are
objects (to access it, it must be inherited from another class). applied to user-defined data types. It enables to make user-defined
implementations of various operations where one or both of the operands are
of a user-defined class. Only the predefined set of C# operators can be
overloaded. To make operations on a user-defined data type is not as simple
• Abstract method: can only be used in an abstract class, and it does as the operations on a built-in data type. To use operators with user-defined
not have a body. The body is provided by the derived class (inherited data types, they need to be overloaded according to a programmer’s
from).
requirement. An operator can be overloaded by defining a function to it. The
An abstract class can have both abstract and regular methods: function of the operator is declared by using the operator keyword.
10 11
The following table describes the overloading ability of the various
• C#
operators available in C#
// C# program to illustrate the
using System;
namespace Calculator {
class Calculator {
number1 = num1;
number2 = num2;
The return type can be of any type except void for unary operators like !, ~, + // Function to perform operation
and dot (.) but the return type must be the type of ‘Type’ for – and ++
// By changing sign of integers
operators and must be a bool type for true as well as false operators. But
do remember that the true and false operators can be overloaded as pairs public static Calculator operator -(Calculator c1)
only. The compilation error arises if a class declares one of these operators {
without declaring the other. c1.number1 = -c1.number1;
The following syntax shows the use of Unary operator – c1.number2 = -c1.number2;
12 13
Syntax :
}
operator operator (object1, object2);
}
Here, second "operator" is a symbol that
denotes a binary operator.
class EntryPoint operator + (a, b);
{ Example :
Input : 200, 40
{ Input : 300, 20
Output : 320
using System;
calc = -calc;
namespace BinaryOverload {
}
public int number = 0;
}
}
// no-argument constructor
// parameterized constructor
Overloading Binary Operators
public Calculator(int n)
14 15
// Overloading of Binary "+" operator num1.display(); // Displays 200
return Calc3; }
} }
}
// function to display result
Output :
public void display()
200
{ 40
Console.WriteLine("{0}", number); 240
}
} *******************************************************************
Properties
class CalNum {
private variables can only be accessed within the same class (an outside class
// Driver Code has no access to it). However, sometimes we need to access them - and it
can be done with properties.
static void Main(string[] args)
16 17
{ get
{
get { return name; } // get method
return val[index];
set { name = value; } // set method }
} set
{
} val[index] = value;
}
}
Here,
An indexer allows us to access instances of a class using an index just like Example: C# indexer
an array.
using System;
class Program
{
// declare an array to store elements
private string[] studentName = new string[10];
***************************************************************************
// define an indexer
public string this[int index]
{
C# Indexer get
{
// return value of stored at studentName array
In C#, we define an indexer just like properties using this keyword followed return studentName[index];
}
by [] index notation. For example,
set
public int this[int index]
{
{
18 19
// assigns value to studentName 1. using System;
studentName[index] = value;
2. delegate int Calculator(int n);//declaring delegate
}
} 3.
4. public class DelegateExample
5. {
public static void Main()
6. static int number = 100;
{
// create instance of Program class 7. public static int add(int n)
Program obj = new Program(); 8. {
9. number = number + n;
// insert values in obj[] using indexer i.e index position
10. return number;
obj[0] = "Harry";
obj[1] = "Ron"; 11. }
obj[2] = "Hermoine"; 12. public static int mul(int n)
13. {
Console.WriteLine("First element in obj: " + obj[0]);
14. number = number * n;
Console.WriteLine("Second element in obj: " + obj[1]);
} 15. return number;
} 16. }
17. public static int getNumber()
Output 18. {
19. return number;
First element in obj: Harry
Second element in obj: Ron 20. }
21. public static void Main(string[] args)
22. {
********************************************************************************** 23. Calculator c1 = new Calculator(add);//instantiating delegate
24. Calculator c2 = new Calculator(mul);
Delegates 25. c1(20);//calling method using delegate
In C#, delegate is a reference to the method. It works like function pointer in C and C++. 26. Console.WriteLine("After c1 delegate, Number is: " + getNumber());
But it is objected-oriented, secured and type-safe than function pointer. 27. c2(3);
28. Console.WriteLine("After c2 delegate, Number is: " + getNumber());
For static method, delegate encapsulates method only. But for instance method, it
29.
encapsulates method and instance both.
30. }
The best use of delegate is to use as event. 31. }
Internally a delegate declaration defines a class which is the derived class Output:
of System.Delegate.
After c1 delegate, Number is: 120
After c2 delegate, Number is: 360
C# Delegate Example
**********************************************************************************
Let's see a simple example of delegate in C# which calls add() and mul() methods.
20 21
Collections o SortedList
In C#, collection represents group of objects. By the help of collections, we can perform 2) System.Collections classes
various operations on objects such as
These classes are legacy. It is suggested now to use System.Collections.Generic classes.
The System.Collections namespace has following classes:
o store object
o update object o ArrayList
o delete object o Stack
o retrieve object o Queue
o search object, and o Hashtable
o sort object
3) System.Collections.Concurrent classes
In sort, all the data structure work can be performed by C# collections.
The System.Collections.Concurrent namespace provides classes for thread-safe
We can store objects in array or collection. Collection has advantage over array. Array operations. Now multiple threads will not create problem for accessing the collection
has size limit but objects stored in collection can grow or shrink dynamically. items.
There are 3 ways to work with collections. The three namespaces are given below: o BlockingCollection
o ConcurrentBag
o System.Collections.Generic classes
o ConcurrentStack
o System.Collections classes (Now deprecated)
o ConcurrentQueue
o System.Collections.Concurrent classes
o ConcurrentDictionary
1) System.Collections.Generic classes o Partitioner
o Partitioner
The System.Collections.Generic namespace has following classes:
o OrderablePartitioner
o List **********************************************************************************
o Stack
o Queue
o LinkedList
o HashSet
o SortedSet
o Dictionary
o SortedDictionary
22 23
UNIT IV }
}
ERROR AND EXCEPTION HANDLING
• The exception can be handled using the System.Exception class of C#.
• An exception is defined as an event that occurs during the execution of a program
• The object of the type IndexOutOfRangeException is used to display a message to the
that is unexpected by the program code.
user about the exception that has occurred.
• The actions to be performed in case of occurrence of an exception is not known to
the program.
• In such a case, we create an exception object and call the exception handler code. Syntax:
• The execution of an exception handler so that the program code does not crash is
called exception handling. try
• Exception handling is important because it gracefully handles an unwanted event, an {
exception so that the program code still makes sense to the user.
// statements that may cause an exception
}
catch( Exception obj)
{
// handler code
}
} C# FILES
Working With Files
try { The File class from the System.IO namespace, allows us to work with files:
Example
// Try to access invalid index of array
using System.IO; // include the System.IO namespace
Console.WriteLine(arr[7]);
// An exception is thrown upon executing
// the above line File.SomeFileMethod(); // use the file class with methods
}
catch (IndexOutOfRangeException e) { Method Description
Example • The Dead State − It is the situation when the thread completes
execution or is aborted.
using System.IO; // include the System.IO namespace
The Main Thread
In C#, the System.Threading.Thread class is used for working with threads. It allows
string writeText = "Hello World!"; // Create a text string creating and accessing individual threads in a multithreaded application. The first
thread to be executed in a process is called the main thread.
File.WriteAllText("filename.txt", writeText); // Create a file and
write the content of writeText to it When a C# program starts execution, the main thread is automatically created. The
threads created using the Thread class are called the child threads of the main
thread. You can access a thread using the CurrentThread property of the Thread
string readText = File.ReadAllText("filename.txt"); // Read the class.
contents of the file
using System;
Console.WriteLine(readText); // Output the content using System.Threading;
namespace MultithreadingApplication {
class MainThreadProgram {
The output will be: static void Main(string[] args) {
Thread th = Thread.CurrentThread;
Hello World! th.Name = "MainThread";
Button Fires an event when a mouse click Represents a button on a form. Its text property determines the
occurs or the Enter or Esc key is caption displayed on the button’s surface.
pressed.
TextBox Accepts user input. Can be designed to accept single- or multi-line input. Properties allow
CheckBox Permits a user to select one or Consists of a check box with text or an image beside it. The check box it to mask input for passwords, scroll, set letter casing automatically,
more options. can also be represented as a button by and limit contents to read-only.
setting: checkBox1.Appearance = Appearance.Button. TreeView Displays data as nodes in a tree. Features include the ability to collapse or expand, add, remove, and
copy nodes in a tree.
CheckedListBox Displays list of items. ListBox with checkbox preceding each item in list.
-------------------------------------------------------------------
ComboBox Provides TextBox and ListBox Hybrid control that consists of a textbox and a drop-down list. It
functionality. combines properties from both the TextBox and the ListBox.
Menu Creation
DataGridView Manipulates data in a grid format. The DataGridView is the foremost control to represent relational An imperative part of the user interface in a Windows-based application is the menu.
GridView data. It supports binding to a database. The DataGridView was
introduced in .NET 2.0 and supersedes the DataGrid. A menu on a form is created with a MainMenu object, which is a collection of MenuItem
objects. You can add menus to Windows Forms at design time by adding the MainMenu
GroupBox Groups controls. Use primarily to group radio buttons; it places a border around the control and then adding menu items to it using the Menu Designer. Menus can also be
controls it contains.
added programmatically by adding one or more MainMenu controls to a form and
adding MenuItem objects to the collection.
ImageList Manages a collection of images. Container control that holds a collection of images used by other
controls such as the ToolStrip, ListView, and TreeView.
Adding Menu, Menu Items to a Menu
Label Adds descriptive information to a Text that describes the contents of a control or instructions for using a
First add a MainMenu control to the form. Then to add menu items to it add MenuItem
form. control or form.
objects to the collection. By default, a MainMenu object contains no menu items, so that
ListBox Displays a list of items—one or May contain simple text or objects. Its methods, properties, and the first menu item added becomes the menu heading. Menu items can also be
more of which may be selected. events allow items to be selected, modified, added, and sorted. dynamically added when they are created, such that properties are set at the time of
their creation and addition.
ListView Displays items and subitems. May take a grid format where each row represents a different item
and sub-items. It also permits items to be displayed as icons. 1. using System;
2. using System.Collections.Generic;
3. using System.ComponentModel;
MenuStrip Adds a menu to a form. Provides a menu and submenu system for a form. It supersedes
the MainMenu control. 4. using System.Data;
5. using System.Drawing;
6. using System.Linq;
Panel Groups controls. A visible or invisible container that groups controls. Can be made
FlowPanelLayout scrollable.
7. using System.Text;
TablePanelLayout 8. using System.Threading.Tasks;
FlowPanelLayout automatically aligns controls vertically or
9. using System.Windows.Forms;
horizontally. 10.
11.
12.
TablePanelLayout aligns controls in a grid.
13. namespace MenuTest
14. {
PictureBox Contains a graphic. Used to hold images in a variety of standard formats. Properties 15. public partial class MenuTest1 : Form
enable images to be positioned and sized within control’s borders. 16. {
ProgressBar Depicts an application’s progress. Displays the familiar progress bar that gives a user feedback 17. private MainMenu mainMenu;
regarding the progress of some event such as file copying. 18.
RadioButton Permits user to make one choice Represents a Windows radio button. 19. public MenuTest1()
among a group of options. 20. {
StatusStrip Provides a set of panels that Provides a status bar that is used to provide contextual status 21. InitializeComponent();
indicate program status. information about current form activities. 22. mainMenu = new MainMenu();
23. MenuItem File = mainMenu.MenuItems.Add("&File
Child windows per documents are One document per window is
"); Limits
allowed in MDI. enforced in SDI.
24. File.MenuItems.Add(new MenuItem("&New"));
25. File.MenuItems.Add(new MenuItem("&Open")); Container SDI is not a container
MDI is a container control.
26. File.MenuItems.Add(new MenuItem("&Exit")); Control control.
27. this.Menu = mainMenu;
28. MenuItem About = mainMenu.MenuItems.Add("&Abo MDI contains multiple documents
SDI contains one window
ut"); Operation which at a time appear as child
only at a time.
29. About.MenuItems.Add(new MenuItem("&About")); window.
SDI EXAMPLE
-------------------------------------------------------------
SDI AND MDI APPLICATIONS
BASIS OF
MDI SDI
COMPARISON
1. Frequent user: Who is familiar with the program and uses them to
MDI EXAMPLE control its more advance or dangerous facilities.
2. Infrequent user: Who is unfamiliar with the scope and use of the
program and who is using to learn the basic.
• The dialog boxes have buttons, combo boxes and other gizmos on
their surface.
• They can be placed where we need no conventional plan is
necessary.
• Every dialog box has at least one terminating command, a control
that activated, causes a dialog box to shut down and go away.
• Generally, we offer two terminating commands OK and CANCEL.
They are summoned from the menu. They are most frequently modal a derived type. You provide this method to enable derived classes to override the logic
dialog boxes, and they control a single function like printing inserting and for raising the event. A derived class should always call the OnEventName method of
many others.
the base class to ensure that registered delegates receive the event.
5) Bulletin dialog box
The following example shows how to declare an event named ThresholdReached. The
They are best characterized as a ubiquitous error.
event is associated with the EventHandler delegate and raised in a method
6) Process dialog box named OnThresholdReached.
They are like bulletins, are erected at the programs discretion rather than class Counter
the user request. Alters the user to the programs inability to respond {
public event EventHandler ThresholdReached;
normally.
protected virtual void OnThresholdReached(EventArgs e)
{
ThresholdReached?.Invoke(this, e);
}
the SerialDataReceivedEventHandler delegate includes The following example shows an event handler method
the SerialDataReceivedEventArgs class as one of its parameters. named c_ThresholdReached that matches the signature for the EventHandler delegate.
The method subscribes to the ThresholdReached event.
The EventArgs class is the base type for all event data classes. EventArgs is also the
class you use when an event doesn't have any data associated with it. When you create class ProgramTwo
{
an event that is only meant to notify other classes that something happened and static void Main()
{
doesn't need to pass any data, include the EventArgs class as the second parameter in var c = new Counter();
c.ThresholdReached += c_ThresholdReached;
the delegate. You can pass the EventArgs.Empty value when no data is provided.
// provide remaining implementation for the class
The EventHandler delegate includes the EventArgs class as a parameter. }
the event. Typically, you should use the same naming pattern as .NET and end your }
Event handlers
To respond to an event, you define an event handler method in the event receiver. This
method must match the signature of the delegate for the event you're handling. In the
event handler, you perform the actions that are required when the event is raised, such
as collecting user input after the user clicks a button. To receive notifications when the
event occurs, your event handler method must subscribe to the event.
UNIT V
ADO.NET Architecture
ADO.NET
1 2
The two key components of ADO.NET are Data Providers and DataSet Command
. The Data Provider classes are meant to work with different kinds of
data sources. They are used to perform all data-management operations The Command Object uses to perform SQL statement or stored
on specific databases. DataSet class provides mechanisms for procedure to be executed at the Data Source. The command object
managing data when it is disconnected from the data source. provides a number of Execute methods that can be used to perform the
SQL queries in a variety of fashions.
Data Providers
ASP.NET Command
The .Net Framework includes mainly three Data Providers for
ADO.NET. They are the Microsoft SQL Server Data Provider , DataReader
OLEDB Data Provider and ODBC Data Provider . SQL Server uses the
The DataReader Object is a stream-based , forward-only, read-only
SqlConnection object , OLEDB uses the OleDbConnection Object and
retrieval of query results from the Data Source, which do not update
ODBC uses OdbcConnection Object respectively.
the data. DataReader requires a live connection with the databse and
ASP.NET SQL Server Connection provides a very intelligent way of consuming all or part of the result
set.
ASP.NET OLEDB Connection
ASP.NET DataReader
ASP.NET ODBC Connection
DataAdapter
DataAdapter Object populate a Dataset Object with results from a Data
Source . It is a special class whose purpose is to bridge the gap between
the disconnected Dataset objects and the physical data source.
ASP.NET DataAdapter
Connection
The Connection Object provides physical connection to the Data
Source. Connection object needs the necessary information to
recognize the data source and to log on to it properly, this information
is provided through a connection string. ********************************************************
ASP.NET Connection
3 4
ADO Connection Object ConnectionTimeout Sets or returns the number of seconds to wait for a
connection to open
Connection Object
The ADO Connection Object is used to create an open connection to a data CursorLocation Sets or returns the location of the cursor service
source. Through this connection, you can access and manipulate a database.
Property Description
Method Description
ConnectionString Sets or returns the details used to create a
connection to a data source
5 6
CommitTrans Saves any changes and ends the current ConnectComplete Triggered after a connection starts
transaction
Note: You cannot handle events using VBScript or JScript (only Visual Basic,
Visual C++, and Visual J++ languages can handle events).
7 8
Collections
Properties
Collection Description
Property Description
ADO Command Object CommandType Sets or returns the type of a Command object
The major feature of the Command object is the ability to use stored queries
and procedures with parameters. State Returns a value that describes if the Command
object is open, closed, connecting, executing or
retrieving data
ProgID
set objCommand=Server.CreateObject("ADODB.command")
9 10
Methods
DataSetYou create an instance of a DataSet by calling the DataSet constructor. Optionally
specify a name argument. If you do not specify a name for the DataSet, the name is set to
"NewDataSet".
You can also create a new DataSet based on an existing DataSet. The new DataSet can be an
Method Description
exact copy of the existing DataSet; a clone of the DataSet that copies the relational structure
or schema but that does not contain any of the data from the existing DataSet; or a subset of
the DataSet, containing only the modified rows from the existing DataSet using
the GetChanges method. For more information, see Copying DataSet Contents.
Cancel Cancels an execution of a method
The following code example demonstrates how to construct an instance of a DataSet.
DataReader Object
Execute Executes the query, SQL statement or procedure in
the CommandText property
Collection Description The following example illustrates using a DataReader, where reader represents a
valid DataReader and command represents a valid Command object.
C#
Parameters Contains all the Parameter objects of a Command reader = command.ExecuteReader();
Object
Use the DataReader.Read method to obtain a row from the query results. You can
access each column of the returned row by passing the name or ordinal number of
the column to the DataReader. However, for best performance,
Properties Contains all the Property objects of a Command
the DataReader provides a series of methods that allow you to access column values
Object
in their native data types (GetDateTime, GetDouble, GetGuid, GetInt32, and so on).
For a list of typed accessor methods for data provider-specific DataReaders,
see OleDbDataReader and SqlDataReader. Using the typed accessor methods when
you know the underlying data type reduces the amount of type conversion required
when retrieving the column value.
******************************************************** The following example iterates through a DataReader object and returns two
columns from each row.
11 12
C# such as DataSet, DataTable, DataView, and DataViewManager to write Windows
Forms and Web Forms-based interactive database GUI applications.
static void HasRows(SqlConnection connection)
{
using (connection) The DataAdapter class for all data providers comes from the DbDataAdapter class,
{ which in turn comes from the DataAdapter class.
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM Categories;",
connection); An application doesn't create an instance of the DbDataAdapter interface directly, but
connection.Open();
instead, it creates an instance of a class that inherits IdbDataAdapter and
SqlDataReader reader = command.ExecuteReader(); DBDataAdapter. As you can see from Figure 5-39, many data provider-specific
classes implement IDbDataAdapter.
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}
Always call the Close method when you have finished using the DataReader object.
If your Command contains output parameters or return values, those values are not
available until the DataReader is closed.
************************************************************* The DataAdapter enables you to connect to a dataset and specify SQL strings for
retrieving data from or writing data to a DataSet. As you've seen at the beginning of
this article, a dataset represents in-memory cached data. An in-memory object frees
DataAdapter you from the confines of the specifics of the database and allows you to deal with the
data in memory. The DataAdapter serves as an intermediary between the database
and the DataSet.
DataAdapter: Adapting to Your Environment
Constructing a DataAdapter Object
A DataAdapter plays a vital role in ADO.NET architecture. It sits between a data source
and a dataset and passes data from the data source to the dataset, and vice versa,
with or without using commands. Now is the time you'll be using disconnected classes
13 14
The DataAdapter constructor has many overloaded forms. You can create a set the SelectCommand property of the data adapter. You can also see that
constructor with no arguments, pass a Command object, pass a Command object OleDbDataAdapter has no arguments as its constructor:
with Connection object as arguments, or any combination of these. You can also 1. // Create an OleDbDataAdapter object
specify a SQL statement as a string for querying a particular table or more than one 2. OleDbDataAdapter adapter = new OleDbDataAdapter();
table. You can also specify the connection string or a Connection object to connect 3. adapter.SelectCommand = new OleDbCommand (SQL, conn);
to the database.
Listing 5-41 creates a connection, builds a SQL statement using the SELECT query,
and passes the SQL string and the connection objects as SqlDataAdapter
constructor arguments. I've been using in the previous examples.
********************************************************
Executing a SELECT statement using SqlDataAdapter
1. string ConnectionString = "Integrated Security = SSPI;" +
"Initial catalog = Northwind; " + " Data Source = localhos DataTable
t; ";
2. string SQL = "SELECT CustomerID, CompanyName FROM Customer A DataTable, which represents one table of in-memory relational data, can be
s"; created and used independently, or can be used by other .NET Framework objects,
3. SqlConenction conn = new SqlConnection(ConnectionString); most commonly as a member of a DataSet.
4. You can create a DataTable object by using the appropriate DataTable constructor.
5. // open the connection
You can add it to the DataSet by using the Add method to add it to
6. conn.Open();
7. the DataSet object's Tables collection.
8. // Create a SqlDataAdapter object
9. SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn); You can also create DataTable objects within a DataSet by using
the Fill or FillSchema methods of the DataAdapter object, or from a predefined or
As discussed earlier, there is no difference in creating OleDb, SQL, or ODBC data
inferred XML schema using the ReadXml, ReadXmlSchema,
adapters. The only difference is the connection string. For example, the following
code snippet shows you how to create an OleDbDataAdapter object. or InferXmlSchema methods of the DataSet. Note that after you have added
a DataTable as a member of the Tables collection of one DataSet, you cannot add it
Listing 5-42 uses the Access2000 Northwind database and accesses all records of to the collection of tables of any other DataSet.
the Orders table by using a SELECT *SQL query.
When you first create a DataTable, it does not have a schema (that is, a structure). To
Executing a SELECT statement using OleDbDataAdapter define the schema of the table, you must create and add DataColumn objects to
1. // create a connection object
the Columns collection of the table. You can also define a primary key column for
2. string ConnectionString = @ "Provider =Microsoft.Jet.OLEDB
.4.0; " + "Data source = c:\\ Northwind.mdb"; the table, and create and add Constraint objects to the Constraints collection of the
3. string SQL = "SELECT * FROM orders"; table. After you have defined the schema for a DataTable, you can add rows of data
4. OleDbConnection conn = new OleDbConnection(ConnectionStrin to the table by adding DataRow objects to the Rows collection of the table.
g);
5. You are not required to supply a value for the TableName property when you create
6. // open the connection a DataTable; you can specify the property at another time, or you can leave it empty.
7. conn.Open(); However, when you add a table without a TableName value to a DataSet, the table
8.
will be given an incremental default name of TableN, starting with "Table" for Table0.
9. // create an OleDbDataAdapter objecto
10. OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, conn
Note
);
You can also use DataAdapter's Command properties by using the Command object We recommend that you avoid the "TableN" naming convention when you supply
with OleDbDataAdapter. For example, the following code uses OleDbCommand to a TableName value, because the name you supply may conflict with an existing
15 16
default table name in the DataSet. If the supplied name already exists, an exception 8.
9. namespace WindowsFormsApp
is thrown. 10. {
11. public partial class Form1 : Form
The following example creates an instance of a DataTable object and assigns it the 12. {
name "Customers." 13. public Form1()
14. {
15. InitializeComponent();
C#Copy 16. }
DataTable workTable = new DataTable("Customers"); 17. }
18. }
19. public class Form1 : Form
The following example creates an instance of a DataTable by adding it to 20. {
the Tables collection of a DataSet. 21. private DataGridView dataGridView1 = new DataGridView();
22. private BindingSource bindingSource1 = new BindingSource();
C#Copy 23. private SqlDataAdapter dataAdapter = new SqlDataAdapter();
24. private Button reloadButton = new Button();
DataSet customers = new DataSet(); 25. private Button submitButton = new Button();
DataTable customersTable = customers.Tables.Add("CustomersTable"); 26.
27. [STAThread()]
28. public static void Main()
******************************************************** 29. {
30. Application.Run(new Form1());
DATAGRIDVIEW AND DATABINDING 31. }
32.
33. // Initialize the form.
The DataGridView control supports the standard Windows Forms data binding 34. public Form1()
model, so it can bind to a variety of data sources. Usually, you bind to 35. {
a BindingSource that manages the interaction with the data source. 36. dataGridView1.Dock = DockStyle.Fill;
37.
The BindingSource can be any Windows Forms data source, which gives you great 38. reloadButton.Text = "Reload";
flexibility when choosing or modifying your data's location. For more information 39. submitButton.Text = "Submit";
about data sources the DataGridView control supports, see the DataGridView control 40. reloadButton.Click += new EventHandler(ReloadButton_Click);
41. submitButton.Click += new EventHandler(SubmitButton_Click);
overview. 42.
43. FlowLayoutPanel panel = new FlowLayoutPanel
Visual Studio has extensive support for data binding to the DataGridView control. For 44. {
more information, see How to: Bind data to the Windows Forms DataGridView 45. Dock = DockStyle.Top,
46. AutoSize = true
control using the Designer. 47. };
48. panel.Controls.AddRange(new Control[] { reloadButton,
To connect a DataGridView control to data: submitButton });
49.
1. Implement a method to handle the details of retrieving the data. The 50. Controls.AddRange(new Control[] { dataGridView1, panel });
51. Load += new EventHandler(Form1_Load);
following code example implements a GetData method that initializes 52. Text = "DataGridView data binding and updating demo";
a SqlDataAdapter, and uses it to populate a DataTable. It then binds 53. }
the DataTable to the BindingSource. 54.
55. private void GetData(string selectCommand)
2. In the form's Load event handler, bind the DataGridView control to 56. {
the BindingSource, and call the GetData method to retrieve the data. 57. try
3. using System; 58. {
4. using System.Data; 59. // Specify a connection string.
5. using System.Data.SqlClient; 60. // Replace <SQL Server> with the SQL Server for your
6. using System.Globalization; Northwind sample database.
7. using System.Windows.Forms;
17 18
61. // Replace "Integrated Security=True" with user login 109. // Update the database with changes.
information if necessary. 110. dataAdapter.Update((DataTable)bindingSource1.DataSource);
62. String connectionString = 111. }
63. "Data Source=<SQL Server>;Initial Catalog=Northwind;" +
64. "Integrated Security=True";
65.
******************************************************
66. // Create a new data adapter based on the specified query.
67. dataAdapter = new SqlDataAdapter(selectCommand,
connectionString);
68.
69.
and
// Create a command builder to generate SQL update, insert, Connecting to a database using OLEDB
70. // delete commands based on selectCommand.
71. SqlCommandBuilder commandBuilder = new C# and .Net can work with a majority of databases, the most common
SqlCommandBuilder(dataAdapter);
72. being Oracle and Microsoft SQL Server. But with every database, the logic
73. // Populate a new data table and bind it to the behind working with all of them is mostly the same.
BindingSource.
74. DataTable table = new DataTable
75. { In our examples, we will look at working the Microsoft SQL Server as our
76. Locale = CultureInfo.InvariantCulture database. For learning purposes, one can download and use
77. };
78. dataAdapter.Fill(table); the Microsoft SQL Server Express Edition, which is a free database
79. bindingSource1.DataSource = table; software provided by Microsoft.
80.
81. // Resize the DataGridView columns to fit the newly loaded
content. In working with databases, the following are the concepts which are
82. dataGridView1.AutoResizeColumns( common to all databases.
83. DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
84. }
85. catch (SqlException) 1. Connection – To work with the data in a database, the first obvious
86. { step is the connection. The connection to a database normally
87. MessageBox.Show("To run this example, replace the value of
the " + consists of the below-mentioned parameters.
88. "connectionString variable with a connection string 1. Database name or Data Source – The first important
that is " +
89. "valid for your system."); parameter is the database name to which the connection
90. } needs to be established. Each connection can only work
91. }
92. with one database at a time.
93. private void Form1_Load(object sender, EventArgs e) 2. Credentials – The next important aspect is the username
94. {
95. // Bind the DataGridView to the BindingSource and password which needs to be used to establish a
96. // and load the data from the database. connection to the database. It ensures that the username
97. dataGridView1.DataSource = bindingSource1;
98. GetData("select * from Customers"); and password have the necessary privileges to connect to
99. } the database.
100.
101. private void ReloadButton_Click(object sender, EventArgs e) 3. Optional parameters – For each database type, you can
102. { specify optional parameters to provide more information
103. // Reload the data from the database.
104. GetData(dataAdapter.SelectCommand.CommandText); on how .net should handle the connection to the
105. } database. For example, one can specify a parameter for
106.
107. private void SubmitButton_Click(object sender, EventArgs e) how long the connection should stay active. If no
108. { operation is performed for a specific period of time, then
19 20
the parameter would determine if the connection has to We will see a simple Windows forms application to work with
be closed. databases. We will have a simple button called “Connect” which
2. Selecting data from the database – Once the connection has been will be used to connect to the database.
established, the next important aspect is to fetch the data from the
database. C# can execute ‘SQL’ select command against the So let’s follow the below steps to achieve this
database. The ‘SQL’ statement can be used to fetch data from a
Step 1) The first step involves the creation of a new project in Visual
specific table in the database.
Studio. After launching Visual Studio, you need to choose the menu
3. Inserting data into the database – C# can also be used to insert
option New->Project.
records into the database. Values can be specified in C# for each
row that needs to be inserted into the database.
4. Updating data into the database – C# can also be used to update
existing records into the database. New values can be specified in
C# for each row that needs to be updated into the database.
5. Deleting data from a database – C# can also be used to delete
records into the database. Select commands to specify which rows
need to be deleted can be specified in C#.
Ok, now that we have seen the theory of each operation, let’s jump
into the further sections to look at how we can perform database
operations in C#.
SQL Command in c#
SqlCommand in C# allow the user to query and send the commands
to the database. SQL command is specified by the SQL connection
object. Two methods are used, ExecuteReader method for results
of query and ExecuteNonQuery for insert, Update, and delete
commands. It is the method that is best for the different
commands.
How to connect C# to Database
Let’s now look at the code, which needs to be kept in place to
create a connection to a database. In our example, we will connect
to a database which has the name of Demodb. The credentials used
to connect to the database are given below
Username – sa
Password – demo123
21 22
using System; Inserting is usually a straightforward task. It begins with the simple
using System.Collections.Generic;
using System.ComponentModel;
problem of inserting a single row. Many times, however, it is more
using System.Data; efficient to use a set-based approach to create new rows. To that end,
using System.Data.SqlClient;
using System.Drawing; you’ll also find techniques for inserting many rows at a time.
using System.Linq;
using System.Text;
using System.Threading.Tasks; Likewise, updating and deleting start out as simple tasks. You can update
using System.Windows.Forms;
one record, and you can delete one record. But you can also update whole
namespace DemoApplication1
{ sets of records at once, and in very powerful ways. And there are many
public partial class Form1 : Form handy ways to delete records. For example, you can delete rows in one
{
public Form1() table depending on whether or not they exist in another table.
{
InitializeComponent();
} SQL even has a way, a relatively new addition to the standard, by which
private void button1_Click(object sender, EventArgs e) you can insert, update, and delete all at once. That may not sound like too
{
string connetionString; useful a thing now, but the MERGE statement represents a very powerful
SqlConnection cnn; way to bring a database table into sync with an external source of data
connetionString = @"Data Source=WIN-50GP30FGO75;Initial
Catalog=Demodb;User ID=sa;Password=demol23"; (such as a flat file feed from a remote system). Check out Section in this
cnn = new SqlConnection(connetionString);
cnn.Open(); chapter for details.
MessageBox.Show("Connection Open !");
cnn.Close();
} 4.1. Inserting a New Record
}
}
Problem
********************************************************************************
You want to insert a new record into a table. For example, you want to
insert a new record into the DEPT table. The value for DEPTNO should be
23 24
50, DNAME should be “PROGRAMMING”, and LOC should be However, if you do not list your target columns, you must insert into all of
“BALTIMORE”. the columns in the table, and be mindful of the order of the values in the
VALUES list; you must supply values in the same order in which the
Solution database displays columns in response to a SELECT * query.
Use the INSERT statement with the VALUES clause to insert one row at a
4.2. Inserting Default Values
time:
Problem
insert into dept (deptno,dname,loc)
A table can be defined to take default values for specific columns. You
values (50,'PROGRAMMING','BALTIMORE') want to insert a row of default values without having to specify those
values. Consider the following table:
For DB2 and MySQL you have the option of inserting one row at a time or
create table D (id integer default 0)
multiple rows at a time by including multiple VALUES lists:
/* multi row insert */ You want to insert zero without explicitly specifying zero in the values list
of an INSERT statement. You want to explicitly insert the default,
insert into dept (deptno,dname,loc) whatever that default is.
25 26
insert into D default values 3 where empno in ( select empno from emp_bonus )
The DEFAULT VALUES clause causes all columns to take on their Discussion
default values.
The results from the subquery represent the rows that will be updated in
table EMP. The IN predicate tests values of EMPNO from the EMP table
Updating when Corresponding Rows Exist
to see whether they are in the list of EMPNO values returned by the
subquery. When they are, the corresponding SAL values are updated.
Problem
You want to update rows in one table when corresponding rows exist in Alternatively, you can use EXISTS instead of IN:
another. For example, if an employee appears in table EMP_BONUS, you
want to increase that employee’s salary (in table EMP) by 20 percent. The update emp
following result set represents the data currently in table EMP_BONUS:
set sal = sal*1.20
from emp_bonus
EMPNO ENAME
---------- ---------
where emp.empno=emp_bonus.empno )
7369 SMITH
7900 JAMES
27 28
You may be surprised to see NULL in the SELECT list of the EXISTS
delete from emp where deptno = 10
subquery. Fear not, that NULL does not have an adverse effect on the
update. In my opinion it increases readability as it reinforces the fact that,
unlike the solution using a subquery with an IN operator, what will drive Discussion
the update (i.e., which rows will be updated) will be controlled by the
By using a WHERE clause with the DELETE command, you can delete a
WHERE clause of the subquery, not the values returned as a result of the
subset of rows in a table rather than all the rows.
subquery’s SELECT list.
4.14. Deleting a Single Record
Deleting All Records from a Table
Problem
Problem
You wish to delete a single record from a table.
You want to delete all the records from a table.
Solution
Solution
This is a special case of “Deleting Specific Records.” The key is to ensure
Use the DELETE command to delete records from a table. For example, to
that your selection criterion is narrow enough to specify only the one
delete all records from EMP:
record that you wish to delete. Often you will want to delete based on the
primary key. For example, to delete employee CLARK (EMPNO 7782):
delete from emp
When using the DELETE command without a WHERE clause, you will Discussion
delete all rows from the table specified.
Deleting is always about identifying the rows to be deleted, and the impact
of a DELETE always comes down to its WHERE clause. Omit the
Deleting Specific Records
WHERE clause and the scope of a DELETE is the entire table. By writing
Problem
conditions in the WHERE clause, you can narrow the scope to a group of
records, or to a single record. When deleting a single record, you should
You wish to delete records meeting a specific criterion from a table. typically be identifying that record based on its primary key or on one of
its unique keys.
Solution
Use the DELETE command with a WHERE clause specifying which rows ************************************************************
to delete. For example, to delete all employees in department 10: **********
29 30
31