Vous êtes sur la page 1sur 149

NagaRaj

.Net -->C#

Sri Sai Ram


C# Class Note Book (Bangar Raju)
Dt:04-02-2010

COBOL

Business Application

Pascal

Scientific Application

Fort on

Mathematic Application

C Language is a generic language.


Drawback:-Reusability (Size of programming will be to be increase), Security(C Not Secured).
In Object oriented programming languages will available Reusability, Security.
Ex: - C++
In 90s New Problem will be acquired, that is flat-form dependency (Developed On one
Language), Internet cable Exiting.
Windows will not be secured, because its a flat-form dependency.
Yahoo Messenger is working LINUX Windows.
Google also working LINUX Windows.
Java is a flat-form independency.
Visual Basic Microsoft its going to be a user friendly language.
There is a use in UPPER Case Key board letters, LOWER Case Key board letters restrictions.
Repaid application will be fast.
VB - Worked in only windows.
SMC Simple Manage C (Same as JAVA)
Introduction: .NET is a collection of languages
Ex: - 20 languages minimum.
COBOL is dependent on .Net.
COBOL & Java is Complete different.
COBOL & .NET Machining too, Style is same.
SMC nothing but C#.
C# is Case Sensitive.
C, C++, Java object oriented programs, Reusability.
C, C++, Java Reusable only with in Language.
.Net Reusability all 20 Languages.
Ex:-C# used In VB, COBOL, and J #.
Language intractability.
Do you learning .Net your are good application developer.
But not good programmer.
Do you learning Java your are good Programmer.
But not good Application developer.

*** END OF THE DAY ***

Naresh Tech. Class Notes

Hari

Page1

NagaRaj
.Net -->C#

Sri Sai Ram

Dt: 05-02-2010
Flat-form Dependency:Machine code is prepared to Operating System.
Source code Compiled Machine code (or) Native code (exe)
Machine code Pro: - compile windows machine code prepaid OS.
Windows Machine: What is meant by flat-form dependency?
In this approach the source code when complied generates machine code (or) native code (or)
executive code.
The problem with machine code is if was generated an Operating System.
It can be executed only within the Operating System.
Because its get proposed according to the Operating System.

In the above case as the machine code (exe) is generated to execute on windows the other
operating system will not be capable to run the code. So it is run on windows but not on UNIX.
Flat-form Independency:Java:- Source CodeCompiled Byte code JVM Machine Code.

Byte code: - This cant understand any Operating System.


JVM run the code.
The JVM is a byte code, its a Target code,
JVM is not a Independent, its depended.
Window will be use window JVM;UNIX will be use Unix JVM.
What is the mean by flat-form independent?
In the approach the source code when compiled gets converted into intermediate code (seemly
finished).
This intermediate code can be carried and executed on.
Provided software which is required to convert the intermediate code into machine code was
installed.
In turns of java byte code was the intermediate code which can be executed on any machine
provided JVM was install on it.
This will be taken the responsibility of convinced byte code according to the Operating System.

Naresh Tech. Class Notes

Hari

Page2

NagaRaj
.Net -->C#

Sri Sai Ram

In this case JVM (Java Virtual Machine) is converting the byte code in to Machine code specific
the Operation System.
JVM on dependent on the Operating System.
Java:- Source

Compiled

Byte code

Byte code JVM (Win) Windows Machine Code


Byte code JVM (UNIX) Unix Machine Code
Byte code JVM (MAC) Windows Machine Code
.NET Languages:

CIL -- Common Intermediate Language Code.


CLR -- Common Language Runtime.
VES
-- Vertical Execution System.
Theflat-form independency provided under .Net language is similar to that of java.
Where the byte code knows called as CIL Code.
CIL is production name is MSIL Code (Micro Soft Intermediate Language Code).
This IL Code can be carry is executed provided the CLR (Same as JVM).

*** END OF THE DAY ***

Dt: 06-02-2010
Naresh Tech. Class Notes

Hari

Page3

NagaRaj
.Net -->C#

Sri Sai Ram

All Compilers will be generating in same CIL code.


Compilation and execution process in case of .Net languages take place as follows:

All the .Net languages required a specific languages compiler for complication of the program.
But every language after compilation ha to generate the same type of code that is CIL.
It is taken by the CIR to convert into machine code.
As all language over generating the same IL code.
Code generated by one language can be consumed from the other languages providing our
intractability language. It is called as language independency.

.NET:-- It was a system which can be used in the development of various kind of application like,

1).
Desktop (CUI, GUI)
2).
Web.
3).
Mobile
CUI

Character user interface.


GUI

Graphical user interface.


Languages
C#, VB.Net..
Technologies
ASP.Net, ADO.Net....
Servers

Web Server, Data Base Server


Under.Net we came a craze overuse thing like Langs, Technologies, Servers, ext
Under language we are provided with Number of Languages to program like C#, VB, J#, VC++,
ext
Under technologies we have be provided ASP.Net(Web Application Development)
ADO.Net (Data Base Communication), ext...
Server play a key role in develop on any application like data base servers(SQL server) web
servers(IIS), site Administration server (SHARE POINT), Integration Server (Biz Talk).
COM (Computer Object Model), before .Net Micro Soft ware use COM.
Micro Soft Inter chose.Net resolved the problem under its own traditional Technologies COM.
Intermediate Code will control on JVM (or) CLR.
JVM (or) CLR will be called Frame work.
Use of frame work:Operating System Independency, Security, and Memory maintains
framework.
Managed Code

Flat form Independency.


Unmanaged Code

Flat form Dependency.


*** END OF THE DAY ***

Dt: 08-02-2010
Frame work:Naresh Tech. Class Notes

Hari

Page4

NagaRaj
.Net -->C#

Sri Sai Ram

It was Software which makes the functionality of a Operating System & makes the code to
execute under its control.
By default Machine code execute directly under the control of Operating System.
Which as intermediate code execute under the control of the frame fork.

The Advantage of Executing intermediate code under Frame Work will be,
1. Flat form indecency (or) Independency.
2. Security.
3. Memory Management.
Because of the above feature what it provides the code which execute under the frame work
environment is known as managed code and the code which execute directly under the Operating
system is known as unmanaged code.
Frame work is unmanaged code.
NGWS

Next Generation Windows System.


The development of .Net frame work has bean stored in the late 90s originally under the name
of NGWS.
ISO

International Standard Organization.


Ex: - C, C++
ECMA

Erosion Computer Manu factional Association.

To develop the.Net Frame work Microsoft has first prepared a set of Specification known as CLI
Speciation (Common language infrastructure).
Those speciation ware standardized under ISO & ECMA.
NOTE: - The CLI specifications were open, which gives a chance for every one to developed
.Net Frame work.
CLI Specifications:- CLI specification covers the following rules,

CLS
CTS
BCL
VES

Naresh Tech. Class Notes

Common language specification.


Common Type Specification.
Base Class Library.
Virtual execution system.

Hari

Page5

NagaRaj
.Net -->C#

Sri Sai Ram

CLS: - A set of Base rules all the .Net languages have to adapt to interoperate each other. That is
all languages after compilation of the generate the same type of codes known as common
language specification.
CTS:-A carding to this all the types under .Net languages was to adapt the some data types
structure. In the sance sizes of the types should be uniformed between the languages.
C# is a case sensitive (lower case).
VB.Net Not a case sensitive (Starting latter Upper Case).
As every .Net language has been derided from an existing language the name of under the
language might be difference, but there sizes will be uniform.
Every type used in every language after compilation has to be converted into IL types.

Every type used under every language is getting converted to IL.


But when it gets consumed from any other language it set declared in the other language
understandable format only.

NOTE: -CLS, CTS were foundation for the language the inter operability which was made
possible under .Net languages.

*** END OF THE DAY ***

Naresh Tech. Class Notes

Hari

Page6

NagaRaj
.Net -->C#

Sri Sai Ram

Dt: 09-02-2010
Library:-A set of prepaid functionalities.
Base class Library (BCL):- A library is a set of predefined functionalities were every language
provides the languages.
Libraries are traditional language were specifies to the language. Were as libraries under .Net
languages were common to all languages.
Microsoft provided the libraries in the form of base class library for congestion in .Net languages.
Most of the base class libraries were implemented in c# language.

NOTE:- Base class libraries were the best example


for language intractability provided under .Net
languages.
BCL is a part frame work class library.
Frame work class library (FCL):- It was a contractive set of libraries that was provided by
Microsoft for the execution of .Net framework & ASP.Net runtime. Under FCL BCL was only a part
what we can consumed.
CLR is also a virtual execution System.
Virtual execution system (VES):- As we were heavier time all the high level .Net languages get
converted to IL code after compilation.
This IL code can be carried & executed as any machine provided and Specific virtual system is
available.
Which takes the responsibility of learning IL code into machine code according to Operating
System and Hardware.

Note:- The virtual execution system was the foundation for Operating System independency which
was make possible under .Net languages.
Following the above CLI specifications Microsoft has implemented party company mono
(Subsidiary of novel) has implemented the frame work for few other machines like UNIX, Linux,
Sun Solaris, and MAC-OS.
Note:- .Net has theoretically flat form independent between there is a chance of implemented the
frame work for any Operating System making use of the open CLI specification. But practically
implementation was given only for few machines.
The .Net framework has launched in the year 2000 as 1.0 Beta 1(trail version) from then
number of changes made to it were the current version was 4.0.
Naresh Tech. Class Notes

Hari

Page7

NagaRaj
.Net -->C#

Sri Sai Ram

Versions release of .Net framework

20002001200220032005200620072009-

1.0 Beta 1
1.0 Beta 2
1.0 RTM
1.1
2.0
3.0
3.5
4.0

Important Data:ADO.Net

Communication with database.

ASP.Net

For developing to web application.

RTM

Realize to Manufacture (its a production version).

WPF

Windows Prosecution foundation.

WCF

Windows Communication Foundation.

WF

Windows workflow function (Its only for administration).

Card Space

Its only for administration.

Modern Technologies

3.0 Version

3.5 Version
LINQ
ADO.Net
Entity Framework.

*** END OF THE DAY ***

Dt: 10-02-2010
Naresh Tech. Class Notes

Hari

Page8

NagaRaj
.Net -->C#

Sri Sai Ram

.Net Frame Work Architecture:-

Common Language Run Time: -Its the code component under the .Net framework which was
Responsible in convention IL code into machine & execute it.
Base Class Library (BCL):- It was set of common functionalities the available through out all
the .Net languages.
Win forms technologies is used in the development of windows application (Graphic user
interfaces).
ASP.Net Technology is used in the development of web applications using .Net languages.
ADO.Net Technology is used for communication with data Sources (Data base file, exe
WPF (Window Prosecution foundation) was a technology all so used in the development of GUI
only. With a support for Graphics, animations, 2D & 3D Images. Which was not available under
traditional win forms.
WCF (Windows Communication foundation)is a technology used in the development of
distributed application.
LinqLanguage integrated query was also used for interaction with data sources, objects and
collections.
ADO.Net Entity Framework is similar to link but a execution for traditional ADO.Net.
Futures of .Net:- Language Independency: the .Net framework introduces a common type system, or CTS & CLS
Specification defines all possible data types and programming constructs supported by the CLR
and How they may or may not interact with each other.
Because of this feature the .Net framework support the exchanges of instances of types between
programs written in any of the .Net languages.
BCL:- The BCL part of Framework Class Library (FCL),is a library of functionality available to
all languages using the .Net framework. The BCL provides classes which encapsulate a number
of common functions.

Naresh Tech. Class Notes

Hari

Page9

NagaRaj
.Net -->C#

Sri Sai Ram

Portability:- The design of the .Net framework allows it to theoretically be flat form independent
and thus cross flat form compatible, that is a program written to use the framework should run
without changes on any type of system for which the framework is implemented.
Microsoft implementations of the framework cover windows. In addition Microsoft submits the
specifications for CLI (Which includes core class, libraries, CTS, and the CIL)to both ECMA &
ISO, Making them available as open standards.
This makes it possible for third parties to create compatible implementation of the framework on
other flat form.
Simplified deployment: - Installation of computer software must be carefully managed to ensure
that it dont interface with prevision ally installed software and it conforms to increasingly
stringent security requirement.
The .Net framework includes design features and tools like packing and deployment that help
address those requirements.

*** END OF THE DAY ***

Dt: 11-02-2010
Common Run Time Engine:Naresh Tech. Class Notes

Hari

Page10

NagaRaj
.Net -->C#

Sri Sai Ram

Programming language on the .Net framework compiled into an IL known as CIL. In


Microsoft implement the IL is not interpreted but rather compiled in a manner known as JIT (Just-InTime) compiler into native code.
In this from of conversions it adapt few optimization techniques like,
1. Conversion graduals during the program execution.
2. Conversion of only the request code which should be executed.
3. Strong of the converted code in volatile memory for next time use.

Memory Management: It is the act of managing computer memory. In its simple form this involves providing
ways to allocate pretensions of memory to programs but their request & Freeing it for reuse when
no longer needed.
The management of main memory is critical to the computer system. In this process it user the
Garbo collection which is the automated allocation and de-allocation of computer memory
resources for a program.
This is generally implemented of the programs language level and is in opposite to named
memory management. The explicitly memory allocation and de-allocation of computer memory
resources.
In computer science, garbage collection is a from of automatic memory management. The
garbage collection or just collection attempts to radian garbage or memory used by objects that
will never be accessed again by the application.Garbage Collection was invented by Jun
Mccarthy around 1959 to solve the problem of manual memory management.
Inter-operability :( Technology Inter-Operability):COM (Computer Object Model) it was a specification which advices not build
software as a monolithic unit (single unit).In spite it advises building the software by dividing into
smaller components or libraries and then integrates as software, which provides the feature like ease
maintenance of software and Reusability.

Naresh Tech. Class Notes

Hari

Page11

NagaRaj
.Net -->C#

Sri Sai Ram

COM is operation system dependent specially windows.


Intractability:Because introduction between older and newer application is commonly required the .Net framework
provides means to access functionality they was implemented in programmer that executes outside the
.Net environment in this process access to COM components is provided under the system dot runtime
dot intractability services of the frame work.

RCM: -Runtime callable wrapper in exposes the unmanaged COM interfaces as Managed .Net interfaces
to a .Net application.
CCW:-COM Callable wrapper this exposes managed .Net interfaces as unmanaged COM interfaces to a
COM application.

*** END OF THE DAY ***


Dt: 12-02-2010
Concerns & Criticisms related to .Net: Applications running in a managed environment such as the Microsoft frameworks CLR or
Javas JVM tend to require more system resources than similar applications that access
machine resources more directly.
Naresh Tech. Class Notes

Hari

Page12

NagaRaj
.Net -->C#

Sri Sai Ram

Some application, however, have been shown to perform better in .Net than in their native
version.
This could be due to the runtime optimization made possible in Just-In-Time compilation of
managed code, or other aspects of the CLR like Garbage collection.
As JIT languages can be more easily reverse engineered than native code to algorithms used
by an application there is concern over possible lass of trade secrets and the by passing of
license control machines many obfuscation techniques already developed, however, can help
to prevent this; indeed Microsoft visual studio 2005(.Net 2.0) includes such a tool.
In a managed environment such as the Microsoft frameworks CLR or Javas JVM the
regularly occurring Garbage Collection for Declaiming memory suspends execution of the
application for an unpredictable lapse of time (Typically not more than few milliseconds).
Since the framework is not preinstalled on older versions of windows an application that
requires it must verity that it is present and if it is not, guides the user to install it.
Newer versions of the framework (3.0 & up) and not pre-installed on any version of the
windows Operating System, as some developers have expressed concerns about the large
size.
C Sharp (Programming Language): C# is an object oriented programming language developed by Microsoft as part of the .Net
initiative and later approved as a standard by ECMA and ISO.
Ander Hejlsberg leads development of the C# language, which has a procedural, object oriented
syntax based on C++ and influences from as pets of several other programming languages (most
notably Delphi & Java) with a particular emphasis on simplification.
History: During the development of .Net, the Class Libraries were originally written in a language called
Simple Managed C (SMC).
In January 1999, Anders Hejlsberg formed a team to build a new language at that time called
Cool, later the language had been renamed C# and the class libraries and ASP.Net runtime had
been ported to C#.
C#s principal designer and lead architect at Microsoft is Anders Hejlsberg, who was previously
involved with the design of Visual, J++, Borland Delphi and Turbo Pascal Languages.
In interviews & technical papers he has stated that flaws in most major programming languages
(Ex: - C++, Java, Delphi and Smalltalk) drove the fundamentals of CLR, which, in turn drove the
design of C# programming language it self.

*** END OF THE DAY ***

Dt: 15-02-2010
Design Goals: The ECMA standard list these design goals for C#.
It is intended to be a simple, modern, general purpose and object oriented programming language.
The language should include strong type checking, array bounds checking, and detection of
attempts to use uninitialized variables, sources code portability and automatic garbage collection.
Naresh Tech. Class Notes

Hari

Page13

NagaRaj
.Net -->C#

Sri Sai Ram

The language is extended for use in developing software components that can take advantages of
distributed environments.
Programmer portability is very important especially for those programmer already familiar with
C and C++.
Support for intended to be suitable for writing applications for both hosted and embedded
systems.
Versions: -

1.0, 1.5, 2.0(ECMA), 3.0

Note: -C# 3.0 is not currently standardized by any standards organization, but it is expected that it will
also become an ECMA & then standard as its early versions. Features of C# 2.0:

Partial classes which allow class implementation across more than one source file.
Generics or parameterized types.
Static class that cannot be in satiated, and that only allows static members.
Anonymous delegates.
The accessibility of property assessors can be set independently.
Null able value types which provides improved interaction with SQL databases.
Coalesce operator (??) returns the first of its operands which not null (or null, if no such operated
exists).

Features of C# 3.0:

Language integrated query.


Object initializes and collection initializes.
Anonymous types.
Implicitly typed arrays.
Lambda expressions.
Automatic properties.
Partial methods.
C is procedural oriented language.
Programming structure and various languages.

C Program
Collection of functions.
Void main() <- entry point
{
- Call the function from here
}
Procedural programming language like C var a collection of function. Were these function var
expressly called for the main function our execution.
Most of the languages var designed in such a way these execution stands from main, which
consider as the entry point of a programming.
Procedural programming languages supports from few criticizers like lack of security and
reusability.
To provide these purposes object oriented languages come into existed.
Wrapper is protected the container.
Class is a user defined data types.
Structure== class (both are same)
int
=
100
Invalid
int x =
100
Valid
Naresh Tech. Class Notes

Hari

Page14

NagaRaj
.Net -->C#

Sri Sai Ram

Note:- int is a plane of house


X is a structure of house.
In object oriented language the code gets defined under a container rapper what we called as a
class. That provides the basis security for the contents which was present Exide it.

Procedural programming object oriented program.


A class is a user defined type where we never consume a type directly. To consume a type first we
required to create a copy of the type. Where copy of the type physically occupied space in the
memory, but not the types.
Ex:-

int
int x

=
=

100
100

invalid
Valid

As a class is also a type to consume with we required create a copy of it what we called a object
and then consumed it.
CPP PROGRAM:
class Example
{
Collection of Functions
};
Void Main()

entry point

{
-

Create the object of class


Using the object invoke functions in class
}

C++ language supports from a criticism that it was not fully object oriented because as per the
standard for object oriented programming the code has to be become under a class, but in C++
the main get defined outside the class.
Because if it was inside the class it should be invoked only using object of the class. Which get
created under main only.
class Test
{
---Members
};
void Main()
{
Test t;

// create object of class.


// invoke members of the class.

}
Naresh Tech. Class Notes

Hari

Page15

NagaRaj
.Net -->C#

Sri Sai Ram

To over came the problem is C++ when the Java language was inter choose a solution has
bean provided with static numbers.
If a member of a class is a charade of class, object of a class it not required for invoked it.
So if with main was declared classic it was be without create object point and become as a
entry point.
JAVA PROGRAM
class Example
{
Collection of methods
static void Main()
{

entry point

--Create the object of Class


--Using object invoke methods in class
}
}
C# language was design basic on the Gide line on the Java so the structure of a C# program will
be exactly same as a Java program. Which also known as Main as static.

*** END OF THE DAY ***

Dt: 16-02-2010
System specifications:Hard: 2.5-3.0GB
Ram: 1 GB
Naresh Tech. Class Notes

Hari

Page16

NagaRaj
.Net -->C#

Sri Sai Ram

Operating System:
XP Service pack 3, Vista (Home premium Business ultimate), windows7 (Home premium or
business or ultimate).
Visual studio .Net 2008(.Net framework 3.5, C# 3.0 compiler, VB 9.0 Compiler).
Data Base: SQL Server 2005 or 2008 & oracle.
MS office.
Books:
Professional C# 2008(Wrox press)
C# 3.0 Unleashed (SAMS).
C# 2008 Developers (Dietel)(SAMS).
Websites:
www.msdn2.com
www.csharp-corner.com
www.bangarraju.net
syntax to define a class:
[<modifiers>]class<Names>
{
-Members
}
Note:- 1. Every keyword lower case.
2. Proper case words will be start upper case letters.
Ex:- methodsMethods, class Class, membersMembers.
Modifiers ware few optional parameters like public, private, static, ext. As C# was case sensitive
language we required to a adopt the same convention adapted by Microsoft were writing the code, we
write on billow:
All keywords should be defined lower case.
To consume the base class library adapt proper case. Convention. That character of every word
should be on upper case.
Syntax defines main method:
Static void / int Main([string[]args])
{
-stmts
}
Main should be explicitly declared as static,it all the execution from the class it.
Main can be either value returning or non-value returning. If its want to return a value it can
return only int.
We can pass a string array as a parameter to the main method. Which was only optional.
class Example
{
static void Main()
{
System.Console.WriteLine(My first Program);
}
}

Save the file:D:\csharp7\Example.cs (D Drive, csharp7 folder)


Compile the program:
Start Menu programs MS Visual studio visual studio tools visual studio command
prompt
D:\> cd csharp7> dir
Csc <file name>

Naresh Tech. Class Notes

Hari

Page17

NagaRaj
.Net -->C#

Sri Sai Ram

D:\> csharp7> Example


My first program.
Note:- we can write code either by using visual studio .Net or under any text editor like note pad.
Which required manual compilation and execution.
Writing the first program:- Open the notepad and write following code in it.
class Example
{
static void Main()
}
System.Console.WriteLine(My first program);
}
}
Note:- Save the program we were provided with Csharp compiler which was a command line
utility which should be used from Visual studio command prompt as following:
csc <file name>
- To open visual studio command prompt go to:
Start menu programming MS visual studio visual studio tools visual studio
command prompt, click on to open and go into the folder where your program was saved
compile the program as following:
D :\> csharp7> csc example.cs
- Once the program compiles successfully, generates example.exe which contains IL code in it.
Executing the program:
- Now from the same location where we compiled the program use the following stmt to execute:
D:>\csharp7>example.
Csc: c Sharp compiler.
Ildasm: (Intermediate Language Dis-Assembler):- It was tool using which we can view the content of
IL code. Which has to be use from visual studio command prompt as well as follows:
Ildasm <name of exefile>
Ex:- D:>\csharp7> ildasm example.exe
- When we execute it opens a window in which we find a node with our class name expand it
under that click on the pink button beside the node Main, which displays the code in a new
window.
- System.Console.WriteLine
- Console is a predefined class.
- System is called a name space, it is a logical container in a class.
- File is a physical container, folder is a logical container.

*** END OF THE DAY ***

Dt:17-02-2010
System.Console.WriteLine:Naresh Tech. Class Notes

Hari

Page18

NagaRaj
.Net -->C#

Sri Sai Ram

Console was a predefined class which provides standard IO functionalities that can be performed
on IO devices.
It includes few static methods like Write(print), WriteLine(Print and canalize line), ReadLine,
exe(ReadLine something like that Scanef).
System is a name space where a name space is a logical container of classes.
Name spaces for gives under the programming languages for two basis reasons.
1. Grouping up Related class.
2. To overcome the name cosign, that is defined of multiple classes with the same name can be
done by putting them under different Name spaces.

Importing a Namespace: As every class has to be refund with a name space for consumption these name spaces some time
will be very much length.
In such case without suing the name space before the class we can import a name space and
consumed all the class under them directly to import a name space we use using statement in C#
language and import statement in VB language.
1. Using <Namespace>;

C#
2. Import <Namespace>

VB
Ex:- using System;
class UsingDemo
{
static void Main()
{
Console.WriteLine(importing a namespace);
}
}
D:\csharp7>notepad UsingSystem.cs
It will be directly open to the in notepad under that using file name usingSystem.cs file
D:\>csc UsingSystem.cs
to compile the programming file.
D:\> cls UsingSystem
To run the programming file.

DATA TYPES:Integer Types:Byte


Short
Int

System.byte
System.Int16
System..Int32

Naresh Tech. Class Notes

0
-32768
-2^31
Hari

+
+

255
32767
2^31-1
Page19

NagaRaj
.Net -->C#

Sri Sai Ram

Long
System.Int64
Sbyte
System.SByte
Ushort System.Ulint16
Uint
System.Ulint32
Ulong
System.Ulint64

-2^63
-128
0
0
0

+
+
+
+
+

Decimal or Float types:Float


System.Single
Double System.Double
Decimal
System.Decimal

4 Bytes
8 Bytes
16 Bytes

Boolean Type:
Bool

System.Boolean

true or false

Character type:
Char
String

System.Char
System.String

2 bytes
(Variable in the length)

2^36-1
127
65535(1)
2^32-1(2)
2^64-1(4)

Root Type:Object System.Object


The size of char type is increase to 2 bytes to provide the support for Unicode languages. All the
language characters we call it as an as key value, where as for other language characters its
known as Unicode values. Where Unicode values required 2 bytes memory location for stored it.
String is variable in size which defends upon number of characters we align to it.
Object type is a capable to store any type of value under it. It get initialized with 4 bytes but can
be changed in runtime. Which is also a variable length type.
Syntax for variable declaration: [<modifiers>][Const][readonly]<type><var>[=value][,n]
Int x;
public int y;
const float Pi=3.14f
readonly String Str;
bool b1, b2;
A constant and read only variable are one and the same which cant be modified outside of the
class and which they war declared.
Initialized a constant of the time of declaration mediatory.
When as in case of read only it was optional.
A content cant modified with in class also, but read only can be modified within the class.
Ex:-

String Str=100;
int x = Str;
int x = int.Parse(str);

invalid

Program:- VatDemo.cs
usnig System;
class VatDemo
Naresh Tech. Class Notes

Hari

Page20

NagaRaj
.Net -->C#

Sri Sai Ram


{
static void Main()
{
int x, y, z;
Console.Write(Enter x value:);
x= int.Parse(Console.ReadLine());
Console.Write(Enetr y Value:);
y = int.Parse(Console.ReadLine());
z= x+y;
Console.WriteLine(Sum of {0} &{1} is : {2},x,y,z);
(OR)
Console.WriteLine(Sum of +x+&+y+is:+z);
}
}

*** END OF THE DAY ***

Dt:18-02-2010
Note:Parse Method:-It was a method under all the data types responsible for converting a string a appropriate
type value.
Ex:int x = int.Parse(100)
//Converts to int
Naresh Tech. Class Notes

Hari

Page21

NagaRaj
.Net -->C#

Sri Sai Ram

Bool b = bool.Parse(true)
//Converts to bool
Flaot f =float.Parse(3.14f) //Converts to flaot
Note:-the given value should be compactable of being converted into the appropriate type value.
Ex:- int y =int.Parse(10x); //Invalid
Data types ware categorized into 2.
1. Value type 2. Reference type.
Value types store the data on the stack. Stack is a place where data is stored in fixed length, such
as int, float, ext
Every program has its one stark and no other program shares it allocated on program execution.
Stack work on a principle first in last out.
Stack will under the control of OS.
Stack will dont provide dynamic memory allocation and destruction.
Stack is faster in access.
References Types:C# support to pre-defended reference types string and objects. Reference type store reference in a
heap. Heap is the second place where reference be stored instead on data.
A .Net the heap is now more managed is called managed heap. When application create the first
reference type memory is allocated for the type at base address of managed heap.
When the application create next object the Garbage collector allocate memory for it in the
address base is available the garbage collection continues allocate place new object in this
manner.
Ex:int x = 100;
String s = Hello;

Null-able Value types (2.0):-In the traditional languages and earlier version a C# we have a program that
is we cant store null values in values types. They can only stored in reference types.
Ex:- String s = null;
//Valid
int x =null;
//invalid
Because of this which interactive with SQL database we will be facing a program, as a database allows
null values both in value types draw back from C# 2.0 we were provided with an option of storing null
value under value types also. Which has to done as following:
int x = null;

Invalid
int ?x = null;

valid
double ?d= null;

valid
Naresh Tech. Class Notes

Hari

Page22

NagaRaj
.Net -->C#

Sri Sai Ram

Implicitly typed variables(3.0): -It was an option which allows to declared variable by using the
keyword Var. which the data type of a variable is decided depending upon the value we assigned it.
Ex:- var
x =100;
x is int
var
s = Hello;
s is string
var
f = 3.14f;
f is float
Note:- in this case declaring a variable without assigning a value is not possible.
Ex:- var y;
invalid
Ex:-FindType.cs
using System;
class FindType
{
static void Main()
{
var x = 100;
Console.WriteLine(x.GetType());
var f =3.14f;
Console.WriteLine(f.GetType());
var s=Hello;
Console.WriteLine(s.GetType());
var b = true;
Console.WriteLine(b.GetType());
}
}
Note: - Get Type is a free defined method which returns the type of a given variable.
Note: - Object is a heap memory.

*** END OF THE DAY ***

Dt: 19-02-2010
Boxing & Un-Boxing: If a value type was stored on the managed help a reference type. Its known as Boxing.
Ex:int x=100;
Object obj =x;
Boxing
The Reverse of Boxing that is Converting Reference type to value type is Un-Boxing.
Ex:int y =(int) obj;
Un-Boxing
Naresh Tech. Class Notes

Hari

Page23

NagaRaj
.Net -->C#

Sri Sai Ram

Operators:Arithmetic

+,-,*,/,%
Assignment

=,+=,-=,*=,/=,%=.
Comparison

==,!=,<,<=,>,>=,is, as, like


Concatenation

+
Increment & Decrement
++, -Logical

&&, !!, ^
Conditional Statement: A block of code which executes basing on a condition is known as conditional statement. There
of 2 types,
1. Conditional Branching(if, switch)
2. Conditional looping (while, do-while, for-each)
Conditional Branching:- these statement allow you to branch your code defending on whether certain
conditions were met or not. C# has 2 constructs for branching code, the if statement which allows you to
test whether a specific condition is met, and the switch statement, which allows you to compare an
expression with a number of different values.
Syntax: if:-

if(<condition>)
<stmts>;
else if(<condition>)
<stmts>;
---------------else
<stmts>;

Ex:- Ifdemo.cs
using system;
class Ifdemo
{
static void Main()
{
int x, y;
Console.Write(Enter X value:);
x = int.Parse(Console.ReadLine());
Console.Write(Enter Y value:);
y = int.Parse(Console.Readline());
if(x>y)
Console.WriteLine(x is greater);
else if(x<y)
Console.WriteLine(y is greater);
else
Console.WriteLine(Both are equal);
}
}
Switch:Syntax:- switch(<expressions>)
{
case<value>:
<stmts>;
Naresh Tech. Class Notes

Hari

Page24

NagaRaj
.Net -->C#

Sri Sai Ram


break;
----------------default:
<stmts>;
break;
}

In switch case Break is not optional it will be must.


NOTE:-Using Break after a case was not optional in C#, it is mandatory to use ever after default also.
Ex: - SwitchDemo.cs
using System;
class SwitchDemo
{
static void Main()
{
Console.Write(Enter Student No.(1-3):);
int Sno = int.Parse(Console.ReadLine());
switch(sno)
{
case 1:
Console.WriteLine(Student 1);
break;
case 2:
Console.WriteLine(Student 2);
break;
case 3:
Console.WriteLine(Student 3);
break;
default:
Console.Write(Wrong Student No:);
break;
}
}
}
Conditional Loop:C# provides 4 diff. loops that allow you to execute a block of code repeatedly until a
certain condition is met. Those are,
1.
2.
3.
4.

for loop
while loop
do..while loop
for each loop

A loop required 3 things in common:


1. initialization
2. condition
3. iteration
which set the starting point of loop.
which set the end of loop.
It set the takes you to the next cycle.
Syntax:-

Naresh Tech. Class Notes

Hari

Page25

NagaRaj
.Net -->C#
(1) for :-

Sri Sai Ram


for(initialize; condition; iterator)
Ex:-

(2) while:-

<stmts>;
for(int x=1; x<=100; x++)
Console.WriteLine(x);

while(condition)
<stmts>;
Ex:-

int x= 1;
While(x<=100)
{
Console.WriteLine(x);
x++;
}
The minimum number of execution of while is zero.
The minimum number of execution of dowhile is one.
(3) Dowhile:- do { <stmts>;}
while(Condition);
Ex:- int x=1;
do{
Console.WriteLine(x);
x++;
} while(x<=100);
Note:-In case of while loop its checks with conditions first and then execute of the code only if the
condition if satisfied. So the minimum number of execution in this case will be zero.
Where as in case of dowhile first its executes the code once and then checks with the condition for
the next time execution. So minimum numbers execution here will be zero.
(4) Foreach:Syntax:- foreach(type var in coll / array)
{
<stmts>;
}
For-each was a special loop which has bean differed for processing of arrays and collection where
an array is set of similar type values and collection is a set of dissimilar type values.

JUMP STATEMENTS:C# Provides a Number statements that allow you to jump immediately to another line in a program.
Those are,
1.
2.
3.
4.

Goto
Break
Continue
Return
(1) Goto:- It allow you to jump directly to another specified line in the program, indicated by a label
which is an identifier followed by a colon.
Syntax:goto xxx;
Naresh Tech. Class Notes

Hari

Page26

NagaRaj
.Net -->C#

Sri Sai Ram


Console.WriteLine(Hello);
xxx;
Console.WriteLine(Goto called);

(2) Break:- It is used to exit from a case in a switch statement and also used to exit from for, foreach,

while, dowhile loops immediately after the end of the loop.


Ex:-(1)
for(int i=1; i<=100; i++)
{
Console.WriteLine(i);
}
Console.WriteLine(End of the loop);

output:- 1 to 100

(2)

for(int i=1; i<=100; i++)


{
Console.WriteLine(i);
If(i==50);
out put:1 to 50
break;
51 to 100
}
Console.WriteLine(End of the loop);
(3) Continue: - This can be used only in the loop statement which will jump the control to the
iteration part without executing the statement present after it.
Ex:for(int i=1;i<=100;i++)
{
if(i==7)
o/p:1 to 6
continue;
and
Console.WriteLine(i);
8 to 10
}
Console.WriteLine(End of the loop);
(4) Return: - Its used for jumping out of a function (or) method in execution. Where in this process

it is capable to carry a value out of the function or method it was only optional.
Ex:- RetDemo.cs
D:\>cd csharp7
D:\csharp7>RetDemo.cs
D:\csharp7>cls

Ex:-RetDemo.cs
using System;
class RetDemo
{
static void Main()
{
Console.Write(Enter a number:);
int x= int.Parse(Console.ReadLine());
if(x<2)
return;
Console.Write(Enter a limit:);
int y= int.Parse(Console.ReadLine());
Naresh Tech. Class Notes

Hari

Page27

NagaRaj
.Net -->C#

Sri Sai Ram


for(int i=1; i<=y; i++)
Console.WriteLine({0}*{1}={2},x,i,x*i);
}
}

Output:-

Enter a number: 2
Limit a number: 10
2 * 1= 2
2 * 2= 4
2 * 6= 6
2 * 4= 8
2 * 5= 10

2*6
2*7
2*8
2*9
2 *10

= 12
= 14
= 16
= 18
= 20

*** END OF THE DAY ***

Dt: 22-02-2010
Arrays:It was a set of similar type values stored in a sequential order. These are 3 types.
1. Single Dimensional(rows)
2. Two Dimensional (rows & columns)
3. Jagged dimensional.
Naresh Tech. Class Notes

Hari

Page28

NagaRaj
.Net -->C#

Sri Sai Ram

In C#, arrays can be declared as fixed length or dynamic fixed length array can store a predefined
number of items. Which size of dynamic arrays increases as you add new items to the array.
(1) Single dimensional: - These are arrays which stored the values in the form of row.
Syntax: - <type>[]<name>= new<type>[size];
Ex:int[]arr =new int[4];
(or)
Int[]arr;
Arr= new int[5];
(or)
int[]arr={list of values};
Ex:- SDArray.s
using System;
class SDArray
{
static void Main()
{
int[]arr = new int[5];
int [0]=10; arr[1]=20; arr[2]=30; arr[3]=40; arr[4] =50;
for(int i=0; i<5; i++)
o/p:- 10
20
Console.Write(arr[i] + );
10
20

30
30

40
40

50
50

Console.WriteLine();
foreach(int i in arr)
Console.Write(i + );
} }
While assigning the values of an array we can either use for or for-each loop. The basic
Difference of this two were,
In case of for: The variables of the loop referees to values of the array. That is for-each the
variable of loop referees to value of the array in assigned to the variable of loop.
In case of for: The variable of the loop will always be int only. Where as in case of for-each the
variable of the loop will be same as the type of values under the array.Assigning values at
declaration:
int[] arr = {100, 200, 300, 400, 500, 600};
Once we declared reference type always its references type. Array comes under reference type as
we have a chance of an array after declaration.
Array class:-It was a predefined class under the system name space which acts as a base
for every we ware declaring.
The class array provides a set of method and properties that can be applied on the array
we declared those are,
Array:

Sort(array)
Reverse(array)
Copy(src, dest, count)
Length

Ex:- SDArray2.cs
Naresh Tech. Class Notes

Hari

Page29

NagaRaj
.Net -->C#

Sri Sai Ram


using System;
class SDArray2
{
static void Main()
{
int [] arr ={34,56,90,61,29,38,69,83,71,63};
for(int i=0; i<arr.Length; i++)
O/P:-34,52,2,90,61,29,
Console.Write(arr[0]+ );
38,69,83,71,63.
Console.WriteLine();
Array.Sort(arr);
O/p:-2,29,34,38,52,61,63,
foreach(int i in arr)
69,71,83,90.
Console.Write(i+ );
Console.WriteLine();
Array.Reverse(arr);
foreach(int i in arr)
O/p:- 90,83,71,69,63,61,52,38,
Console.Write(i+ );
34,29,2.
Console.WriteLine();
int [] brr = new int[8];
Array.Copy(arr,brr,5);
foreach(int i in brr)
Console.Write(i+ );
Console.WriteLine();
} }

O/p:- 90,83,71,69,63,0,0,0,0,0,0.

(2) Two Dimensional Array:-these are arrays which hold the data in the form of rows and

columns.
Syntax:<type>[,] <name> = new<type>[rows, columns];
Ex: -

int[,] arr = new int[3,4];


(or)
int[,] arr;
Arr = new int[2,3];
(or)
int[,] arr = { list of values };

*** END OF THE DAY ***

Dt: 23-02-2010
Ex:- TDArray.cs
using System;
class TDArray
{
static void Main()
Naresh Tech. Class Notes

Hari

Page30

NagaRaj
.Net -->C#

Sri Sai Ram

{
int a=5;
int[,] arr= new int[4,5];
//assigning values to 2D array:
for(int i=0; i<arr.GetLength(0); i++)
{
for(int j=0; j<arr.GetLength(1); j++)
{
arr[i,j]=a;
a+ =5;
}
}
//Printing Values from 2D (dymention)array:
for(int i=0;i<arr.GetLength(0),i++)
{
for(int j=0;j<arr.GetLength(1);j++)
Console.Write(arr[i,j]+ );
Console.WriteLine();
}
}}
Note:-Get length was a method which can be used foe finding the number of rows and columns present
in a 2 dimensional array. Where if zero given parameter value, it return rows and for 1 it returns columns
of the array.
Assigning values to 2 dimensional array while declaration:
int [,] arr = {
{11,12,13,14},
{21,22,23,24},
{31,32,33,34}
};
(3) Jaggad Arrays:- This is same a two dimensional arrays out here the number of columns
under each row can be varied, but in 2 dimensional array the number of array. Because here
multiple single dimensional array were combined together to form a new array.
Syntax: - <type>[][]<name> = new <type>[rows][];
Ex:int [][] arr = new int[3][];
(or)
int [][] arr = {list of values};
Where declaring a jagged array in the initialized declaration we can only specified the
number of rows but not the number of columns.
Ex:-int [][] arr = new int[4][];
After specifying the number of rows known pointing to each row we receiving to
specified the number of columns under the rows.
arr[0] = int[6] ;
arr[1] = int[5];
arr[2] = int[8];
arr[3] = int[4];

Naresh Tech. Class Notes

Hari

Page31

NagaRaj
.Net -->C#

Sri Sai Ram

Ex: - JaggedDemo.cs
using System;
class JaggedDemo
{
static void Main()
{
int[][] arr = new int[4][];
arr[0] = new int[6];
arr[1] = new int[5];
arr[2] = new int[8];
arr[3] = new int[4];
//assigning values to Jagged array:
for(int i =0; i<arr.GetLength(0); i++)
{
for(int j =0; j<arr[i].length; j++)
arr[i][j] = j+1;
}
//printing values from jagged array:
for(i=0; i<arr.GetLength(0); i++)
{

O/p:- 1 2 3 4 5 6
12345
12345678
1234

(1) for(int j=1; j<arr[i].Length; j++)


Console.Write(arr[i][j]+ );
console.WriteLine();
}
}
}

(OR)

(2). foreach(int x in arr[i])


Console.Write(x+ );

Assigning values jagged while declaration:


int [j][] arr = {
new int[3] {11,12,13},
new int[5] {21,22,23,24,25},
new int[4] {31,32,33,34}
};
Command Line parameters: When we want to take in a input to a program well were prompting the user and entering the
value and capturing if using ReadLine method.
Naresh Tech. Class Notes

Hari

Page32

NagaRaj
.Net -->C#

Sri Sai Ram

Without prompting for each value the user can supply all the values to the program, using cmd
line Paramus as following:
< exe to executes><list of values>
Ex: - add to 200
We can supply any numbers of values to here separate with a wide space.
Whose all the value captured under the sting away of main method it present.
Ex: -Param.cs
using System;
class Params
{
static void Main(String[] args)
{
foreach(String str in args)
Console.WriteLine(str);
}
}
O/p:Params 10 20
Hello true 3.14f

10
20
hello
true
3.14f

*(Query)
* Add numbers 10 20 30 40?

*** END OF THE DAY ***

Dt:-24-02-2010
Naresh Tech. Class Notes

Hari

Page33

NagaRaj
.Net -->C#

Sri Sai Ram

Working with visual studio:It was an editor provided by Microsoft to develop .Net applications of any type (windows (or)
web (or) console) using any of the .Net languages.
Versions
1st
2nd
3rd
4th
5th

Visual studio
frame work
2002
2003
2005
2008
2010(Beta version)

1.0
1.1
2.0
3.5
4.0

The current version of visual studio was 2008 RTM. Which came with .Net frame work 3.5
To launch the visual studio go to start menu programs Microsoft visual studio Microsoft
visual studio and click on it to open.
Project is a collection of file.
Application developed under visual studio is known as project, where project is collection of
files.
To create a new project either click on the create project option (or) go to file Menu and select
new project, which opens the new project windows.
Under the new project window we need to specified the following details:
1. Under Project types choose the language in which we want to developed the application.
Ex: - Visual C#.
2. Under templates specify the type of application we want to console application.
Ex:- Console application.
3. On top right corner we can change frame work version in which we want to develop the
application, default is 3.5 can be changed either to 2.0 or 3.0
4. In bottom under the name option specify name to the project.
Ex: - sample project.
5. Bellow the project name specifies the location where we want to save the project.
Ex: - D:\csharp7
Click on the button which creates the project with a default class program under program.csfile.
When project were developed under visual studio by default name space get created with the
same name of project that is sample project, from now each and every class of the project comes
under same Name Space.
We were aware that a Name space collection of class program within the main method write the
following code:
Console.WriteLine(first Project);
Console.ReadLine();
To Run class Press F5, which will save, compile and then execute the class.
Ctrl+F5 (with outusing ReadLine() )
Under visual studio we find a windows known as solution Explorer, which is used for organizing
the project, it will allow us to view add and delete the intense under the project, to open solution
Explorer goto view Menu and select solution explorer.
To add a new class under project open solution explorer right clicks on project and select add (or)
class which opens add new item window select class from it and specified a name in the bottom.
Then click on the add button, which adds the class under project.
Note: - The new class which has been added also comes under the same name-space.
- Now write following code under class.
Naresh Tech. Class Notes

Hari

Page34

NagaRaj
.Net -->C#

Sri Sai Ram

static void Main()


{
Console.WriteLine(Second class);
Console.ReadLine();
}
Now to run the class open solution explorer right click on the project and select properties which
opens project properties windows.
Under it we find a property startup object which will list all classes under the project that contains
a valid Main method in them, choose your class and run
it.

*** END OF THE DAY ***

Dt: 25-02-2010
Object Oriented Programming: Before 70s we have procedural programming language like C, which few problems lock reusability, security.
To overcome the above program in 70s a new approach in programming has been inter choose
that is object oriented programming which provides the security, reusability.
A language to be called as object oriented needs to satisfied 4 basis principle like,
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
1. Encapsulation:-It was a principle which tells we can protect anything by wrapping under a
container. In object oriented languages over code gets protected by getting wrapping under a
container what we called as class.
2. Abstraction: - It was a principle, which talks about hiding if the complexity by providing the
user with a set of interfaces to consume the functionality.
3. Inheritance: -according lay property of parents belongs to children (or) acquired by children. In
object oriented language also the members of a class be acquired by other classes. If they have
parent, child relationship bit been each other.
4. Polymorphism: - According to this entities behave in different way depending upon the inputs
they receive. This can be implemented in object oriented languages within approved known as
over loading.
Methods:
Syntax:[<modifiers>]void\ type<Name>([<param defs>])
{
Naresh Tech. Class Notes

Hari

Page35

NagaRaj
.Net -->C#

Sri Sai Ram


-stmts
}

Modifiers war optional which can be special keywords like public, private, static, protected.
Void \ type is used to specified whether the method was value returning or non-value returning or
void tells it was non-value returning and to return a value we need to specified the type of value it
has to return.
Param deference are used for passing nay values to a method for executing to make it dynamic.
We can pass parameters do a methods as following:
Syntax:[out\ref]<type><var>[,n]
Out\ref keywords where used of declaring reference variables. Which allows as to falls a paramer
to a method using pass by ref mechanism(implicit pointers).
Methods have to be defined under classes.
To invoke the methods defined under a class we first required to create the object of class as
following:
Syntax:-<class><name> = new<class>([<a list of values>])
Ex:- program p;
p= new program();

//p is an variable
//p is an object

(or)
program p = new program();

// p is an object

Note:- we can create the object of a class anywhere in the class can be created from other classes also
while create under the same class we generally create it is main method because it was the entry point
as the class.
*** END OF THE DAY ***
Dt:-26-02-2010
Open the visual studio go to file new project choose languages C# Temples:
console application Name it as project and write the following code under the class
program.
Ex:- Program.cs
class Program
{
// No input and output
void Test1()
{
Console.WriteLine(first Method);
}
// No output but has input
void Test2(int x)
{
Console.WriteLine(second Method:+ x);
Naresh Tech. Class Notes

Hari

Page36

NagaRaj
.Net -->C#

Sri Sai Ram

}
// No input but has output
string Test3()
{
returnthird Method;
}
// has input and input
string Test4()
{
return Hello +name;
}
// returning multiple values:
int Math1(int x, int y, ref int z)
{
z = x*y;
rerurn x+y;
}
//Returning multiple values:
int Meth2(int x, int y, out int z)
{
z = x*y;
return x+ y;
}
static voidMain(String[] args)
{
program p = new program();
p.test1();p.test2(10);
Console.WriteLine(p.Test3());
Console.WriteLine(p.Test4(Raju));
int b=0; // initialization is mandatory
int a=p.Math1(100,50,ref b);
Console.WriteLine(a+ +b);
int n; //initialization is optional
int m = p.Math2(100,50, out n);
Console.WriteLine(m+ +n);
Console.ReadLine();
}}
Note: -ref and out keywords were used for returning an output from a method this is similar to the
concept of pass by reference Mechanism (implicit pointers) available in traditional C++ language. There
is no support for explicitly pointers under .Net language.
Syntax:int Math1(int x, int y, int z)
{
z = x*y;
return x+y;
}

Naresh Tech. Class Notes

Hari

Page37

NagaRaj
.Net -->C#

Sri Sai Ram

Member of class:-Whatever we defined under a class were known as member of a class. Here every
member of a class (except static) should be invoked by using the object of class. Add a new class under
the project as first.cs and write the following code:
class first
{
int x=100;
static void main()
{
first f;
f = new First();
Console.WriteLine(f.x);
Console.ReadLine();
}
}

O/p:- 100

Note:-The memory allocation for an object gets performed only after using the operator. We can destroy
the memory allocated for an object by assigning the value null to it. Only null is assign we can use the
objective for accessing the member. To test this rewrites the code under the method of class first as
following:
First f = new First();
Console.Write(f.x);
f = null;
Console.WriteLine(f.x); //invalid
Console.ReadLine();
Fig:-

We can create any number of objects a class and each we create using new will have memory
allocated separately to it.

Naresh Tech. Class Notes

Hari

Page38

NagaRaj
.Net -->C#

Sri Sai Ram

A modification preformed an member of an object does not reflects the member of other
object to check this rewrite code under the main method of class first.
Ex:First f1 = new First();
First f2 = new First();
Console.WriteLine(f1.x + + f2.x);
f1.x = 500;
Console.WriteLine(f1.x + + f2.x);
Console.ReadLine();
Fig:-

We can assign the object of a class to the variable of same class and make as a reference. In this
can both the object and reference will be consuming the same memory.
Modification made an members the object reflect back to the reference and vice versa.
To check this rewrite the code under main method of class first as following:
First f1 = new First();
First f2 = f1;
o/p:- 100
100
Console.WriteLine(f1.x + + f2.x);
500
500
F1.x=500;
Console.WriteLine(f1.x + + f2.x);
Console.ReadLine();
Fig:-

When there are two or more object and references pointing to a memory location assigning null to
any of this will not distil the memory allocated.
It will be only remove other can consumed. To check this rewrite code under main method of
class first as follows:
Ex:First f1 = new first();
First f2 = f1;
O/p:100
f1 = null;
Console.WriteLine(f2.x); // valid
Console.WriteLine(f1.x); // invalid
Console.ReadLine();

Naresh Tech. Class Notes

Hari

Page39

NagaRaj
.Net -->C#

Sri Sai Ram

Fig:-

*** END OF THE DAY ***

Dt: 27-02-2010
cd:\>ildasm
cd: d:\> csharp7>ildasm example.exe
Whenever an object gets created with new operator internally the following things place:
1. Reads the classes where in this process it identified each and every member defined under the
class.
2. In cokes the constructors allocates the memory required.
Constructor: It was a special method present in every class responsible for initializing the variables of a class.
The name of a constructor method is same as the class name.
Constructor method was a non-value returning method.
Every class required if at all has to execute.
Note: -while compiling a program the complier verifiers whether the class was defined with any
contractor or not. If not defined to makes the class to execute will take the responsibility of defending the
constructor under the class.
Syntax: - [<modifiers>]<Names>([<paramdefs>])
{
-stmts
}
Note:- Constructor name is same as the class nme.
Program:- Add a class ConDemo.cs
class ConDemo
{
ConDemo()
{
Console.WriteLine(Constructor);
}
void show()
{
Console.WriteLine(Method);
}
static void Main()
{
Consloe.WriteLine(MainMethod);
ConDemo cd1 = new ConDemo();
ConDemo cd2 = new ConDemo();
ConDemo cd3 = cd1;
cd1.show();
cd2.show();
cd3.show();
Console.ReadLine();
}
}
Note:-

Naresh Tech. Class Notes

Hari

Page40

NagaRaj
.Net -->C#

Sri Sai Ram

Note:-Creating object of a class using the new operator is a called we make to the constructor. Which will
internally allocate the memory that will require for a types.
Constructors are two types,
1. Default (or) Zero argument constructor.
2. Parameterized Constructor.
A Constructor with any parameter is a default or zero argument constructor, this can be defined
either by a programmer or will be defining by the compiler.
A constructor will parameter is a parameterized constructor. Which can be defined only a
parameter.
If a constructor in a parameterized value to the parameter has to send will creating the object of
class because just like method called should match method signature. Constructor should be
match constructor signature.
To check this write constructor in our previous class as following:
ConDemo(int x)
{
Console.WriteLine(Constructor: +x);
}
Know under main will creating object send the values to parameters as following:
ConDemo cd1 = new ConDemo(10);
ConDemo cd2 = new ConDemo(20);
Add a class class ConParams.cs
class ConParams
{
int x,y; //class variables
ConParams(int a, int b) //Block variables
{
x=a; y= b; (or) this.x=x; this.y=y; (or) x=X; y=Y
//this.x= class variable, x= local variables
}
void Add()
{
Console.WriteLine(x+y);
}
void Sub()
{
Console.WriteLine(x-y);
}
void Mul()
{
Console.WriteLine(x*y);
}
void Div()
{
Console.WriteLine(x/y);
}
static void Main()
{
ConParams cp=new ConParams(100,20);
cp.Add();cp.Sub(); cp.Mul(); cp.Div();
Console.ReadLine();
}
Naresh Tech. Class Notes

Hari

Page41

NagaRaj
.Net -->C#

Sri Sai Ram

}
This is a keyword which can be used for refer end to member of a class.
If a class content multiple methods in it which has to be executed by using the set of values in
such cases without sending the value using each method separately it is better to send the values
using constructor of the class in our above example.
*** END OF THE DAY ***
Dt:-01-03-2010
Ex: -class Customer
{
decimal bal;
customer(int Custid)
{
bal=<get bal from dbtable for given Custid>;
}
decimal GutBall()
{
return bal;
}
void withdraw(decimal amt)
{
bal =-amt;
}
void deposit(decimal amt)
{
bal +=amt;
} }
In the above example any number of customers can use application at the same time by
passing a customer id. Which will create a object are that customer by loading the balance
information from database.
Custid
Cname
Bal
101
xxx
5000
102
yyy
12000
103
zzz
18000
------------------------------------------------------------------------------------Customer c1
=
new customer(101);
Customer c2
=
new customer(102);
Customer c3
=
new customer(103);

C1.Deposit(5000);
10000
C2.Withdraw(4000);
8000
As we were availed a class is a collection of members which can be categorized into 2 types,
1. Instance Members(Not static)
2. Static members.

Naresh Tech. Class Notes

Hari

Page42

NagaRaj
.Net -->C#

Sri Sai Ram

Members of a class which to required object of the class for initialization and execution var
none as instance or Non static members. Where as members of the class which dont required
object of the class for initialization and execution where none as static members.
Instance Variables -Vs- Static Variables: A variable declared using static Modifier or declared under a static block. Were state rest of
all were instance variables.
Ex:int x =100;
//instance
static int y =200; // static
static void Main()
{
int z=300;
// static
}
A static variable get initialize once the execution of class starts. Whereas instance variable
gets initialize only after creating the object of class.
The minimum, the maximum number of times an static variable gets initialize will be one and
only once. Where as in case of instance it will be zero or n.
A static variable were only a single copy for the complete class modifications mode by one
objects will be reflected to other. Whereas instance variable were separate copies each object
changes of one will not reflected to the other.
Note: - while referring to instance members we required to reference by using the object of class. Where
as we refer to static members by class name.
Add a class StatVars.cs
class StatVars
{
int x = 100;
static int y=200;
o/p:
200
static void Main()
100
{
Console.writeLine(StatVar.y);
StatVars obj=new StatVars();
Console.WriteLine(obj.x);
Console.ReadLine();
} }
Instance Methods-Vs-Static Methods: A method declared using static modifier was a static method rest of all was instance only.
While define ding static methods we cannot consume any instance member of the class directly.
They can only we consumed by creating the object of the class.
Note:-Non-static members of a class cant be consumed from static blocked directly. They should be only
by using object of the class.
Add a class StatMets:class StatMets
{
int x=100;
static void y=200;
static void Add()
{
StatMets obj=new StatMets();
o/p:-300
Console.WriteLine(obj.x+y);
}
static void Main()
Naresh Tech. Class Notes

Hari

Page43

NagaRaj
.Net -->C#

Sri Sai Ram

{
StatMaets.Add()
Console.ReadLine();
} }
*** END OF THE DAY ***
Dt:-02-03-2010
Instance Constructor Vs- Static Constructor: A Constructor declared used static modifier was static constructor rest of all var instance
constructor only.
Static constructor was responsible for initialization for static variable and instance constructor
responsible for initialization for instance variables.
A static Constructor is called only once in execution on the class where as instance constructor
gets call each time we created its not called at all.
Static constructor is the first block of code which gets executed under the class.
A static constructor cannot be parameterized because explicit calling a constructor is not done (or)
not possible.
Add a class StatCon.cs
class StatCon
o/p:- Static Constructor
{
Main Method
static StatCon
Non-Static Constructor
{
Non-Static Constructor
Console.WriteLine(static constructor);
}
StatCon()
{
Console.Writeine(Non-Static Constructor);
}
static void Main()
{
Console.WriteLine(Main Method);
StatCon c1=new StatCon();
StatCon c2=new StatCon();
Console.ReadLine();
}
}
Static Classes:-this for inter choose in C# 2.0 which can be defined only with static members
initialization of the class in not possible, because there was no instance members under the class.
***Inheritance:
Its in approach it allows consuming of the members in a class by a new class by establishing parent child
relation between the classes.
Syntax:- [<modifiers>]<CC Name><PC Name>
Ex:class Class1
{
-Members
}
Naresh Tech. Class Notes

Hari

Page44

NagaRaj
.Net -->C#

Sri Sai Ram

Class Class2:Class1
Note:- Inheritance allows to consume member of a parent under child but not private members. Default
scope for member of a class was private only.

Ex: -Add a class Class1.cs


class Class1
{
public Class1()
{
Console.WriteLine(class1 constructor);
}
public void Test()
{
Console.WriteLine(Method one);
}
public void Test2()
{
Console.WriteLine(Method Two);
}
}
Ex: - Add a class Class2.cs
class Class2: Class1
{
public Class2()
{
Console.WriteLine(Class2 Constructor);
}
public void Test 3()
{
Console.WriteLine(Method Three);
}
static void Main()
{
Class2 c=new Class2();
c.Test1();
c.Test2();
c.Test3();
Console.ReadLine();
}
}
Naresh Tech. Class Notes

Hari

o/p:- Class1 Constructor


Class2 Constructor
Method One
Method Two
Method Three

Page45

NagaRaj
.Net -->C#

Sri Sai Ram

Things to be consider while using inheritance:1. In inheritance execution of a child class always start by invoking the default constructor of
parent. While should be accessible to the child. If not accessible inheritance will not be possible.
2. Members of the parent class can be accessed by child classes, where as child class members
cannot be accessed by parent class. Because a parent class it not avower of it child class to test
this write the following code under child class main method:
Class1 p= new class1();
p.Test1();
p.Test2();
p.Test3();
invalid
3. As we war aver that object of a class can be assigned to the variable of the same class it can be
also assigned to variable of it parent class and make it of a reference, but using that reference we
cant invoke member of child class.
To test this rewrite code under main method of child class2 as following:
class2 c= new class2();
class1 p= c;
p.Test1();
p.Test2();
p.Test3(); invalid

Note:-The object of child class that is present in as parents reference if required can be converted by into
childes reference but should done by using explicit type costing.
Ex:class 2 c= new class 2();
class 1 p= c;
class 2 c2= (class 2)p;
(or)
Class 2 c2=p as class2;
C2.Test1();
C2.Test2();
C2.Test3();
Note:- Using child reference we can again call all the methods.
*** END OF THE DAY ***

Naresh Tech. Class Notes

Hari

Page46

NagaRaj
.Net -->C#

Sri Sai Ram


Dt:-03-03-2010

4. Every class what we defined in .Net languages as a default parent class, even if we inherit or not.
That is the class object when we complete the program the compiler verified whether the class is
inheriting from any other class. If not inheriting compiler inherit from the class object. So object
class will be a parent either directly or indirectly for any class.The Member of object class can be
access from any class what we are going to defined.
Ex:- GetType(), ToString(), ext
To check this rewrites the code under main method of class 2 as following:
object obj = new Object();
console.writeLine(obj.GetType());
class1 p=new Class1();
Console.WriteLine(p.GetType());
Class2 c = new Clas2();
Console.writeLine(c.GetType());
Console.ReadLine();

5. Types of Inheritance: As for the object oriented programming there are 2 types of inheritance.
1. Single Inheritance
2. Multiple Inheritance
Single Inheritance: - If a class has only one inheritance parent class then its known as single
inheritance.

Multiple Inheritances: - If a class has more than one immediate parent class to it its known multiple
inheritances.

Traditional C++ language supports both single and multiple inheritances where as the modern languages
java and .Net does not provide the support for multiple inheritance through classes because it supports
from the problem of ambiguity.
Naresh Tech. Class Notes

Hari

Page47

NagaRaj
.Net -->C#

Sri Sai Ram

6. As we war aver that execution of child classes always start by invoking default constructor of
parent classes implicitly. But if the parent does not container ina default container in constructor
in the sance (contains a parameterized), implicit calling of the constructor is not passable
because the parameter requires a value. In such cases explicit calling of the constructor is required
by using a keyword base.
Which can refer to many number of base classes, to check this rewrite the constructor under class
one as following:
Ex:- public Class1(int x)
{
Console.WriteLine(class1 Constructor:+x)
}
Known try to run class2 which gives a compile time error staring class1 does not content a zero argument
constructor. Known do the following modification to class2 constructor.
public class2(int x):base(x)
{
Console.WriteLine(Class2 Constractor);
}
Know while creating the object of the class2 send the value for its parameter which will come to
the constructor o it and from where goes to class1 constructor. Write the following code under
main to create class2 object.
Class2 c =new Class2(20) ;
Console.ReadLine();
*** END OF THE DAY ***

Dt:-04-03-2010
Extension Methods: - In was a new concept added from C# 3.0 which allows to adding new methods
to a class, without editing the class the approach of extension methods will be near similar to
inheritance. Were in inheritance we can extend the functionality of a class with help o a child class.
But in case of extension method we can extend methods of class with using any inheritance. This can
be done with help of a class of type static.

Naresh Tech. Class Notes

Hari

Page48

NagaRaj
.Net -->C#

Sri Sai Ram

In the above case under inheritance to invoke all the 4 methods we need to object of class2. Where as
in extension methods we can use the object of class1.

Add a class Original.cs and write the following :


class Original
{
public int a =100;
public void Show1()
{
Console.WriteLine(Method one: + this.a);
}
public void Show2()
{
Console.WriteLine(Method Two);
}
}

Add a class StatClass.cs and write following making the class as Static.
static class StatClass
{
public Static void Show3(this Original obj)
{
Console.WriteLine(Method three);
}
public static Show4(this Originalobj, int x)
{
Console.WriteLine(Method Four: + x);
}
public static void show5(this Original obj)
{
Console.WriteLine(Method five: + obj a);
} }

To consume the class Original Add new classTestOriginal.cs and write the following:
class TestOriginal
{
static void Main()
{
Original o = new Original();
o.Show1();
o.Show2();

Naresh Tech. Class Notes

Hari

Page49

NagaRaj
.Net -->C#

Sri Sai Ram

o.Show3();
o.Show4();
o.Show5();
Console.ReadLine();
}
}
(4). POLYMORPHISM: Entities behave in diff ways depending upon the input they receive is known as polymorphism.
Which can be implemented in OOP with an approach known as overloading.
Overloading allows to defined multiple methods constructor under the class with the same name
by changing their signature.
Change in signature in the scene either we can change the members of parameter being passing to
the method/ type of parameter being passing the method/order of paramer being.
Ex: public void show()
public void show(int x)
public void show(String s)
public void show(int x, String s)
public void show(String s, int x)
Note: - change in return type of the method will not be taken in the Concentration in case of overloading.
Ex:- public String show() invalid
There String in not a input value.

Add class LoadDemo.cs


class LoadDemo
{
public void show()
{
Console.WriteLine(1);
}
public void show(int x)
{
Console.WriteLine(2);
}
public void show(String s)
{
Console.WriteLine(3);
}
public void show(int x, String s)
{
Console.WriteLine(4);
}
public void show(String s, int x)
{
Console.WriteLine(5);
}
static void Main()
{
LoadDemo obj = new LoadDemo();
Obj.show();

Naresh Tech. Class Notes

Hari

Page50

NagaRaj
.Net -->C#

Sri Sai Ram

Obj.show(10);
Obj.show(Hello);
Obj.show(10, Hello);
Obj.show(Hello, 10);
Console.ReadLine();
}
}
Overloading approach its allows as to provide multiple behaviors to a method.
Ex:- writeLine() method under console class which provides 19 differences overloads for printing a
different type of value as follows:
WriteLine()
WriteLine(int value)
WriteLine(String value)
WriteLine(bool value)
Constructor overloading: - As we can over load methods we can also overload constructor we
can defined more than one constructor under the class changing their signature.
*** END OF THE DAY ***

Dt:-05-03-2010

Add a class LoadCon.cs


class LoadCon
{
int x;
public LoadCon()
{
x = 10;
}
public LoadCon(int x)
{
this.x = x;
}
public void Display()

Naresh Tech. Class Notes

Hari

Page51

NagaRaj
.Net -->C#

Sri Sai Ram

{
Console.WriteLine(x);
}
static void Main()
{
LoadCon d1 = new LaodCon();
LoadCon d2 = new LaodCon(9);
l1.Display();
l2.Display();
Console.ReadLine();
} }
Overloading of the constructor gives use the flexibility of initializing the variables of class either
with default values or allow a programmer to initialize the variables with their required values.
In our above case when the object of the class increased using default constructor, the variable x
gets initialized with a default value 10 (or) using the parameterized constructor programmer can
send his own value to the variable.
Inheritance Based overloading: In the method of a class get overloaded under its child class we call it as Inheritance
Based Overloading.

Add a class LoadParent.cs


class LoadParent
{
public void Test()
{
Console.WriteLine(method-1);
}
public void Test(int x)
{
Console.WriteLine(method-2);
} }

Add a class LoadChild.cs


class LoadChild
{
public void Test(String s);
{
Console.WriteLine(method-3);
}
static void Main()
{
LoadChild c = new LoadChild();
c.Test(); c.Test(10); c.Test(ram);
Console.ReadLine();
} }
Inheritance based overloading provides an approach of adding new behaviors to a method when
the existing behaviors are not matching your requirement.
Naresh Tech. Class Notes

Hari

Page52

NagaRaj
.Net -->C#

Sri Sai Ram

Method overloading: - If a method of parent class is redefined under the child class with the same
signature is called method of overriding.
Difference Between overloading & overriding:

(Q).How can a child class override its parent class method?


Child class can override method of their parent class provided the parent class declares the
method as Virtual.
Now the child class gets the permission for overriding the method by using override modified.
Which was only optional for the child classes to override the method.
To test overriding do the following charges,
1. Go into the class load parent and add virtual modified to the test method which takes int as a
parameter:
Public virtual void test(int x);
{
Console.WriteLine(method-2);
}
Now run your child class to prove overriding is only optional and verify the output.
2. Now to override the method under child class add a new method in the class load child.
public override void test(int x)
{
Console.WriteLine(method-4);
}
Now run the child class and observe the difference in output.
When a method of parent class is overridden under child class a call to the method from child
class gives the preference to the local method execution.
At by overriding a method under child if required the child class can invoke the parent classes
virtual method also which can be done in two ways,
1. By creating the object of parent class we can invoke the parent classes virtual method.
- To test this rewrite the code under child class main method.
LoadParent p = new LoadParent();
LoadChild c = new LoadChild();
p.Test(10);
c.Test(10);
Console.ReadLine();
Note:- Earlier we have discuss references of parent class created from child class objects cant invoke
numbers of child class. But there was an execution in case of overriding. That is here parent reference
creates from child object can invokes child class overridden methods because it was dare with a
permission of parent (number of the other methods will be recognize).

Naresh Tech. Class Notes

Hari

Page53

NagaRaj
.Net -->C#

Sri Sai Ram

To check this re-writes the code under child class main method.
LoadChild c = new LoadChild();
LoadParent p = c;
p.Teat(10);
//invokes parent method.
c.Teat(10);
// invokes child method.
Console.ReadLine();
**Note: -p.Test(ram);

//invalid because it is not override.

2. Using the base keyword also we can invoke parent classes virtual method from child class.
But using of the base keyword from static block is not possible.
- To test this adds new method under this child class.
public void Ptest(int x)
{
base.Test();
}
Now in child class main method write the following code.
LoadChild c = new LoadChild();
c.Ptest(10);
//invokes parent method
c.Test(10);
//invokes child method

*** END OF THE DAY ***


Dt:-06-03-2010
Method Hiding: A method defined under parent class can be re-implemented under the child class using two different
approaches:
1. Method Overriding
2. Method Hiding
Method Overriding:-In overriding parent class first declared a method using virtual modifier giving the
child class permission to re-implement in the method which can be done by the child class using the
override keyword.
Method Hiding: -In hiding parent doesnt explicitly give any permission to the child for re-implementing
the method for the child class can perform it with the permission of parent also using the new keyword.

Naresh Tech. Class Notes

Hari

Page54

NagaRaj
.Net -->C#

Sri Sai Ram

To check this add new method under the class load child as follows:
public new void Test()
{
Console.WriteLine(Method 5);
}
From know we called to method using object of child invoke the child class method only and to
invoke the parent methods from child use the same to the approach discuss under method
overriding either by using base keyword are using object of parent class.
Note:- In overriding we have discuss references of parent class created from child class object
from if calls re-implemented method using overriding method approach invokes child class
methods it was done with a permission. But incase of method hiding it invokes its own method
but not child class method as parent didnt give a permission to re-implemented the method.
To check this rewrite code under child class main method as following:
LoadChild c = new LoadChild();
LoadParent p = c;
p.Test();
//invokes parent method
c.Test();
//invokes child method
Console.ReadLine();
Polymorphism is of two types,
1. Static or Compile type polymorphism
2. Dynamic or Runtime polymorphism
1. In static polymorphism is the object of access reusing with polymorphism method which has to
call at the time of compilation of a programming method over loading comes under the approach.
2. In dynamic polymorphism is same the object of class reusing with polymorphism method which
has to call only in the runtime. Method overloading, method overriding, hiding comes under this
approach.
How can a class be consumed from other classes. A class can be consumed from other classes in
two different approaches,
1. Inheritance (Inherit & Consume).
2. By creating the object and consume.
Sealed classes: - A class which cant be inherited by one other class was known as a sealed class.
Which should be declared using a sealed modifier.
Ex:- Sealed class Class1
{
-Define Members
}
class Class2 : Class1 Invalid

Naresh Tech. Class Notes

Hari

Page55

NagaRaj
.Net -->C#

Sri Sai Ram

Selected methods: - A method which cant be overridden under the child classes was known as a
sealed method by default every method under the class was sealed only. Because overriding of a
method is not be possible, under it was declared as virtual.
If a method is declared as virtual under a class can any of its child class override the method?
Yes, If method is declared as virtual any of its child class in a linear hierarchy or highrarkey can
override the method.
Ex:Class1
public virtual void Show()
Class2 : Class1
public override void Show()
Class3 : Class2
public override void Show()
Can a class resects its parent classs virtual method not to be overridden by its child classes?
Yes,this can be done by using sealed modifier one the method whiled overloading.
Ex:- Class1
public virtual void Show()
Class2 : Class1
public sealed override void Show()
Class3 : class2
public override void Show()
//Invalid
*** END OF THE DAY ***

Dt:-08-03-2010
Abstract classes and Abstract Methods:A Method without any method body is known as an Abstract method. It contains only the declaration
of the method, it should be declared by using the abstract modifier.
Abstract classes: - The class under which we declared this abstract method is known as an abstract
class and should be declared abstract modifier.
Ex:abstract class Test
{
public abstract void Add(int x, int y);
}
The concept of abstract method is nearly related with the concept of method overriding. Where in
overriding parent class declared a method as virtual and child class re-implements that method by
using the override keyword.
In case of abstract method parent class the class method is abstract which ha to be implemented
by the child class by using the override keyword only.
The method overriding re-implemented/overriding the method is optional where as in abstract
method implementing/overriding the method is mandatory.
Naresh Tech. Class Notes

Hari

Page56

NagaRaj
.Net -->C#

Sri Sai Ram

An Abstract class can continent both abstract and non-abstract method on it.
If a child class wants to consume the non-abstract method of is parent first it required to implement
abstract methods of its parents. Then only it can consume non-abstract method of its parent.

Note: -Wecant create object of an abstract class. So it is not useful for its self.
Add a class

AbsParent.cs
abstract class AbsParent
{
public void Add(int x, int y)
{
Console.WriteLine(x+y);
}
public void Sub(int x, int y)
{
Console.WriteLine(x-y);
}
public abstract void Mul(int x, int y);
public abstract void Div(int x, int y);
}
Add a class AbsChild.cs
class AbsChild:AbsParent
{
public override void Mul(int x, int y)
{
Console.WriteLine(x*y);
}
public override void Div(int x, int y)
{
Console.WriteLine(x/y);
}
Static void Main()
{
AbsChild c= new AbsChild();
c.Add(190, 45);
c.Sub( 98, 34);
c.Mul( 25, 25);
Naresh Tech. Class Notes

Hari

Page57

NagaRaj
.Net -->C#

Sri Sai Ram

c.Div(100, 20);
Console.ReadLine();
}
}
After implementing the entire abstract methods parent under child if required with in the child
class we can create the reference of and using this reference we can invoke all the non-abstract
and abstract methods of our parent. To check this re-write under main method of child class as
following:
{
AbsChild c= new AbsChild();
AbsParent p=c;
p.Add(190,45);
p.Sub(98,34);
p.Mul(25,25);
p.Div(100,20);
Console.WriteLine();
}

In the above case the two figures rectangle and circle war inhering from the class figure. So, they
a quid the character stick a figure which doesnt required the declaration of attributes(variable)
again this provides reusability and all the child of figure to provide the implementation for
abstract methods the were declared under the parent class figure with the same signature.

*** END OF THE DAY ***


Dt:-09-03-2010

Add a class Figure.cs


public abstract class Figure
{
public double width height, radius;
public abstract double GetArea();
public abstract double GetPerimeter();
}
Add a class Rectangle.cs
public class Rectangle : Figure
{
public Rectangle(double width, double, height)
{
this.width=width;
base.height=height;

Naresh Tech. Class Notes

Hari

Page58

NagaRaj
.Net -->C#

Sri Sai Ram

}
public override double GetArea()
{
return width*height;
}
public override double GetParimeter()
{
return d*(width+height);
}
static void Main()
{
Rectangle r =new Rectangle(234,63);
Console.WriteLine(r.GetArea());
Console.WriteLine(r.GetPerimeter());
Console.WriteLine();
} }
Interface: - An interface also a type similar to a class which can contains only abstract members.
Interface:Only abstract members.
Class
:Only Non-abstract members.
Abstract Class:Both abstract and Non-abstract members.
In interface can be case in 2 different scenarios.
1. It used in distributed application development, which developing application with Remote.
2. These also use for multiple inheritance, because interfaces support multiple inheritance.
A class can be having only one class as parent do it. Where as the same class can have multiple
interfaces as a parent to it.

Basically inheritance is 2 categories.


1. Implementation inheritance
2. Interface inheritance
1. Implementation inheritance: -The inheritance what we get with the help of a class is known as
implementation inheritance, this always single.
2. Interface inheritance: - the inheritance what we get from interface in known as interface
inheritance, this was always multiple.
Syntax: [<modifiers>]interface<Name>
{
-Abstract member declarations
}
An interface cant contain any variable in it.
The default scope of members of an interface is public.
Every member of interface by default abstract.
Just like class can inherit from a class an interface can inherit from interface.
Add a interface in a project as Inter1.cs and write the following:
Inter1.cs(add a OOPProject(right click)-add a item Name is Inter1.cs)
interface Inter1
{
Naresh Tech. Class Notes

Hari

Page59

NagaRaj
.Net -->C#

Sri Sai Ram

void Add(int x, int y);


void Sub(int x, int y);
void Test();
}
Add one more interface in Inter2.cs
interface Inter2
{
void Mul(int x, int y);
void Div(int x, int y);
void Test();
}
Add a class InterClass.cs
class InterClass : Inter1, Inter2
{
public void Sub(int x, int y)
{
Console.WriteLine(x-y);
}
public void Add(int x, int y)
{
Console.WriteLine(x+y);
}
public void Mul(int x, int y)
{
Console.WriteLine(x*y);
}
public void Div(int x, int y)
{
Console.WriteLine(x/y);
}
/*Approach 1:
public void Test()
{
Console.WriteLine(Declared in both interfaces);
}*/
// Approach 2:
void Inter1.Test()
{
Console.WriteLine(Method of interface2);
}
static void Main()
{
InterCalss obj = new InterClass();
obj.Add(23,45);
obj.Sub(90,76);
obj.Mul(25,25);
obj.Div(76,23);
Inter1 i1 = obj;
Inter2 i2 = obj;
i1.Test();
i2.Test();
Console.ReadLine();
}
}

Naresh Tech. Class Notes

Hari

Page60

NagaRaj
.Net -->C#

Sri Sai Ram

Note: - Earlier we have been discoursing multiple inheritances is not supported in .Net languages through
classes because of obliquity program. When as if we come a cross the same obliquity incase of interface it
can be dissolved in 2 ways.
1. Implement an obliquity method once under the class where each interface thing its method was
implemented as in our approach 1. In this case we can call method directly by using the object of
class only.
Ex: - obj.Test();
2. We can also implement the method separately for each interface to do this we need to prefix the
interface name before the method as in own approach 2. In this case we can invoke the method only
by using the reference of the interface under which the method was defined.

*** END OF THE DAY ***

Dt:-10-03-2010
Project or Application Management: While developing an application some times the code may be rewritten under more then one
project also, where the collection of those projects is known as a solution.
Where ever we create a new project by default visual studio will create a solution and under it the
project gets created, where a solution is collection of projects and project is collection of files or
items.
Solution
-Collection of projects
-Collection of files or items
A solution also requires a name which by default takes the name of project created first, but can
be changed if required.
A solution can have projects of different .Net languages like C#, VB, VC++,etc.., as well as
different templates like windows, console applications etc
To add a new project under an existing solution, right click on solution node in solution Explorer
select add new project which opens the new project window. Under that first select a
language (Ex:-C#) and then select a template (ex:-Console Application)name it as Second
project click ok to add the project.
Naresh Tech. Class Notes

Hari

Page61

NagaRaj
.Net -->C#

Sri Sai Ram

By default the project contains a class program under second project name space write the
following code in its main method:
Console.WriteLine(Second Project);
Console.ReadLine();
To run the above class first are need to set a property StartUp Project, because these are multiple
projects under the solution visual studio doesnt know which project we want to run so by default
it runs the first project of the solution. That is, i.e., OOPS Project.
To specify which project has to be executed use the StartUp Project property, to set this open
the solution Explorer right click on second Project and select set as StartUp Project, then run
the application.
Note:- If the project contains multiple classes in it to run a class we need to set StartUp object
property again under Second projects property window.
The application what we have crated is physically saved on the hard dick in the same hierarchy
what we see under solution explorer. i.e., first it creates a folder referring to solution under it
creates a separate folder referring to each project and under it files corresponding to project gets
saved.
D:\Csharp7\OOPs Project\OOPs Project
D:\Csharp7\OOPs Project\Second Project
A solution is saved with an extension of .sln & C# project is saved with an extension .csproj. We
can find those files under the solution folder and project folder.
When ever a project is compiled the IL Code of all files under the project will be stored on a
single file out put file known as Assembly. These Assemblies are what we carry on to client
machines when the application has to be installed, so they are referred as units of deployments.
The name of an assembly file will be same as the project name and it will be under bin\Debug
folder of each projects folder.
Ex:-D:\Csharp7\OOPs Project\OOPs Project\bin\Debug
D:\Csharp7\OOPs Project\Second Project\bin\Debug

*** END OF THE DAY ***


Dt:-11-03-2010
(Q). Can we consume a class of a project from a class of the same project?
Ans:- yes. We can consume them directly as were under same project, and were considered as a
family.
(Q). Can we consume a class of a project from a class of another project?
Ans: -Yes. We can consume but not directly as they were under different project and first need to add
reference of the assembly in which the class was present to the project who whats to consume it.
(Q). How to add reference of an assembly to a project?
Ans:- To add reference of an assembly to a project open Solution Explorer right click on the project
to when reference has to be added and select Add reference which open window select Browse
option on the top & select an assembly from its physical location and click ok. Now we can consume
classes of the assembly referring with their namespace.

Access Specification: - These are modifiers used to defined scope of a type (or) its members that
is who can access them and who cant. C# has 5 access specifies, those are:
1. Private
2. Internal

Naresh Tech. Class Notes

Hari

Page62

NagaRaj
.Net -->C#

Sri Sai Ram

3. Protected
4. Protected Internal
5. Public
Note:- Members defined under a class with any scope or specifies were always accessible with in the
class, where restrictions comes into picture only when we try to access them outside of the class.
1. Private: -Members declared as private under a class were not accessible of the class scope for
members of the class are private only. A class under a namespace cant be directed as private.
2. Protected: -Members declared as projected under a class can be access only from child classes, A
non-child class cant consume them. Class under a namespace cant be declared as protected also.
(Q).How to restrict a class not to be accessible to any other class?
Ans: -This can be done by declaring constructor of class as private.
(Q). How to restrict a class not to be inherited by any other class?
Ans: - This can be done by declaring class as sealed.
(Q). How to restrict a class not to be accessible for any other class to consume by creating its
object?
Ans: -This can be done by declaring constructor of the class as protected.
3. Internal: -Members declared internal under the class are accessible only with in the project either
from a child (or) non- child class. Default scope for access is internal only in C#.
4. Protected internal: -Members declared as protected in internal under a class enjoys dual scope
i.e. with in the project they behave as internal members and provides access to all classes, outside
the project they change to protected and still provides access to their child classes.
5. Public: - A class or member of a class if declared as public were global and can be accessed from
any where.

Accessing Members:Case 1: with in a class.


Case 2: with in a child class of same project.
Case 3: with in a non-child class of same project.
Case 4: with in a child class of other project.
Case 5: with in a non-child class of other project.

Naresh Tech. Class Notes

Hari

Page63

NagaRaj
.Net -->C#

Sri Sai Ram

*** END OF THE DAY ***

Dt:-12-03-2010

OpenVisual StudioFileNew ProjectConsole ApplicationAccessDemo(Name)


Sol. Name=My Solution default program make as public and write the following Code.
public class program
{
private void Test1()
{
Console.WriteLine(Private Method);
}
internal void Test2()

Naresh Tech. Class Notes

Hari

Page64

NagaRaj
.Net -->C#

Sri Sai Ram

{
Console.WriteLine(Internal Method);
}
protected void Test3()
{
Console.WriteLine(Protected Method);
}
protected internal void Test4()
{
Console.WriteLine(Protected internal Method);
}
public void Test5()
{
Console.WriteLine(Public Method);
}
static void Main(String[]args)
{
program p=new program();
p.Test1(); p.Test2(); p.Test3();
p.Test4(); p.Test5();
Console.ReadLine();
}}
Add a class two.cs to this project

Class two: program


{
static void Main()
{
two t = new two();
t.Test1(); t.Test2(); t.Test3();
t.Test4(); t.Test5();
} }
Add a class three.cs to this project
Class three: program
{
static void Main()
{
program p=new program();
t.Test1(); t.Test2(); t.Test3();
t.Test4(); t.Test5();
Console.ReadLine();
} }
Open solution explore r/c sol Add New Project choose console application
name = AccessDemo2 rename program.cs as Four.cs (using the sol.exp) r/c on
AccessDemo2 project in sol.exp select add reference Browse choose assembly of
accessdemo project from its physical location.
D:\csharp7\Mysolution\Access Demo1\bin\debug
Under the class Four.cs writes the code.

class Four: AccessDemo1.program


{
static void Main(String[]args)

Naresh Tech. Class Notes

Hari

Page65

NagaRaj
.Net -->C#

Sri Sai Ram

{
Four f= new Four();
t.Test3(); t.Test4(); t.Test5();
Console.ReadLine();
}
}
Add a class under the new project Five.cs
class Five
{
static void Main()
{
AccessDemo1.program p=new AccessDemo1.program();
p.Test5();
Console.ReadLine();
}
}
Language Interoperability: As we are aware .Net language can interoperate with each other i.e., code of 1 language can be
consumed from the other languages.
To test this add a new project under the My solution choosing the language as VB and template as
class library by naming it as VB project.
Note: -A class library is a collection of classes which can only we consume but not execute it.
Now under the default class class1 write the code.
public class Class1
public Function SayHello(s as String, x as integer)
Return Hello &S& &x
end Function
end class
To compile the project open the sol.Exp r/c project build (which will be compile the project
and generates assembly).
To consume this class from C# add a new class under the project AccessDemo2 naming it as
TestVB.cs.
r/c on accessDemo2 project and add the reference of VB projects assembly from its physical
location.
D:\csharp7\MySolution\VBproject\bin\Debug.
Now under the class TestVB.cs write the code.

class TestVB
{
static void Main()
{
VBProject.Class1 obj = new VBProject.Class1();
Console.WriteLine(obj.SayHello(ram,23));
Console.ReadLine();
}
}
Class Members:As we are aware a class is a collection of members which can be various types. Like,
- Fields
Naresh Tech. Class Notes

Hari

Page66

NagaRaj
.Net -->C#

Sri Sai Ram

- Methods
- Constructors
- Destructors
- Properties
- Delegates
- Enums
- Events
Destructors: It is a block of code which gets invoked when the object of a class gets destroyed. Each is
opposite to a constructor.
Where a constructor is called when object of class is created.
Some times your application may contain unmanaged resources in it. Like file handing db
mgt
Which will not be under the control of garbage collector in such cases to manage those
un-managed resources like closing of file/ connection we use the Destructor.
Destructor name is as same as class but prefix with a tilde (~) operator.
Destructor doesnt have any access prefix and import parameters.

*** END OF THE DAY ***


Dt:-13-03-2010

Add a class DestDemo.cs


class DestDemo
{
public DestDemo()
{
Console.WriteLine(object1 is Created);
}
~DestDemo()
{
Console.WriteLine(object1 is Destroyed)
}
}
class DestDemo2: DestDemo
{
public DestDemo2()
{
Console.WriteLine(object2 is Created);
}
~DestDemo2()
{
Console.WriteLine(object2 is Destroyed)
}
static void Main()
{
DestDemo2 d= new DestDemo2();
//d=null;
//GC. Collect();
//Console.ReadLine();
}

Naresh Tech. Class Notes

Hari

Page67

NagaRaj
.Net -->C#

Sri Sai Ram

}
Run the above program by using Ctrl+F5 and check the o/p which will internally call you the
constructors and destructors of both classes.
When constructors are called they will be called from top of the hierarchy and destructors will be
called from bottom of the hierarchy.
Now uncurrent the console.ReadLine() stmt and run program by using F5. Which will invoke only
the constructors but not the destructors. Because in the previous case program executors was
completed so, garbage collector come in to picture to destroy object. But in this case as the execution
of program is still not completed GC didnt come for object destruction.
So, only the constructor is called but not the destructor.
Even it was not advised we can forcefully call a Garbage Collector for destroying the object using
GarbageCollection collect ().
To check this un current the removing two lines of code and run the program.

Properties: Whenever a class has a value which should be accessible outside of the class access to the value can
be provide in 2 ways:
1. String them in a public variable.
2. String them in a private variable and define a property to access the value.
When the value was stored in a public variable every 1 has a change to get/set the value of it.
Ex: public class Test
{
public int a = 10;
}
Test obj= new Test();
int x=obj.a
//Capture the value (Get)
obj.a = 200;
//Assigning a value (Set)
If the access to the value is provided through a property we can give the access in 3 ways:
1. Both get and set access (read/write property).
2. Only get access (read only property).
3. Only set access (write only property).
Property Syntax: [<modifiers>] type <Name>
{
[get{<stmts>;}]
//Get Accessor
[set{<stmts>;}]
//Set Accessor
}

The code under the get block gets executed whenever we try to capture the value of a property.
The code under set block will be executed whenever we try to assign a value to the property.
If defined only with get block, it was a read only property.
If defined only with set block, it was a write only property.

Naresh Tech. Class Notes

Hari

Page68

NagaRaj
.Net -->C#

Sri Sai Ram

*** END OF THE DAY ***

Dt:-15-03-2010
Add a class customer.cswrite code
namespace OopsProject
{
public enum Cities{hyd, Bang, Chenni, Bombay};
class Customer
{
int custid, -age;
string -cname, -state;
Cities city;
public Customer(int custid)
{
this.-custid = custid;
//values has to come from DB
-cname = ram;
-age =25;
-city =0;
-state = Tamilnadu;
Country = India;
}
//Read only property
public int Custid
{
get{return custid;}
}
//read-write property
public String Cname
{
get {return-cname;}
set{-cname = value;}
}
//Read-write property with condition
public int Age
{
get{return age;}
set {
if(value>-age)
-age=value;
Naresh Tech. Class Notes

Hari

Page69

NagaRaj
.Net -->C#

Sri Sai Ram

}
}
//Enumerated property
public cities city
{
get {return city;}
set {-city=value;}
}
//setting scope of property accessors independency(2.0v)
public string state
{
get{return state;}
protected set{-state =value;}
}
//Automatic properties(3.0V)
public string Country
{
set;
get;
}
}
}
To consume the property add a new class TestProps.cs
class TestProps
{
static void Main()
{
Customer obj=new Customer(101);
Console.WriteLine(obj.Cname);
Obj.Cname=Rams;
Console.WriteLine(obj.Cname);
Console.WriteLine(obj.Age);
Obj.Age=20;
//Assignment fails
Console.WriteLine(obj.Age);
Obj.Age=30;
//Assignment success
Console.Write(obj.Age);
Console.Write(obj.City);
Obj.City=Cities.Hyderabad;
Console.WriteLine(obj.City);
//obj.State=AP:cant be assigned with a value this is not a child class.
Console.Write(obj.Country);
Console.ReadLine();
}
}

Naresh Tech. Class Notes

Hari

Page70

NagaRaj
.Net -->C#

Sri Sai Ram

Enum property: It is a property which can be mapped with set of values, where the user has a change of
assigning a value to the property only from the list of values proceeded.
In this case the value has to be first specified under a type known as Enum.
Syntax:[<modifiers>]enum<Name>{<list of values>};
Ex:- public enum Days{M, T, W, TH, F};
An enum is also a type which can be declared either under a namespace (or) under a
class.
As it was a type it cant be consumed unless an object of it was created.
Ex:- Days day=0; (or) days day = Days.M;
The property which is defined in this Enum type was an enumerated property.

Ex:- public Days Day


{
get{return day;}
set{day=value;}
}
Automatic Properties: This option allows you to define properties without any variable declaration and also we dont require
writing any code under get and setting blocks. But it is must and should contain get and set blocks in it.

*** END OF THE DAY ***

Dt:-17-03-2010
Delegates: Naresh Tech. Class Notes

Hari

Page71

NagaRaj
.Net -->C#

Sri Sai Ram

A delegate is a pointer to a method which can be used for executing the method when a
method gets call to execute this method each time a stack get created and destroyed. When
the method gets call for multiple time process repeat each time which may be time consuming
if our come this if it all the method is called making this delegate a single stack will be used
for executing of the method for multiple times.
Using Delegates: - To makes use of a delegate we need to follow the billow process,
Step-1: -Delegate Declaration.
Syntax: -[<modofiers>]delegate void\type<Name>([<param defs>])
Note:- the input/output of a delegate should be same as the I/O parameters of the method which the
delegate wants to call.
Ex-1: public void Add(int x, int y)
{
Console.WriteLine(x+y);
}
public delegate void AddDel(int x, int y);
Ex-2: public string SayHello(string name)
{
return Hello+name;
}
public delegate string SayDel(string name);
Step-2: - As a delegate is also a type to consume it first we need to create an object of it and
which creating the objects pass the method which the delegate has to call as a parameter.
Ex-3:AddDel ad = new AddDel(Add);
SayDel sd = new SayDel(SayHello);
Step-3:- Call the delegate for the execution of the method(from now no need of calling the
method directly for execution).
Ex-4:ad(100,50); ad(90,25); ad(800,450);
Console.WriteLine(sd(xxx));
Console.WriteLine(sd(yyy));
Console.WriteLine(sd(zzz));
Add a class DelClass.cs and write the following.
class DelCalss
{
public string SayHello(string name)
{
return Hello+name;
}
public delegate string SayDel(string name);
static void Main()
{
DelClass obj=new DelClass();
o/p:- Hello xxx
SayDel sd=new SayDel(obj.SayDel);
Hello yyy
Console.WriteLine(sd(xxx));
Hello zzz
Console.WriteLine(sd(yyy));
Console.WriteLine(sd(zzz));
Console.ReadLine();
}
}
Delegates are 2 types,
Naresh Tech. Class Notes

Hari

Page72

NagaRaj
.Net -->C#

Sri Sai Ram

1. Single cast Delegates


2. Multi cast Delegates
If delegate is used for if working a single method we called as single cast delegates.
Where as if delegate is used for calling multiple method we call it as multicast delegates.
Note: -In multicast delegates what we want to call using the delegate should have same parameters.
Add a class MultiDel.csand follows,
class MultiDel
{
public void Add(int x, int y)
{
Console.WriteLine(Add: +(x+y));
}
public void Sub(int x, int y)
{
Console.WriteLine(Sub: +(x-y));
}
public void Mul(int x, int y)
{
Console.WriteLine(Mul: +(x*y));
}
public void Div(int x, int y)
{
Console.WriteLine(Div: +(x/y));
}
public delegate void MathDel(int x, int y);
static void Main()
{
MultiDel obj = new MathDel();
MathDel math = new MathDel(obj.Add);
math +=obj.Sub;math +=obj.Mul; math+=obj.Div;
math(100,50);
Console.WriteLine();
math(450,60);
Console.WriteLine();
math -=obj.Sub;
math(625,25);
Console.WriteLine();
}
}

*** END OF THE DAY ***


t:-18-03-2010
Structure: It was also type under which we can define members, like variables, methods, constructors,
etcSame as a class. This basis difference between a class and a structure will be as
following:

Naresh Tech. Class Notes

Hari

Page73

NagaRaj
.Net -->C#

Sri Sai Ram

Add a code file under a project which create a blank file name it as MyStrut.cs and write the
following :
using System;
namespace OOPSProject O/p: -Method in a Structure : 100
{
Method in a Structure : 200
struct MyStruct
{
int x;
public MyStruct(int x)
{
this.x = x;
}
public void Show()
{
Consloe.WriteLine(Method in a Structure: + x);
}
static void Main()
{
MyStruct m1;
//Invokes default Constructor
m1.x = 100;
m1.Show();
MyStruct m2 = new MyStruct(200);
m2.Show();
Console.ReadLine();
}

Naresh Tech. Class Notes

Hari

Page74

NagaRaj
.Net -->C#

Sri Sai Ram

}
}
We can consume a structure from another structure or class by creating it object but not by
inheritance.
Add new code file MyStruct2.cs and write the following:
using System;
namespace OOPSProject
O/P:-Method in a Structure : 300
{
Struct MyStruct2
{
static void Main()
{
MyStruct obj =new MyStruct(300);
Obj.Show();
Console.ReadLine();
}
}
}
Exception & Exception Handling: within a program we may be coming across two diff. types of errors,
1. Compile time errors.
2. Run time errors.
An error which comes into picture due to syntax cal mistakes was as compile time error. This
was never dangerous.
An error which comes into picture while execution of a program was a runtime error. Which has
also known as exception.
Exception comes into picture for few basis resources like,
1. Wrong implementation of logic.
2. Invalid input supplied to the program could not locate a required resource etc
Exception were consider dangerous because wherever an exception comes into picture the
program terminate abnormally without executing the next line of code even if the code no way
related with the execution.
Exception Handling: It was a process that can be used for stopping the abnormal termination of a program whenever an
execute the code which is not related with the execution.

*** END OF THE DAY ***

Dt:-19-03-2010
How are executions Implemented:-

Naresh Tech. Class Notes

Hari

Page75

NagaRaj
.Net -->C#

Sri Sai Ram

There were member of predefined exceptions that comes in a picture on different situation.
That is for every execution scenario. We were provided with a support execution class. Which
has responsible to perform two things when in occurs.
1. Abnormal termination of the program.
2. Display an error massage specific to the error is execution.
Most of these exception class defined under the system namespace like divided by Zero
exception, Format exception, Null reference exception, etc all these exception classes were
sub classes of the predefined class exception implemented as following:
Exception
- Code generic for all exception.
DivideByZeroException : Exception
- Code specific to the exception.
FormatException : Exception
- Code specific to the exception.
NullReferenceException : Exception
- Code specific to the exception.
As discus every is a class whenever an exception situation occurs an object of related
exception class gets created and throw. Which takes the responsibility of abnormal
termination and display the error massage related with the exception.
Handling an Exception: To handle an exception we were providing with of code that is try, catch blocks which has to
be use as following:
Syntax: try
{
- stmts which will case an exception.
- stmts related with exception occurred and should not be executed.
}
catch(<execution><var>)
{
- stmts which should be executed only when an execution occurs.
}
---<multiple catch blocks if required>-- one the code is enclosed under try catch blocks the execution will be following:
If all statement in try were for execution successfully (means execution did not occurred)
the control directly from end of try Jump to the statement that was present after all the
catch blocks.
If any of the statement under try come occurs an error or exception from that line the
control directly jumps to catch blocks checking for a matching catch block to handle the
execution.
If found with a matching catch block abnormal termination stop there and executes the
code under catch block and jumps to the statement present after all the catch blocks.
If did fine matching catch blocks abnormal termination will occurs again.

Demo.cs
using System;

Naresh Tech. Class Notes

Hari

Page76

NagaRaj
.Net -->C#

Sri Sai Ram


class Demo
{
static void Main()
{
int x, y, z;
try
{
Console.WriteLine(Enter x value:);
x = int.Parse(Console.ReadLine());
Console.WriteLine(Enter x value:);
y = int.Parse(Console.ReadLine());
z = x/y;
Consloe.WriteLine(z);
}
catch(DivideByZeroException ex1)
{
Console.WriteLine(Divisor cannot be zero);
}
catch(FormatException ex2)
{
Console.WriteLine(Enter only numeric);
}
catch(Exception ex3)
{
Console.WriteLine(Error occurred);
}
Console.WriteLine(End of the program);
}
}

OutPut:

Enter x value: 100


Enter y value: 5
20
End of the program

Enter x value: 100


Enter y value: 0
Divisor cannot be Zero
End of the program

Enter x value: 100


Enter y value: y
Enter only numeric
End of the program

*** END OF THE DAY ***

Dt:-20-03-2010
Naresh Tech. Class Notes

Hari

Page77

NagaRaj
.Net -->C#

Sri Sai Ram

Finally Block: By using try and catch we can also pair one block them that is finally block. The code what
we write under this block will execute at any cost. That is its provides mandatory execution
of statements.
All statements under try will be executed only when there was no exception in the code
statements under catch will be executed only when there was an exception in the code.
Whereas statements under finally will execute in both the cases.
FinDemo.cs
using System;
class FinDemo
{
static void Main()
{
int x, y, z;
try
{
Console.Write(Enter x value:);
x = int.Parse(Console.WriteLine());
Console.Write(Enter y value:);
y = int.Parse(Console.WriteLine());
if(y==1)
return;
z = x/y;
Console.WriteLine(z);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message)
}
finally
{
Console.WriteLine(Finally Block);
}
}
Out Put:1. Enter x value : 100
Enter y value: 0
Attempted to divide by zero
Finally block
End of the program
2. Enter x value : 100
Enter y value: y
Input string was not in a current format
Finally block
End of the program
3. Enter x value : 100
Enter y value: 5
20
Finally block
End of the program

Naresh Tech. Class Notes

Hari

Page78

NagaRaj
.Net -->C#

Sri Sai Ram


4. Enter x value : 100
Enter y value: 1
Finally block

In the above program when the values to divisor as one return statement will the control
out of the program. But only after executing finally block. Because once the control
enters into the try we can never come out of a program without execution finally. That is
why we called as mandatory exception.
Note:- Massage: It was a property under the exception class which the predefined error massage associated
with currently raised exception.
While using try, catch and finally they can be used 3 different Combinations,
1.Try & catch: - Here exception will be handle which stops the abnormal termination
when the occurs.
2.Try, catch & finally: -Here exception will be handle as well as a set of mandatory
statements will also be executed when an exception occur or not.
3.Try & Finally: -Here exceptions were not handling so abnormal termination will
occurs when an exception is raised. But before abnormally terminating the program
finally block will be executed.
Exception are two types,
1. System Exceptions.
2. Application Exceptions.
An exception which is predefined and gets raised internally on same predefined
conditions was system exception.
Ex:- Format Exception, DivideByZeroException, NullReference Exception.
An Exception which was explicitly raised by the program under his the program and his
own condition it was an Application Exception.
If the programmer wants to raise an exception under his program it can be done creating
the object of an appropriate exception class and throw it by using the throw statement.
Ex:- FormatException ex =new Format Exception();
throw ex;
(or)
throw new FormatException();
Generally to raised an exception we were given with on optional to create any predefined system
exception class and throw it. But the error massage will be same massage associated with that
exception.
If we want to customize the error manage we need to create object of application exception class
which provide a parameterized constructor for which we can pass error massage as an argument.
ApplicationException(String errormsg)

Ex:- throw new ApplicationException(Divisor cant be an odd number);

ThrowDemo.cs
using System;
class ThrowDemo
{
static void Main()
{
int x, y, z;

Naresh Tech. Class Notes

Hari

Page79

NagaRaj
.Net -->C#

Sri Sai Ram


try
{
Console.Write(Enter x value:);
x = int.Parse(Console.WriteLine());
Console.Write(Enter y value:);
y = int.Parse(Console.WriteLine());
if(y%2>0)
throw new ApplicationException(Divisor Cant be odd number);
z= x/y;
Console.WriteLine(z);
Console.WriteLine(end of the program);
}
}

*** END OF THE DAY ***


Dt:-22-03-2010
Multi Threading: A single program performing multiple actions in a symaltencily is known as Multi Threading.
Traditionally we come accrues a concept multi tasking. In which more then one program can
execute at a given point of time.
Multi tasking is supported by the OS, where as Multi threading is supported by the language.
DOS was a single tasking. Window, Linux was a multi tasking applications.
Servers, MS Word, Excel etc were example for multi threading applications.
A thread is a unit of execution by default every program has one thread or unit of execution, that
is main thread, which is responsible in executing the code.
In single thread a model in there were multiple methods executed the execution will be one
method call after the other. In the sense after completely executing one method then only the
controls gos to the other method for execution.
So, in this case until the method which is executed is completing its execution other method has
to wait even if there was a delay execution of the method.
In multi threading there will be multiple unit of execution responsible in execution of code. That
is for each method we use a different thread for execution. So, the execution will be as following:
1. Time sharing.
- This was the first principle on which multiple thread will be executing. Where
the OS results some time period for teach thread to execute and makes then to
execute in a symaltencily.
2. Maximum Utilization of Resource.
- This principle comes into picture only when the first principle violated. That is if
a thread could not execute in the time allocated to it without waiting for the
thread to execute the control immediately to transfer to the other thread in
execution.
Naresh Tech. Class Notes

Hari

Page80

NagaRaj
.Net -->C#

Sri Sai Ram

How to create a thread:-to create a thread we were provided with a class thread under the
system. Threading Namespace each object we create for the class will be consider as one thread.
Will be creating the object of thread we need to pass the method name as a parameter to its
constructor.
Ex: System Threading.Thread(<Method Name>)
Thread t1 = new Thread(Method1);
Thread t2 = new Thread(Method2);
Thread t3 = new Thread(Method3);
Methods and Properties of thread class:1. Start()
- Start the execution of a thread.
2. Abort()
- Terminates the execution of a thread.
3. Suspend()
- Suspends the execution of a thread, until resume was called.
4. Resume()
- Resumes a suspend of a thread.
5. Sleep(int milliseconds)
- Suspends the execution of a thread. A static which suspend the current executing
thread until the given time period was elapsed.
6. Join()
- Makes the main thread to wait until the thread which calls leaving the program.
7. Priority()
- A newmaritic property for setting the thread of a given thread.
Add a class ThreadDemo.cs
using System.Threading;
class ThreadDemo
{
Thread t1, t2;
public ThreadDemo()
{
t1 =new Thread(show1);
t2 =new Thread(show2);
t1.Start
}
public void Show1()
{
for(int i=1; i<100; i++);
{
Console.WriteLine(Test1: +i);
if(i==100)
Thread.Sleep(1000);
}
Console.WriteLine(Thread 1 exiting);
}
public void Show2()
{
for(int i=1; i<100; i++);
{
Console.WriteLine(Test2: +i);
}
Naresh Tech. Class Notes

Hari

Page81

NagaRaj
.Net -->C#

Sri Sai Ram


Console.WriteLine(Thread 2 exiting);
}
static void Main()
{
ThreadDemo obj=new ThreadDemo();
Obj.t1.Join();
Obj.t2.Join();
Console.WriteLine(Main Thread Exiting);
}
}

*** END OF THE DAY ***

Dt:-23-03-2010
Thread Priority: By default when there was multiple threads in execution all the threads gets executed within
equal implement are priority that is OS gives same preference to all threads to share the CPU
resources. If required we can change the priority of the threads and request the OS to give
additional priority to any of the thread in execution. Each can be done by setting the priority with
any of the 5 values.
1. Lowest
2. Below Normal
3. Normal(default)
4. Above Normal
5. Highest
The thread with the highest priority well consumes more CPU resources then the thread with
lowest priority.
Add a class ThreadDemo.cs and write the following code.
using System;
using System.Threading;
class ThreadDemo2
{
Thread t1, t2;
long count1, count2;
public ThreadDemo2()
{
t1=new Thread(IncrementCount1);
t2=new Thread(IncrementCount2);
//t1.Priority = ThreadPriority.Lowest;
//t2.Priority = ThreadPriority.Highest;
t1.Start(); t2.Start();
}
public void IncrementCount1()
{
while(true)
Count1 += 1;
}
Naresh Tech. Class Notes

Hari

Page82

NagaRaj
.Net -->C#

Sri Sai Ram

public void IncrementCount2()


{
while(true)
Count2 += 1;
}
static void Main()
{
ThreadDemo2 obj =new ThreadDemo2();
Obj.t1.Abort(); Obj.t2.Abort();
Console.WriteLine(Count1 : + obj.Count1);
Console.WriteLine(Count2 : + obj.Count2);
obj.t1.Join(); obj.t2.Join();
}}
When you execute the above program two threads gets created incrementing the count variables
in a independent loop. So, by default as all the thread have the equal priority they increment the
value with equal important. In this case we cant judge which count variable will be higher.
Now uncomment the two line of code under the constructor and then execute to check the result.
Where in this case maximum the count2 value will be higher when compare be count1. Because it
was given more priority than the thread1.
Thread locking (Or) Synchronization: In multithreading we were using a different thread to call a different method. In such cases we
never have a problem but in some cases multiple threads may be calling the same method of
execution. In such case we will be getting unexpected results to check this.
Add a class ThreadDemo3.cs and write the following code.
using System;
using System.Threading;
class ThreadDemo3
{
Thread t1, t2, t3;
public ThreadDemo3()
{
t1 = new Thread(Display);
t2 = new Thread(Display);
t3 = new Thread(Display);
t1.Start(); t2.Start(); t3.Start();
}
public void Display()
{
Cosole.Write([C# is);
Thread.Sleep(5000);
Console.WriteLine(object oriented]);
}
static void Main()
{
ThreadDemo3 obj = new ThreadDemo3();
obj.t1.Join();
}
}
Run the above program and check the results where we can understand the problem which comes
in the picture because multiple threads accessing the same problem. To over come this above
problem we can lock the code under present the method as following:
public void Display()
{

Naresh Tech. Class Notes

Hari

Page83

NagaRaj
.Net -->C#

Sri Sai Ram


Lock(this){
Cosole.Write([C# is);
Thread.Sleep(5000);
Console.WriteLine(object oriented ]);
}
}

Know run the program and check out difference in out put. Where in this case as the code under
the method is lock it will allow only one thread to enter inside. And if any other thread tries to
access the method at the same time it has to wait out side until the thread which is inside come
out.

*** END OF THE DAY ***

Dt: -24-03-2010
GRAPHICAL USER INTERFACE (GUI)
Windows Applications: - Traditionally we were using application of type console also known as CUI
(Character User Interface.
Ex: - DOS & UNIX OS
Console application have disadvantages like:
1. They were not user friendly, as we need to learn the commands first to use them.
2. They do not allow navigating from one field to the other.
To solve these problems in early 90s Microsoft has introduced Graphical User Interfaces (GUI)
or windows applications with its windows OS.
Windows applications or GUI enjoy a beautiful feature known as Look and Feel.
To develop windows applications Microsoft has introduced languages into the market known as
visual basic in90s only.
Later when .Net was introduced the support for developing windows applications has been given
in all .Net languages along with VB.Net.
To develop a windows application we required a set of components known as controls which
have been provide in .Net as classes, where every control is a class available under the
namespace System.Windows.Forms
Controls were Categorized into 2 types:
1. Container Controls: - These controls are capable of holding other controls on them.
Ex:- Form, Panel, GroupBox, SplitContainer, Tab Control etc
2. Non Container Controls: -These controls are not capable of holding any controls on
them; they can be used only after being placed on a container.
Ex:-Button, Label, TextBox, ComboBox, CheckBox, TreeView, ListView, DataGridView
etc
Whatever the control is was every control has 3 things in Common:
1. Properties: - These are attributes of a control which have their impact on look of the
control.
Ex: - Width, Height, BackColor, ForeColor, etc
2. Methods: - These are actions performed by the controls.
Ex:- Clear(), Focus(), Close(), etc
Naresh Tech. Class Notes

Hari

Page84

NagaRaj
.Net -->C#

Sri Sai Ram

3. Events: - These are time periods which specify when an action has to be performed.
Ex: - Click Load, KeyPress, MouseOver, etc
How to develop a window Applications?
Ans: - To develop windows application the base control which has to be created first is a form. To
create a form defines a class inheriting from the predefined class Form so that the new class also
becomes a form.
Ex: - public class MyForm: From
To run the form we have created call static method run under applications class by passing object
of the Form we have created.
Ex:MyForm f= new MyForm();
application.Run(f);
(or)
application.Run(new MyForm());
Form where can be develop a windows application?
Ans: -A windows application can be built in 2 ways:
1. Manually from a notepad following the above process.
2. Using Windows Forms Application template of visual Studio.
Developing a windows applications using Notepad:
Write the bellow code in a notepad, save, compile & the execute:
- using System;
using System.Windows.Forms;
public class MyForm: Form
{
static void Main()
{
Application.Run(new MyForm());
}
}
Out Put: -

Partial Classes: - It was an approach introduced in C# 2.0 which allowsdefining a class an multiple files.

Naresh Tech. Class Notes

Hari

Page85

NagaRaj
.Net -->C#

Sri Sai Ram

1. The advantage in the approach was splitting of each volume (or) related code into multiple (or)
separate files. Which makes ease to organize.
2. As the code is null defined on multiple files, multiple programmers are on the same class, same time.

*** END OF THE DAY ***

Dt: -25-03-2010

Add a class Part1.cs and write the code following:


using system;
partial class Parts
{
public void Method1()
{
Console.WriteLine(Method1);
}
partial class Parts
{
public void Method2()
{
Console.WriteLine(Method2);
} }
Add a class Part2.cs and write the code following:
using system;
partial class Parts
{
public void Method3()
{
Console.WriteLine(Method3);
}
partial class Parts
{
public void Method4()
{
Console.WriteLine(Method4);
} }
Add a class TestParts.cs and write the code following:
using System;
class TestParts
{
static void Main()
{
parts p = new Parts();
p.Method1();p.Method2();
p.Method3();p.Method4();
Console.WriteLine();
}}

Naresh Tech. Class Notes

Hari

Page86

NagaRaj
.Net -->C#

Sri Sai Ram

Developing a windows Application Form Visual Studio: To develop a windows application from VS open the new project windows and select Window
Forms Application template and specify a name to it.
Ex:- WindowsProject
By default the project comes with 2 classes in it.
1. Program.cs
2. Form1.cs
The execution of windows application starts from Program.cs under which we find a main
method that creates the object of form class that has to be run.
Ex:- Application.Run(new Form1());
Form1.cs is the file under which we find class Form1 that is inherited from predefined class Form
and this is the class which we need to run.
Ex:- public partial class Form1 : Form
Windows Application under Visual Studio has 2 places to work with:
1. Design View 2. Code View
Design view is the place where we design our application, this is accessible both programmers
and end Users.
Code view is the place where we write code for execution of application, this is accessible only to
the programmers.
Note:- Because of the design view Visual Studio provides it was known as WYSIWYG
Editor(What You See Is What You Get).

using System;
using System.Windows.Forms;
public class MyForm: Form
{
public MyForm()
{
Base.Text = My own Form ;
this.Width = 400;
this.Height =400;
}
static void Main()
{
Application.Run(new MyForm());
} }

As we are aware every control has properties, method & events to it , to access the
properties and events Visual studio provides property window, which will list all
properties and events corresponding to a control, to open it select the control & press F4
then charge any property you want like Width, Height, BackColor etc
By default it displays properties of the control; we can also view events of the control by
clicking on events option in top of property window.
Note:-Methods of a control can be accessed only form code view.
Naresh Tech. Class Notes

Hari

Page87

NagaRaj
.Net -->C#

Sri Sai Ram

Whenever we set a property to control Visual Studio will internally write the code
referring to properties of control by assigning values. What we specify under property
window, where this code will be present under InitializeComponent() method and is
called from the constructor.
Ex:this.Text = TestForm
this.Width = 250;
this.Height = 250;
Note: -To view code under InitializeComponent() method Right Click on it and Select Go
toDefinition, which takes to a partial class under which the method was defined.
*** END OF THE DAY ***
Dt:-26-03-2010
If we want to write any code under in event that shard executed when the event raises
select the appropriate event in property window and double click on it, that will take you
to code view and provides to special Method under which we need to write the code.
Now in the project we have opened, goto form properties, select Events & Double click
on LoadEvent then write following code under method Form_Load generated in the
code view:
MessageBox.Show(welcome to windows application);
In the same way goto design view again and double click on ClickEvent then write following
code under method Form1_Click:
MessageBox.Show(you have clicked on form);
(Q). what is the method under which we were writing the code corresponding to an Event?
Ans: - The method, under which we write the code corresponding toan Event, is known as Event
Procedure. Which is a block of code that is bound with an event of a control and gets executed whenever
the event occurs or raises.
The code written under event procedure will be internally executed by event with help of a
delegate.

In the above case whenever the event occurs it Calles the delegates which will take
responsibility of executing code that is defined under event procedure.
(Q). How does the event,delagates and event procedure gets linked with each other?
Ans:- Events and delegates were predefined under base class libraries what we define here is only
event procedure, after defining an event procedure under form to link up the event, delegates and
event procedure Visual Studio write a mapping statement as following:
Syntax:- <Control>.<event> += new<delegate>(<event Procedure>)
Ex:- this.Load += new EventHandler(Form1_Laod);
this.Click += new EventHandler(Form1_Click);
Naresh Tech. Class Notes

Hari

Page88

NagaRaj
.Net -->C#

Sri Sai Ram

button1.Click += new EventHandler(button1_Click);


textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
Note:- we can see the above code under method InitializeComponent.
(Q). can we define an Event Procedure Manually?
Ans:- Yes.we can also define an event procedure manually, as following:
Syntax:[<modifiers>]void<Name>(object Sender, EventArgs e)
{
<Statements>;
}
Event Procedures are Non-value returning methods so they were always void.
You can specify any name to an event procedure but Visual Studio follows a convention while
naming them i.e.,
<Controlname>_<event name>.
Ex:- Form1_Load, button1_Click, textBox1_KeyPress.
Every event procedure should take 2 mandatory parameters:
1. Object Sender
2. EventArgs e
Note: - the concept of events and event procedures has been derived from classical VB, but an event
procedure can be bound with any a single event of a single control, events of a single control as well as
with multiple controls also.
Write the code is a Notepad and execute them.
MyForm2.cs
using System;
using System.Drawing;
using System.Windows.Forms;
public class MyForm2: Form
{
public MyForm2()
{
InitializeComponent();
}
private void InitializeComponent()
{
base.Text = My own Form ;
this.Size = new Size(400,400);
this.Load += new EventHandler(Test);
this.Click += new EventHandler(Test);
}
private void Test(object Sender, EventArgs e)
{
MessageBox.Show(Event Raised);
}
static void Main()
{
Application.Run(new MyForm2());
}
}
Add a new forms under the project.
- If we want to add a new form under the project open Solution Explorer, Right
Click on project and select add Windows Form which adds the form as
Form2.cs
Naresh Tech. Class Notes

Hari

Page89

NagaRaj
.Net -->C#

Sri Sai Ram


-

To run the form go into program.cs file and change the code under application.
Run method from Form1 to Form2.
(Before changing)
Appliction.Run(new Form1());
(After changing)
Application.Run(new Form2());

*** END OF THE DAY ***

Dt:-27-03-2010
Binding an Event Procedure with multiple events of a control inVisual Studio:
After the new form is added to project goto its properties, select events and double click on
Load event with defines an event procedure Form2_Load.
If we want to bind the same event procedure with click event of form also again goto events
procedure available in the class, select Form2_Load which was defined previously that
binds the event procedure with click event also, now under the procedure write following
code:
MassageBox.Show (Bound with multiple events of a Control);
Placing Controls on a form:
By default we ware provided with no. of controls as classes which are available under
ToolBoxwindow, to view than go to view menu and select TooBox, which displays all
controls organized in the form of Tabs (groups).
To place controls on form either double clicks on desired control or selects the control &
places it in the desired location on form.
Binding on event procedure with multiple controls:
Add a new form in the button1 & double clickon click event to define
button1_clickevent procedure, map the event procedure with button2 & button3 also.
Now under the event procedure write the following code:
Button b = (Botton)Sender;
if(b.Name)==botton1
MessageBox.Show (Button1 is clicked);
else if(b.Name)==botton2
MessageBox.Show (Button2 is clicked);
else if(b.Name)==botton3
MessageBox.Show (Button3 is clicked);
When an event procedure is bound with multiple controls to recognize the control that
has raised the event we can make use of the parameter Sender of event procedure, as it
was of they object, in run time object of the control that has raised the event will be
captured in it.

Naresh Tech. Class Notes

Hari

Page90

NagaRaj
.Net -->C#

Sri Sai Ram

Note: - As sender cannot refer to the members of control as it was in parent format, so first needs to be
converted into appropriate control type and then to the controls members.
To convert sender into a control format use the following statements:
Button b = (Button)Sender;
(Or)
Button b = Sender as Button;
-----------------------------------------TextBox tb = (TextBox)Sender;
(Or)
TextBox tb = Sender as TextBox;
Every control by default has 2 important properties:
1. Name
2. Text

Name is used for recognizing the control where as text is used for associating some user
defined data with the control.
Note:- By default when a control is created both the 2 properties will have same value which
can be changed as required.
As we are aware every control has No. of events under them, but 1 event will be default
for a control. To write code under default events event procedure we can directly double
click on the control which takes to its mapping event procedure.

Control:
Form
Button
TextBox
CheckBox&RadioButton
TreeView
Timer
ListView, ListBox, Combo

Naresh Tech. Class Notes

Default Event:
--------

Hari

Load
Click
TextChanged
CheckedChanged
AfterSelect
Tick
SelectedIndexChanged

Page91

NagaRaj
.Net -->C#

Sri Sai Ram

*** END OF THE DAY ***

Dt:-29-03-2010
Lable:-Used to display static text on the form. We associated the text to it using the text
property of the control.
TextBox: - Used for taking text input from the users. The control can used in 3 ways:
1. Single line text(default)
2. Multi line text(text area)
3. Password Field.
o To use the control as a multiline text change the multiline property of the control as true, know
use can increase the height of your control.
o By default text area doesnt have scroll Box to it. To make the scroll box visual set the scroll box
property either to vertical or horizontal or both. Horizontal scroll Box get enable only if the Ward
Wrap property of the control is set as false it should be default true.
o To used text Box control has a Password field specified the character we want to use as a
password character under the property.
Ex:-PasswordChar: *(in properties)
Note:- View Tab order Tab order is used to order to tab option specification.

private void btnSave_Click(object sender, EventArgs e)


{
//code the save data send to database.
}

private void btnClear_Click(object sender, EventArgs e)


{
txtName.Clear(); txtPwd.Clear();
txtCPwd.Text= ; txtPhone.Text= ; txtAddress.Text= ;
txt.Name.Focus();
}
(or)
private void btnClear_Click(object sender, EventArgs e)
{
txtName.Clear(); txtPwd.Clear();
txtCPwd.Text= txtPhone.Text=txtAddress.Text= ;

Naresh Tech. Class Notes

Hari

Page92

NagaRaj
.Net -->C#

Sri Sai Ram


txt.Name.Focus();
}
(or)
private void btnClear_Click(object sender, EventArgs e)
{
txtName.Clear(); txtPwd.Clear();
txtCPwd.Text(); txtPhone.Text();txtAddress.Text();
txt.Name.Focus();
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}

Properties AcceptButton (None,btnSave, btnClear, btnClose)


Properties CancelButton (None,btnSave, btnClear, btnClose)

private void txtName_Validating(object sender, EventArgs e)


{
MessageBox.Show(Validating);
}
private void txtName_Leave(object sender, EventArgs e)
{
MessageBox.Show(Leave);
}
private void txtName_Validating(object sender, EventArgs e)
if(txtName.Text.Length==0)
{
MessageBox.Show(cannot leave empty);
}
private void txtName_Validating(object sender, EventArgs e)
if(txtName.Text.Length==0)
{
MessageBox.Show(cannot leave empty);
e.Cancel=true;
}
Note:-e = e is the current executing Event property.
Select Password button(goto) propertiesValidating txtName_ValidatingEx:-

private void txtName_Validating(object sender, EventArgs e)


if(tb.Text.Trim().Length==0)

Naresh Tech. Class Notes

Hari

Page93

NagaRaj
.Net -->C#

Sri Sai Ram


{
MessageBox.Show(cannot leave empty);
e.Cancel=true;
}

private void txtName_Validating(object sender, EventArgs e)


if(tb.Text.Trim().Length==0)
{
MessageBox.Show(cannot leave empty);
e.Cancel=true;
}
if(tb.Name !=txtName)
{
if(tb.Text.Trim().Length<6)
MassageBox.Show(password should be between 6-12 character);
}

MaxLength 32767(default)
MaxLength 12

*** END OF THE DAY ***

Dt:-30-03-2010

Naresh Tech. Class Notes

Hari

Page94

NagaRaj
.Net -->C#

Sri Sai Ram

In windows form the focus navigates between each control with the use of TabKey in
keyboard.
The default sequence of navigation in the same order how controls were placed on the form.
If we want to set the under of navigation as per our requirement goto view (menu) Tab
Under which displays the current tab under of controls.
Click on each control in a sequence in which order we want to navigate. Again goto view
Tab Order.
In the above from perform following validations:
1. Give the provision to close the form ESC key of KeyBoard.
To do this goto from properties and under the close Button property btnclose. So that
cancel Button gets mapped with ESC key and gets clicked whenever we press ESC.
Note:- in the same way we can also map any button with enter Key of keyboard using
Acceptbtn property of form.
2. Check the username, Password, Conform Password to be mandatory fields.
3. Check Pwd, Cpwd to ranging between 6-12 character.
4. Check Cpwd to be matching with Pwd.
5. Give a provision to close the form by clicking on close button without entering
mandatory fields.
To do all above 1st goto properties of Pwd, Cpwd textboxes and set the maxlength
property as 12. So that is accept only 12 chars.
Define a validating event procedure for username textbox and bind it with Pwd,
textboxes also.Now write code:

Class Declaration:
TextBox tb; //on top of the class.
Under validating event procedure:
tb = sender as TextBox;
if(tb.Text.Trim().Length==0)
Naresh Tech. Class Notes

Hari

Page95

NagaRaj
.Net -->C#

Sri Sai Ram


{
MsgBox.Show(cant leave empty);
e.Cancel= true;
return;
}
if(tb.Name !=txtName)
{
if(tb.Text.Trim().Length<6)
{
MassageBox.Show(password should be between 6-12 character);
e.Cancel= true;
return;
}
}
if(tb.Name ==txtCpwd)
{
if(txtPwd.Text != txtCpwd.Text)
{
MassageBox.Show(Confirm pwd should match with pwd);
e.Cancel= true;
return;
}
}

*** END OF THE DAY ***

Dt:-31-03-2010
Define a leave event procedure for user name textbox and bind it with Pwd & confirm Pwd
textboxs then write following under the event procedure:
tb = server as TextBox;
Goto properties of cancel button, set causes validation property as false, so that code under
click event of the button will execute first then any controls validating event. Now under
click event of the button write the following code:
tb.CausesValidation = false; //will not allow validating event textbox
this.Close();
to fire.
6. Check the phone textbox to accept numerics and backspace key only.
Naresh Tech. Class Notes

Hari

Page96

NagaRaj
.Net -->C#

Sri Sai Ram

To do this define a KeyPress event procedure for phone textbox and write the following code:
/* To find ascii values of keys uncomment the bellow line of code */
//MessageBox.Show(Convert.ToInt32(e.KeyChar).ToString());
if(char.IsDigit(e.KeyChar)==false && Convert.ToInt32(e.KeyChar)!=8)
{
MessageBox.Show(Enter numerics only);
e.Handled=true;
}
Under Save Button:
//code to save data to database
MessageBox.Show(Data saved to database);
Under Clear Button:
//txtName.Clear();txtPwd.Clear();
txtCPwd.Clear(); txtPhone.Clear();
txtAddress.Clear(); txtName.Focus();
Validating event occurs when a control was loosing its focus & then performs the validations.
KeyPress event occurs when the focus was under a control and key is pressed and realized.
Some events has properties under them to refer the properties of an event under its event
procedure we can make use of the parameter e of event procedure which will refer to
current executing events properties.
Cancel property of validating event when set as true will not allow the focus to leave the
control.
KeyChar property of KeyPress event returns the char value of KeyPressed and released on
KeyBoard.
Handled property of KeyPress event when set as true will restrict the key used not to come
inside the textbox.
Convert.ToInt32(char ch) returns the ascii value of the given character.
char.IsDigit(char ch) returns true if the given character is numeric or else returns
false.
Note:-char is a structure.
(Q). How does a form gets created?
Ans: - When a form is created internally following things takes place:
i.
Creates a class inheriting from predefined class form so that the new class also becomes a form.
Ex:- public partial class Form1:Form
ii.
Sets some initialization properties like name, text etc under the method InitializeComponent.
Ex:this.Name =Form1;
this.Text =Form1;
(Q).How does a control gets placed on the form?
Ans: -When a control is placed on form following things takes place:
i.
Creates object of appropriate control class.
Ex:- Button button1=new Button();
TextBox textBox1=new TextBox();
ii.
Sets some initialization properties that are required like name, text, size, location etc
Ex:- button1.Name=button1;
button1.Text=button1;
button1.Location=new Point(x,y);
button1.Size=new Size(width, height);
iii.
Now the control gets added to from by calling controls add method on Form.
Ex:- this.Controls.Add(button1);
Note:-The above code will be generated by visual studio under the method InitializeComponent.
Under a windows application code is categorized into a types:
1. Designer code.
Naresh Tech. Class Notes

Hari

Page97

NagaRaj
.Net -->C#

Sri Sai Ram

2. Business Logic.
The code which is responsible for construction of the form is known as designer code.
The code which is responsible for execution of the form is known as Business logic.
Designer code is generated by visual studio under method InitializeComponent &
Business logic is defined by programmers in the form of event process.
Before .Net 2.0 designer code & business logic were defined under a class present in a
single file.
(Before VS 2005)
Form1.cs
public class Form1:Form
{
-Designer code
-Business Logic
}
Form .Net 2.0 with introduction of partial classs designer code & business logic were
separated into 2 different files but of the same class only.
(Form VS 2005)
Form1.cs
public class Form1:Form
{
-Business Logic
}
Form1.Designer.cs
Partial class Form1
{
-Designer code
}
Check Box & RedioButtons:
These controls were used for taking the input from the user in form a selection for a list of
available values.
RedioButton allows only single selection were as CheckBox allows multi selection.
Because a RadioButton allows single selection if we want use them under different question (or)
options we required to group them. So, that are value can selected them each group, to group
them place them are separated container like a panel or group Box.
Both these two controls provide a common property checked to identified whether the control are
selected or not. Its a Boolean property its return true, if selected or else returns false.
** END OF THE DAY ***
Dt:-01-04-2010

Naresh Tech. Class Notes

Hari

Page98

NagaRaj
.Net -->C#

Sri Sai Ram

Under Button1:
if(radioButton1.Checked)
MessageBox.Show(RadioButton1 selected);
else if(radioButton2.Checked)
MessageBox.Show(RadioButton2 selected);
else if(radioButton3.Checked)
MessageBox.Show(RadioButton3 selected);
Under Button2:
if(ChechBox1.Checked)
MessageBox.Show(Check Box1 selected);
if(ChechBox2.Checked)
MessageBox.Show(Check Box2 selected);
if(ChechBox3.Checked)
MessageBox.Show(Check Box3 selected);
Checked Changed Event:
This was the default event of CheckBox & RadioButton controls which will be finding whenever
the control will be selected as well as deselected also.

Set the name of amount TextBox as txtAmount, and set Read only property true & set text as
Zero.
For every CheckBox & RadioButton set the Tag property with fees amount, Normal should have
the Tag as Zero.
Defined it checked changed event for any one CheckBox & Bind it with all the remaining
CheckBoxes.
Defined it checked changed event for any one RadioButton & Bind it with all the remaining
RadioButton.
Then write the following code:
Declatrations:
int Count=0;
-----------------Under CheckBox checkedChanged:
CheckBox cb=sender as CheckBox;
int amt=int.Parse(txtAmount.Text);
if(cb.Checked)
{
Naresh Tech. Class Notes

Hari

Page99

NagaRaj
.Net -->C#

Sri Sai Ram


count +=1;
amt +=Convert.ToInt32(cb.Tag);
}
else
{
amt -=Convert.ToInt32(cb.Tag);
}
if(count==0)
radioButton1.Checked=true;

Under RadioButton checkedChanged:


int amt=int.Parse(txtAmount.Text);
if(amt>0)
{
RadioButton rb=sender as RadioButton;
if(rb.Checked)
amt += Convert.ToInt32(rb.Tag);
else
amt -= Convert.ToInt32(rb.Tag);
txtAmount.Text=amt.ToString();
}
else
radioButton1.Checked =true;
*** END OF THE DAY ***

Dt:-02-04-2010
ComboBox, ListBox, CheckedListBox: These three controls pare all so used for taking the input from the user on form of the selection
from the list of available values.
ComboBox allows only single selection, but can be edited.
ListBox by default gives only single selection but can be change into multi selection.
CheckedListBox by default provides Multi selection.
Adding values to the Controls: We can add values to the controls in diff. mechanism like,
1. In the properties of the control we find items property select and click on the Button beside it.
Which open a window under which we can enter the list of values.
2. Using the items.Add method of the control we can add a single values to the control.
Syntax:- <control>.Items.Add(object value)
3. Using the item.AddRange method we can add an array of values to the control.
Syntax:-<control>.Items.AddRange(object[] values)
4. Using the data source property of control we can bind of table directly to the control. But, as
the control can display only a column of values in it. We need to specify which column we
want to display using the display member property.
<control>.DataSource = <data table>
<control>.DisplayMember = <cd name>
Multi Selection for ListBox: -ListBox by default provides single selection only if we want
multiSelection we can set it use in the selection mode a numerated property. With a value either
multiSimple or multiExtended.
Selection mode:
Naresh Tech. Class Notes

Hari

Page100

NagaRaj
.Net -->C#

Sri Sai Ram

None
One[default value]
MultiSimple(only Mouse click)
MultiExtended(Ctrl+Mouse click)
Identifying the values choose an under the controls. To identified or pick the value choose by the
values we can make use of following properties.
ComboBox:o Text

string
o selectedItem

object
o SelectedIndex

int
ListBox:o selectedItem
object
o selectedIndex

int
o selectedItems

object[]
o selectedIndices

int[]
CheckedList:o CheckedItems

object[]
o checkedIndices

int[]
Goto the items collection property of comboBox add a list of countries in the control. Then write
the followings code:
Under From Load:
listBox1.Items.Add(AP);
listBox1.Items.Add(Tamilnadu);
listBox1.Items.Add(Karnataka);
listBox1.Items.Add(Kerala);
listBox1.Items.Add(Orrisa);
listBox1.Items.Add(Maharastra);
string[] cols={Red,Blue,Yellow,White,Black};
CheckedListBox1.Items.AddRange(cols);
Under ComboBox KeyPress:
if(Convert.ToInt32(e.KeyChar)==13)
if(ComboBox1.FindString(ComboBox1.Text)==1)
comboBox1.Iems.Add(comboBox1.Text);
Under Button1 Click:
MessageBox.Show(comboBox1.Text);
Under Button2 Click:
foreach(object obj in listBox1.SelectedItems)
MessageBox.Show(obj.ToString());
Under Button3 Click:
String str=null;
foreach(object obj in CheckedListBox1.CheckedItems)
str t=obj.ToString()+,;
str=str.SubString(0,str.Length-2);
int pos=pos=str.LastIndexOf(,);
if(pos != -1)
{
str=str.Remove(pos,1);
str=str.Insert(pos,and);
}
MessageBox.Show(str);

Naresh Tech. Class Notes

Hari

Page101

NagaRaj
.Net -->C#

Sri Sai Ram

*** END OF THE DAY ***


Dt:-05-04-2010
Selected Index Changed: It is the default event of the all about 3 controls. Which gets raised after selecting a value from the
control.
Add Fomr8.cs
Declarations:
String[] q1={January,Feb,March};
String[] q2={April,May,June};
String[] q3={July,Aug,Sep};
String[] q4={Oct,Nov,Dec};

-------------------------------------------ComboBox SelectedIndexChanged:
listBox1.Items.Clear();
switch(comboBox1.SelectedIndex)
{
case 0:
listBox1.Items.AddRange(q1);
break;
case 1:
listBox1.Items.AddRange(q2);
break;
case 2:
listBox1.Items.AddRange(q3);
break;
case 3:
listBox1.Items.AddRange(q4);
break;
}
Creating Menus: To create a Menu for your application, place a Menu strip control on from which sits in top of the
form.
To add menu or menu strip, click on Left hand side comes of it which opens a textbox asking to
Typethere. Enter, name in it which adds a menu, repost the same process fir adding multiple
MenuItems.
To add a Menu item under Menu click on a Menu which opens a textbox below it asking to type
here, enter a Name in it which adds a Menuitem under the MenuItems.
Naresh Tech. Class Notes

Hari

Page102

NagaRaj
.Net -->C#

Sri Sai Ram

If we want Munus to be responding for Alt Keys of keyboard prefix& before the character
which should respond for Alt.
Ex:- &File
&Edit
F&ormat
To create a shortcut for MenuItem so that it responds for keyboard auction, go to properties
ofMenuItem & select shourtcutkeys property, click on drop down beside it which displays a
window where we can choose a modifier like Ctrl or Alt or Shift & then choose a key from the
drop down below.
To group related MenuItems under a Menu we can add separators between MuneItems. To do this
right click on a MenuItem add select Insert separator which adds a separator on top of the
MenuItem.
If we want to display an image beside MenuItem right Click on it& select SetImage which
opens a window select Local Resource & then click on import button which opens a Dialog Box
using it select an image from your Hard disk.
Some times we find check marks beside MenuItems to identify whether a property is on or off.
Ex:- WordWrap under Notepad.
If we want to create check marks beside a MenuItems right click on the MenuItem & select
Checked.
But to check ort uncheck the item in run time we need to write the code explicitly under its click
event as following:
if(<control>.Checked==true)
<control>.Checked=false;
else
<control>.Checked=true;

*** END OF THE DAY ***

Dt:-06-04-2010
Multi Document Interfaces (MDI): Which designing an application when ever we have more the one form to run, we were setting
provide source code under the class program, but as we dont provide source code to click when
Naresh Tech. Class Notes

Hari

Page103

NagaRaj
.Net -->C#

Sri Sai Ram

we deploy the application, he will not have a chance to edit the class program and specify his
start-up Form.
In that case we use MDI approach, where we will be having only one Form as a start-up Form
which does not required clients to change it each time & rest of the forms in the application will
be under control of MainForm or Start-up From.
In this approach we have two parts:
1. MDI Parent.
2. MDI Child.
The Form which is going to start the execution is MdiParent, to make a for m as MdiParent set
the IsMdiContainer property of Form as true, an application has only one MdiParent in it.
Rest of the forms under application will be the child forms of parent which comes & sits under
parent Form.
Ex:- Visual Studio is an MdiParent which launches all the remaining forms under it as Childs.
To make a form as child to parent form create object of the Form class we want to launch & set
its MdiParent property with reference of parent form & then call show method.
When we have more than one child form launched under parent the way we they are arranged is
set by Layout to the parent, which can be of the following options:
1. Cascare(d):child forms are arranged one on the top of the other.
2. TileVertical:child forms are arranged one on the beside the other.
3. TileHorizontal: child forms are arranged one on the below the other.
Note: - while designing an application we always make the first form in project as MdiParent.
Add a new Form9.cs& set the IsMdiContainer property as true, also set the windows state
property as Maximize. Which opens the form to the full size of the screen.
Place on a Menu Script control on it & add 2 Menus(Forms, Layout). Under forms Menu add a
separate menu item to launch all the other forms in the application.
Ex:- Form1, Form2, Form3
Under Layout Menu add the Menu item Cascade, TileVertical, TileHorizontal.
Under Form Menu Items,
Form1:
Form1 f=new Form1();
f.MdiParent=this;
f.Show();
Form2:
Form2 f=new Form2();
f.MdiParent=this;
f.Show();
Form3:
Form3 f=new Form3();
f.MdiParent=this;
f.Show();
Under Layout Menu Items,
Cascade:
This.LayoutMdi(MdiLayout.Cascade);
TileVertical:
This.LayoutMdi(MdiLayout.TileVartical);
TileHorzotal:
This.LayoutMdi(MdiLayout.TileHorizontal);
Naresh Tech. Class Notes

Hari

Page104

NagaRaj
.Net -->C#

Sri Sai Ram

User Controls: These are controls which for design by the programmer as for their requirements & consume
them under the applications there are 2 types:
1. Creating a control from scratch.
2. Inherited or Extended control.
1. Creating a control from Scratch: - In this case we all together design a new control as per our
requirement and consume it. To create a control from scratch we need to define a class inheriting
from the predefined class user control.
Ex:-

2. Inherited or Extended Control: - In this case we dont design any control we only customize on
existing control by adding with new properties or methods, etchere we define a class by
inhering from the control for which we want to provide the new behavior.
Ex:public class Numaric TextBox: TextBox
{
-Define the new Behaviour
}

*** END OF THE DAY ***

Dt:-07-04-2010
Creating control from Scratch:
Open a new project by choosing the template as windows Form control Library, name is as
control project and click Ok.
By default the project comes a control, user control inherited from the class user control.
Open the solution Explore & Rename user control.cs as address so that the name of control
changes as address.
Naresh Tech. Class Notes

Hari

Page105

NagaRaj
.Net -->C#

Sri Sai Ram

Design the control as following,

Go to the properties of MaskedTextBoxselect masked properties & click on the button beside it.
Which opens the window select <custom>& enter 6 zeros (000000) in the MaskText billow &
click OK.
Note:- MaskTextBox is same as a textbox, which is used for taking input from the user in specific
format like date, time, phone no., etc
To set a mask we can either choose from the list of available format are specify your own format,
other wise by selecting customers & provide the format MaskTextBox billow using Zero.
Know go to code view & write following code under address class,
//Defining properties to the Control
public string Street
{
get{ return txtStreet.Text; }
set{ txtStreet.Text=value; }
}
public string Buliding
{
get{ return txtBuilding.Text; }
set{ txtBuilding.Text=value; }
}
public string City
{
get{ return txtCity.Text; }
set{ txtCity.Text=value; }
}
public string State
{
get{ return txtState.Text; }
set{ txtState.Text=value; }
}
public string Pin
{
get{ return txtPin.Text; }
set{ txtPin.Text=value; }
}
public string Country
{
get{ return txtCountry.Text; }
set{ txtCountry.Text=value; }
}
//Defining method to the Control:
public void ClearAll()
{
txtStreet.Text=txtBuilding.Text=txtCity.Text=;
Naresh Tech. Class Notes

Hari

Page106

NagaRaj
.Net -->C#

Sri Sai Ram

txtState.Text=txtPin.Text=txtCountry.Text=;
}
Know open Solution Explore Right click on the project(Ex:- ControlProject) select Build, which
will compile theproject & generate on assembly.
Consuming in the controlling: We can consume in the control only by placing with on a form. So, go our windows project to
consume to control.
In we want the control to be add in our ToolBox that can be add to any existing tab as well as add
our own tab to place our controls.
To place our own tab on the ToolBox Right click on the ToolBox & select add Tab specified name
as Csharp7(folder name)control.
To add our control under the tab Right Click on the tab & select choose items, click on the
Browser button in the window open & select the controlsProject assembly from it physical
location.
D:\csharp7\ControlsProject\ControlsProject\bin\Debug
Know the control Gets added under out tab. which can placed on a form & consume.
Create a Form as following,

Under Get Values Button:


//Consuming the following of control
MessageBox.Show(address1.Street);
MessageBox.Show(address1.Building);
MessageBox.Show(address1.City);
MessageBox.Show(address1.State);
MessageBox.Show(address1.Pin);
MessageBox.Show(address1.Country);
Under Clear Values Button:
//Consuming the methods of control
address1.ClearAll();
Under Close Button:
this.Close();

*** END OF THE DAY ***


Dt:-08-04-2010
Developing an Inherited Control: As w discuss earlier here w dont design any control from the scratch. We only define a class
inheriting from the predefine control class.
Add new class under the ControlProject naming it as MyTextBox.cs Make the class public
& write the following code:
o using System.Windows.Forms;
----------------------------------------------------------------------Naresh Tech. Class Notes

Hari

Page107

NagaRaj
.Net -->C#

Sri Sai Ram

public classMyTextBox:TextBox
{
public enum Options{Any, Char, CharOrDigit, Digit};
Options opt =0;
public Options SetOption
{
get{return opt;}
set{opt=value;}
}
public MyTextBox()
{
this.KeyPress +=new KeyPressEventHandler(MyTextKeyPress);
}
private void MyTextBox_KeyPress(object sender,KeyPressEventArgs e)
{
if(Convent.ToInt32(e.KeyChar)==8)
return;
switch(opt)
{
case Options.Digit:
if(Convert.ToInt32(e.KeyChar)==46)
if(this.Text.Index(.)>=0)
e.Handled=true;
if(char.IsDigit(e.KeyChar)==false&&Convert.ToInt32(e.KeyChar)!=46)
e.Handled =true;
break;
case Options.Char:
if(char.IsLetter(e.KeyChar)==flase)
e,Handled=true;
break;
case options.CharOrDigit:
if(char.IsLetterOrDigit(e.KeyChar)==false)
e.Handled=true;
break;
}
}
}
Open Solution Explore ReBuild the project which regenerates the assembly with the new control.
Know consume the control go into the windows project Right Click on the csharp7(fine name)
control Tab we have add in the ToolBox & select Choose item click Browser & select the
Assembly of controls project from it physical location again. Click on OK which adds the control
MyTextBox under the address control. Know place the control on the form go to its properties
where we can find the set option property with default value as any, change it as for your
requirement consume it.
Data Source Communication:
Data source or data store is as place where we store the information. We have varies type if data
sources like files, data bases, indexing servers,etc
While developing applications we were required storing the information under a data source. But
applications cannot communicate with sources directly because each data source adapts a
different protocol for communication.

Naresh Tech. Class Notes

Hari

Page108

NagaRaj
.Net -->C#

Sri Sai Ram

Because a direct communication between applications and data sources was not possible. To
sophisticatethe process of communication Microsoft was provide a solution in the form of drivers
and providers. Which will cat as a mediator between the application and data sources to
communicate with each other.

Drivers:
As a startup Microsoft has earlier designed the drivers to communicate with databases. There are
2 types again.
1. JET Drivers.
2. ODBC Drivers.
1. JET Drivers(Joint Engine Technology Drivers):-These are designed for local base
communication.

Example of databases is Dbase, FoxPro.


2. ODBCDrivers:- Its stands for open Database Connectivity. These are design remote database
communication.
Ex:- Oracle, SQL Server.

Drawback of Drivers: 1. Earlier they were design to communicate only with databases.
2. As the drivers are not part on of a application they need to be installed on each &
every machine the application was running & the configure between the
application, drivers & database.
*** END OF THE DAY ***
Dt:-09-04-2010
OLEDB Providers:-These are design for data source communication and the directly 6 along
with your application which dont required separate installation & configuration on the client
machine.

Note:- Both the driver & providers from Microsoft have a problem they will be design by using native
code language. Because of the native code support in them Visual Basic language was not capable to

Naresh Tech. Class Notes

Hari

Page109

NagaRaj
.Net -->C#

Sri Sai Ram

communicate with then directly. To overcome the problem Microsoft was developed few intermediate
components for Visual Basic to Communicate with drivers & Providers.

1. DAOs
2. RDOs
3. ADOs

Data Access Objects.


Remote Data Objects.
ActiveX Data Objects.
ADO.NET:

ADO.Net:
It was a collection of Managed providers used for communication with data source from .Net
applications.
When .Net was introduced to communicate with data source from .Net applications the best of
traditional 3 technologies, ADOs has been redesigned as ADO.Net.
ADO.Net provides various classes which can be used for data source communication under the
following named spaces:
System.Data
System.Data.Oledb
System.Data.SqlClient
System.Data.OracleClient
System.Data.Odbc
System.Data:-Collection of classes used for, holding & managing the data on client machines.
Classes under this were:
DataSet, DataTable, DataRow, DataColumn, DataView, DataRetation, etc
System.Data.Oledb:- Collection of classes used for communication with any DataSource.
System.Data.SqlClient:-Collection of classes used for communication only with Sql Server.
System.Data.OrcleClient:-Collection of classes used for communication only with Orcle.
System.Data.Odbc:-Collection of classes used for communication with traditional Odbc Drivers
which will in turb Communicate with DataSources.
All the above 4 namespaces contains same set of classes, as following: Connection,Command,
DataReader, DataAdapter, CommandBuilder, Parameter etc
Note:-Each class was referred by prefixing with the namespace before class name to discriminate
between each other as following:
Ex:- OledbConnection
- OledbCommand
- SqlConnection
- SqlCommand
- OracleConnetion
- OracleCommand
- OdbcConnection
- OdbcCommand
Every operation we perform on a data sources involves of 3 steps:
Establishing a Connection.
Naresh Tech. Class Notes

Hari

Page110

NagaRaj
.Net -->C#

Sri Sai Ram

Applying a Statement.
Expecting the Result back.
Establishing a Connection:-In this process we open a channel for communication with target
machine to perform our operations. To open the channel for communication we use connection
class.
Constructors:
Connection()
Connection(String ConnectionString)
ConnectionString is a collection of attributes that are used for connecting with target
machine, those are:
- Provider
- Data Source
- User Id & Password
- Database or Initial Catalog
- Trusted_Connection
- DSN.
Provider:-As we were a ware provider is required for communicating with data sources,
we use a different provider for each data Source.
- Oracle
Msdaora
- Sql Server
SqlOledb
- Ms-Access or Ms-Excel
Microsoft.Jet.Oledb.4.0
- Indexing Server
Msidxs
Data Source:-It was name of target machine where the data source your db is present,
doesnt require to be specified if it was on the local machine.
User Id & Password:-As dbs were secured places for storing data to connect with them
we require a valid User name & password.
- Oracle
Scott/ tiger
- Sql Server
Sa /<blank>
DataSource or Initial Catalog & Trusted_Connection attributes will be used only
while connecting with Sql Server.
DSNattribute is used only in case of Odbc classes.
Connection String for Oracle: Provider=Msdaora;User Id=Scott;Password=tiger
[;Data Source=<server>]
Connection String for Sql Server: Provider=SqlOledb;User Id=Sa;Password=<Pwd>;
Database=<db name>[;Data Source=<server>]
*** END OF THE DAY ***
Dt:-10-04-2010
Methods & properties of connection class: Open():-Method to open connection.
Close():- Method to close the connection.
State:- a property to find status of the connection.
ConnectionString:- Property to get or set the ConnectionString.
To object of class connection can be created in any of the following ways:
Connection con =new Connection();
Naresh Tech. Class Notes

Hari

Page111

NagaRaj
.Net -->C#

Sri Sai Ram

con.ConnectionString= <con str>;


(or)
Connection con = new Connection(<con str>);
Open new project Visual C# windows forms application file name DBOperations.
Then, Form1.cs
Open a new project of type window name it is a DBOperation. Create the form is following:

using System.Data.OleDb;
------------------------------------OleDbConnection oracon.sqlcon;
under Button1 Click:
--------------------------------------------------------- oracon=new OleDbConnection(
Provider=Msdaora;User Id=Scott; Password=tiger);
oracon.Open();
MessageBox.Show(oracon.State.ToString());
oracon.Close();
MessageBox.Show(oracon.State.ToString());
under Button2 Click:
----------------------------------------------------------- sqlcon=new OleDbConnection();
sqlcon.ConnectionString=Provider=SqlOledb;UserId=Sat;Password=123;Database=Ma
ster; Data Source=Server);
sqlcon.Open();
MessageBox.Show(sqlcon.State.ToString());
sqlcon.Close();
MessageBox.Show(sqlcon.State.ToString());
-----------------------------------------------------------Note:-Where password =123; it is your system password. What is your system password write that only.
And also Data Source=Server. Here also server is your system name. Write that also your system name.
Applying a statement:
In this process we send an instruction to the Data Source specifying the type of activity that has to
be performed using and sql statement like Select, Insert & Delete. We use command class for
applying a statement.
Constructors of the class:Command()
Command(string stmt, Connection con)
Properties of Command: Connection:- To set or get the current Connection object associated with command.
CommandText:- To set or get the current Statement associated with command.
Object of class command can be created as bellow:
Command cmd=new Command();
cmd.Connection=<con>;
cmd.CommandText=<sql stmt>;
(or)
Command cmd=new Command(<sql stmt>, con);
Methods of Command class:
Naresh Tech. Class Notes

Hari

Page112

NagaRaj
.Net -->C#

Sri Sai Ram

ExecuteReader()

DataReader
ExwcuteScalar()

Object
ExecuteNonQuery()

int
Note:- After creating the object of command class we need to call any of these 3 methods to execute the
statement.
How to use above 3 Methods?
Select:Rows & Columns

ExecuteReader
Select:Single value

ExecuteScalar
Insert:No.of rows affected

ExecuteNonQuery
Update:No.of rows affected

ExecuteNonQuery
Delete:No.of rows affected

ExecuteNonQuery
Call ExecuteReader method whenever when we want to execute a select statement that returns
values in the form of rows & columns, which captures the data under DataReader a class modeled
on table.
Call ExecuteScalar method whenever we want to execute a select statement that returns single
value results, which returns data as an object.
Call ExecuteNonQuery method whenever we want to execute Non-Query statement (DML
statements) like Insert, Update & Delete so that the no. of Rows affected is returned as an integer
value.
Note:-the above process of calling an appropriate method in an appropriate case is our third step
executing of the Results.
Accessing Data Form DataReader:
DataReader is a class which is modeled on table. To access the data from DataReader it provides
yours following methods:
1. Read() Boolean
Used moving the record pointer current location to next row, after moving the pointer it
will return the status specifying values were present in the row to which it has moved,
that will be true if present & false if not present.
2. GetValue(int index)
object
Used for picking the field value from the rows to which pointer was pointing by
specifying the column index position.
Note:-We can also access data pointed by the pointer in the form of a single dimensional array also, either
by specifying column index position or name, as following:
<dr>[index]

object
<dr>[colname]

object
3. GetName(int index)
String
Returns name of the Column for specified index.
*** END OF THE DAY ***
Dt:-12-04-2010
Form2.cs ---------------(Design)

Naresh Tech. Class Notes

Hari

Page113

NagaRaj
.Net -->C#

Sri Sai Ram

Code:-using System.Data.Oledb;
--------------------------------Declaration:
OleDbConnection com;
Note:- Form2:Form--:Declaration
OleDbCommand cmd;
OleDbDataReader dr;
--------------------------------Under Form Load:
con=new OleDbConnection(
Provider=Msdaora;User Id=Scott;Password=tiger);
cmd=new OleDbCommand(
Select Deptno, Dname, Loc Form Dept,con);
Con.Open();
dr=cmd.ExecuteReader();
label1.Text=dr.GetName(0);
label2.Text=dr.GetName(1);
label3.Text=dr.GetName(3);
ShowData();
---------------------------------------private void ShowData()
{
if(dr.Read())
{
textBox1.Text=drGetValue(0).ToString();
textBox2.Text=dr[1].ToString();
textBox3.Text=dr[Loc].ToString();
}
else
MessageBox.Show(Last Record);
}
-----------------------------------------------Under Next Button:
ShowData();
---------------------------------------------Under Close Button:
if(con.State==ConnectionState.Open)
con.Close();
this.Close();
------------------------------------------------------------------------------------------*** END OF THE DAY ***
Dt:-13-04-2010
Note:1. Select Deptno, Dname, Loc From Dept
2. Select Max(Dept No)+10 From Dept
Inrest stmt
Update stmt
Delete stmt
3. salstr=insert into Dept(Deptno, Dname, Loc)
Value(+textBox1.Text+,+textBox2.Text+,+textBox3.Text+);
4. Insert into Dept(Deptno, Dname, Loc)
Value(textBox1.Text,textBox2.Text,textBox3.Text);
5. Insert into Dept(Deptno, Dname, Loc)Value(50,Research,Hyderabad)
Naresh Tech. Class Notes

Hari

Page114

NagaRaj
.Net -->C#

Sri Sai Ram

Update: update Dept SetDname=Marketing where Deptno=50


sqlstr=Update Dept Set Dname=+textBox2.Text+,Loc=+textBox3.Text+
Form3: (Design)

Code:- Form3.cs:-using System.DataOleDb;


-----------------------Declarations:
OleDbConnection con;
OleDbCommand cmd;
OleDbDataReader dr;
------------------------------------------------Under Form Load:
con=new OleDbConnection("Provider=Msdaora;User Id=Scott;Password=tiger");
cmd=new OleDbCommand();
cmd.Connection=con;
LoadData();
--------------------------------private void LoadData()
{
sqlstr="Select Deptno,Dname,Loc From Dept";
SetStmt();
dr=cmd.ExecuteReader();
ShowData();
}
--------------------------------------private void SetStmt()
{
if(con.State==ConnectionState.Open)
con.Close();
cmd.CommandText=sqlstr;
con.Open();
}
--------------------------------------private void ShowData()
{
if(dr.Read())
Naresh Tech. Class Notes

Hari

Page115

NagaRaj
.Net -->C#

Sri Sai Ram


{
textBox1.Text=dr[0].ToString();
textBox2.Text=dr[1].ToString();
textBox3.Text=dr[2].ToString();
}
else
MessageBox.Show("Last Record");
}
---------------------------------------Under Next Button:
ShowData();
------------------------------Under New Button:
textBox1.Text=textBox2.Text=textBox3.Text="";
sqlstr="Select Max(Deptno)+10 From Dept";
SetStmt();
textBox1.Text=cmd.ExecuteScalar().ToString();
textBox2.Focus();
--------------------------------------------------------------private void ExecuteDML()
{
DialogResult d=MessageBox.Show(sqlstr+"
\n\n Do you wish to execute the stmt?",
"Confirm Sql",MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if(d=DialogResult.Yes)
{
SetStmt();
int count=cmd.ExecuteNonQuery();
if(count>0)
MessageBox.Show("Statement Executed");
else
MessageBox.Show("statement Failed");
LoadData();
}
}
----------------------------------------------Under Insert Button:
sqlstr="Insert into Dept(Deptno, Dname,Loc)
Values("+textBox1.Text+",'"+textBox2.Tet+"','"+textBox3.Text+"')";
ExecuteDML();
------------------------------------------------Under Update Button:
sqlstr="Update Dept Set Dname='"+textBox2.Text+"',Loc='"
+textBox3.Text+"'where Deptno="+textBox1.Text;
ExecuteDML();
----------------------------------------------------

Naresh Tech. Class Notes

Hari

Page116

NagaRaj
.Net -->C#

Sri Sai Ram

Under Delete Button:


sqlstr="Delete From Dept where Deptno="+textBox1.Text;
ExecuteDML();
---------------------------------------------------Under Close Button:
if(con.State !=ConnectionState.Closed)
con.Close();
this.Close();
---------------------------------------------------------------------------------------------------------------------------------------------------------------Working with SQL Server:
Sql server is a collection of databases where a database is again collection of varies objects like
tables,views, properties etc...User under sql server can have 1 or more Databases of their own, so while
connecting with SQL Server form .Net application with in the connection String we need to specify the
name of databasewe want to connect either by using database or initial catalog attributes.

*** END OF THE DAY ***

Naresh Tech. Class Notes

Hari

Page117

NagaRaj
.Net -->C#

Sri Sai Ram

Dt:-14-04-2010
SQL Server provides 2 diff.nodes of authentication.
1. Windows Authentication.
2. SQL Server Authentication.
- In when a user connects through a window user accounts SQL server validates the account name
& password using the windows principal taken in the Operating System. This means the user
identify is conform by windows. SQL Serverdoesn't asked for the password &doesnt perform the
identify validation.
- When using sql server authentication, logins are created in sql server that are not based on
windows user accounts. Both the user name & password created by using sql server & stored in
the server. Users connecting using sql server Authentication must provide their credentials
(login&password) every time that they connect.
- If we want to connect from a .Net application using windows authentication mode under the
connection string in the place of user & password specify Trusted_Connction=True.
Connection String for SQL Server Authentication:
Provider=SqlOledb;User Id=Sa;Password=<pwd>;Database=<dname>[
;Data Source=<Server>]
Connection String for Windows Authentication:
Provider=SqlOledb;Trusted_Connection=true;Database=<dname>[
;Data Source=<Server>]
Note:- integrate Security=true & Trusted_Connection ------Both are same.
Process of a table in SQL Server: Goto start Menu Programs Ms SQL Server SQL Server Management Studio click on
it to Open & provide the Authentication Details to Login:
Once the studio is open in the left land side it open a window object Explore (F8). In that Right
Click node databases & select new database that open a window prompting for the name of the
database.
Enter the name As Csharp7 click OK.
Which adds the database under databases node. Explained the database we have to created Right
Click on node tables & select new table. Which will prompt for column name & data types enter
the following:
Sno
Int
Sname
Varchar
Class
Int
Fees
Money
Photo
Image
Status
bit
Note: Select status column & go in to column properties in the button. In that set the default value or
Binding property as one. Which takes default value as for status as true.
Click on save button on top, specified the name as students & click OK.
Know Right Click created & select open table which open a window under it enter the data we
want ignoring photo & status.
Connecting with SQL Server form .Net Application:
We can connect with SQL Server either by using SQL Client or Oledb classes where SQL client
given better performance the Oledb.
Note:- If using SQL Connection or Oracle Connection classes under connection string we dont
required to specified. Provider attribute as these classes were designed specific for the Database.
Naresh Tech. Class Notes

Hari

Page118

NagaRaj
.Net -->C#

Sri Sai Ram

Code:using System.DataOleDb;
-----------------------Declarations:
SqlConnection con;
SqlCommand cmd;
SqlDataReader dr;
------------------------------------------------Under Form Load:
con=new SqlConnection(User Id=Sa;password=123;Database=Csharp7);
con=new SqlCommanand(Select Sno,Sname,Class,Fees From Students,con);
con.Open();
dr=cmd.ExecuteReader();
label1.Text=dr.GetName(0);
label2.Text=dr.GetName(1);
label3.Text=dr.GetName(2);
label4.Text=dr.GetName(3);
ShowData();
---------------------------------------------------private void ShowData()
{
if(dr.Read())
{
textBox1.Text=dr.GetName(0);
textBox2.Text=dr.GetName(1);
textBox3.Text=dr.GetName(2);
textBox4.Text=dr.GetName(3);
}
MessageBox.Show(Last Record);
}
-------------------------------------------------Under Next Button:
ShowData();
------------------------------------------------Note:-write the code under New, Insert, Update & Delete buttons to perform dml
operations on the table.
-----------------------------------------------------------------------------Under Close Button:
if(con.State==Connection.State.Open)
Naresh Tech. Class Notes

Hari

Page119

NagaRaj
.Net -->C#

Sri Sai Ram


con.Close();
this.Close();
-------------------------------------------------------------------------------------------------------------------------------------------------------------

Data Reader: It was class modificationtable that can be used for holding data on click machine.
Features of Data Reader:1. Faster access to data from the data source as it was connection Oriented.
2. It can hold multiple tables as a time, to multiple tables we need to pass multiple select
statements as arguments to command separated by a semi-colon.
Ex:-Command cmd=new Command(Select*from Students;Select*From Teachers,con);
DataReader dr=cmd.ExecuteReader();
Note:-use the next Result() method on dataReader object to navigate from current table to next table.
DrawBacks of DataReader:1. It was designed in connection oriented architecture, which requires a permanent connection
with data source to access the data. If the connection was closed we cannot access the data,
which will be a burden on data servers when multiple clients were accessing data form it at
the same time.
2. It provides only forward navigation. i.e., allows going either to next record or next table but
not to previous record or table.
3. It was a read only object which will not allow any changes to data present in it.
*** END OF THE DAY ***

Dt:-15-04-2010
DataSet:-Its a class used for holding & managing data on client Machines apart from DataReader. It was
present under System.Data namespace.
Features of DataSet:
1. Its also capable of holding multiple tables.
2. It was designed on dis-connected architecture which doesnt require any permanent
connection with data source for holding the data.
3. It provides scrollable navigation which allows moving in any direction.
4. It was Updatable, i.e., changes can be performed the data present in it.
Using DataSets:
The class which is responsible for loading of data into DataReader from DataSource is command,
in the same way DataAdapter class is used for communication between DataSource & DataSet.
DataReader
<-Command->
DataSource
DataSet
<->DataAdapter<->
DataSource
Constructors for Adapter:
DataAdapter(string stmt, Connection con)
DataAdapter(Command cmd)
Eg:- DataAdapter da=new DataAdapter(<Sql Stmt>, con);
Methods of DataAdapter:
Naresh Tech. Class Notes

Hari

Page120

NagaRaj
.Net -->C#
-

Sri Sai Ram

Fill(DataSet ds, string tname)


Update(DataSet ds, string tname)
Fill is to load data from DataSource to DataSet.
Update is to transfer changes mode on data from DataSet to DataSource.
DataAdapter was internally collection of 4 commands:
a. Select Command
b. Insert Command
c. Update Command
d. Delete Command
When we Fill method on Adapter following thingstakes place:
i.
Opens a Connection with the DataSource.
ii.
Execute the select command under it & loads data from table to DataSet.
iii.
Closes the connection.
As we are aware DataSet is Updatable, once the data is loaded in to it, we can make changes on
data like adding or modifying or deleting.
After performing changes to DataSet if we want to send those changes back to the data Source we
need to call update method on Adapter, which performs the following:

i.
ii.

Re-Opens a Connection with the DataSource.


Changes which are made on DataSet will be sent back to table, where in this process it
will make use of Insert, Update & Delete Commands of Adapter.
iii.
Closes the Connection.
Note:-DataReader is a Pointer based Access.
DataSet is an Index based Access.
Accessing Data from DataSet: -

DataSet is a Collection of tables where each table is represented as a class DataTable &
identified by its index position or name.
DataSet:- Collection of Tables(Data Table)
<dataset>.Tables[index] or Tables[name]
ds.Tables[0] or ds.Tables[students]
-

Every data table is again collection of Rows & Columns where each Row is represented as a
class DataRow adds identified by its index position. Each column is represented as a class
DataColumn & identified its index position or name.
DataTable:
- Collection of Rows(DataRow)
<datatable>.Rows[index]
Naresh Tech. Class Notes

Hari

Page121

NagaRaj
.Net -->C#

Sri Sai Ram

ds.Tables[0].Rows[0]
- Collection of columns(DataColumn)
<datatable>.Columns[index] or Columns[name]
ds.Table[0].Columns[0] or ds.Tables[0].Columns[Sno]
Referring to a cell under DataTable:
<datatable>.Rows[row][col]
ds.Tables[0].Rows[0][0] or ds.Tables[0].Rows[0][Sno]

*** END OF THE DAY ***

Dt:-16-04-2010
Note:- Add a new windowForm From5.cs
DBoperations Right Click Add a new WindowForm Form5.cs
DBoperations Right Click Add Reference .Net MicroSoft.Visual Basic
Form5.cs(Design):

Naresh Tech. Class Notes

Hari

Page122

NagaRaj
.Net -->C#

Sri Sai Ram

Working with DataSet: Add a reference of Microsoft.VisualBasic from .Net tab of add reference window & write
following code under the form:
using System.Data.SqlClinet;
using Microsoft.VisualBasic;
---------------------------------------Declarations:
SqlConnection con;
SqlDataAdapter da;
SqlCommandBuilder cd;
DataSet ds;
int rno=0;
-------------------------------------------Under Form Load:
con=new SqlConnection("User Id=Sa;Password=123;Database=Csharp7");
da=new SqlDataAdapter("Select Sno,Sname,Class,Fees From Students",con);
ds=new DataSet();
da.MissingSchemaAction=MissingSchemaAction.AddWithKey;
da.Fill(ds,"Students");
ShowData();
--------------------------------------------------------------------------------private void ShowData()
{
textBox1.Text=ds.Tables[0].Rows[rno][0].ToString();
textBox2.Text=ds.Tables[0].Rows[rno][1].ToString();
textBox3.Text=ds.Tables[0].Rows[rno][2].ToString();
textBox4.Text=ds.Tables[0].Rows[rno][3].ToString();
}
----------------------------------------------------------------------Under First Button:
rno=0;
ShowData();
Under Prev Button:
if(rno>0)
{
rno-=1;
ShowData();
Naresh Tech. Class Notes

Hari

Page123

NagaRaj
.Net -->C#

Sri Sai Ram

}
else
MessageBox.Show("First Record");
Under Next Button:
if(rno<ds.Tables[0].Rows.Count -1)
{
rno +=1;
Show.Data();
}
else
MessageBox.Show("Last Record");
Under Last Button:
rno=ds.Tables[0].Rows.Count -1;
ShowData();
Under New Button:
textBox1.Text=textBox2.Text=textBox3.Text=textBox4.Text="";
textBox1.ReadOnly=false;
textBox1.Focus();
Adding a new record under DataTable:To add a record to DataTable adopt the following process:
i). Create an empty row by calling the method NewRow() on DataTable.
ii). Assign values to the new row by treating it as a single dimensional array.
iii). Call the Add method on DataTable and add the row to RowsCollection.
Under Insert Button:
DataRow dr=ds.Tables[0].NewRow();
dr[0]=textBox1.Text;
dr[1]=textBox2.Text;
dr[2]=textBox3.Text;
dr[3]=textBox4.Text;
ds.Tables[0].Rows.Add(dr);
MessageBox.Show("Record Added");
textBox1.ReadOnly=true;
button1.PerformClick();//Executes the code click of a button(button1 is First Button);
Updating a record under DataTable:To update a record under data table re-assign modified values back
to the row under data table,so that the old values changes to new.
Under Update Button:
ds.Tables[0].Rows[rno][1]=textBox2.Text;
ds.Tables[0].Rows[rno][2]=textBox3.Text;
ds.Tables[0].Rows[rno][3]=textBox4.Text;
MessageBox.Show("Record Modified");
Deleting a record under Data Table: To delete a record under data table call Delete method on data Row
Collection.
Under Delete Button:
ds.Tables[0].Rows[rno].Delete();
MessageBox.Show("Record Deleted");
button1.PerformClick();
Saving the changes made on DataSet to DB:
Naresh Tech. Class Notes

Hari

Page124

NagaRaj
.Net -->C#

Sri Sai Ram

If we want to save changes made on a DataSet back to the DB we need to call Update method on
DataAdapter. If Update method has to work DataAdapter first requires 3 commands under it. i.e.,
Insert, Update & Delete.
These 3 commands have to be written by the programmers manually or generate them the help of
commandBuilder class.CommandBuilder class if given with an Adapter that contains as
SelectCommand in it will write the remaining 3 commands for Adapter.
Constructor:CommandBuilder(DataAdapter da)
Note:- CommandBuilder can generate us update & delete commands for a given selectcommand only
if the table contains Primary Key Constraint on it.
To add a Primary Key Constraint on our Student table open Sql Server Management Studio
go to Csharp7 database right click on Student table select Modify , that opens a window
showing list of columns right click on Son column & choose the option Set as Primary Key
click on save button and close the studio.

Under Save Button:


cb=new SqlCommandBuilder(da);
da.Update(ds,Students);
MessageBox.Show(Data saved to Database);
-----------------------------------------------------------------Searching the data Present under DataTable:To search record present under DataTable we can make
use of Find method of DataRow class which can data on Primary Key column of table and returns a
Row.
Find(object key) DataRow
Note:- If the Find method has to work we need to first load the Primary Key information of table into
dataset by setting the property value as AddWithKey for MissingSchemaAction of Adapter.
-----------------------------------------------------------------------------------------------------Under Search Button:
int sno =int.Parse(Interaction.InputBox(Enter Sno to search,Search,,100,100));
DataRow dr=ds.Tables[0].Rows.Find(sno);
if(dr !=null)
{
textBox1.Text=dr[0].ToString();
textBox2.Text=dr[1].ToString();
textBox3.Text=dr[2].ToString();
textBox4.Text=dr[3].ToString();
}
else
MessageBox.Show(Invalid Student No:);
--------------------------------------------------------------Under Close Button:
this.Close();
*** END OF THE DAY ***
Naresh Tech. Class Notes

Hari

Page125

NagaRaj
.Net -->C#

Sri Sai Ram

Dt:-17-04-2010
DataGridView: Its a control which can display data in the from table. i.e., Rows & Columns. We can directly
bind a DataTable of to the control by using its DataSource property.
Syntax: - DataSource = <datatable>
Eg: - dataGridView1.DataSource=ds.Tables[0] ;
DataGridView control is updatable which will allows us to add, modify or delete records. The
specialty of this control was only changes perform of the data on the control reflex directly into
the data table to it was bound.

Form6.cs(Design):-

Code:using System.Data.SqlClient;
------------------------------------Declarations:
SqlConnection con;
SqlDataAdapter da;
SqlCommandBuilder cb;
DataSet ds;
--------------------------------------Under Form Load:
con=new SqlConnecton(User Id=Sa;Password=123;Database=Csharp7);
da=new SqlDataAdapter(Select Sno,Sname,Class,Fees From Students,con);
cb=new SqlCommandBuilder(da);
ds=new DataSet();
da.Fill(ds,Students);
dataGridView1.DataSource=ds.Tables[0];
----------------------------------------------------Under Save Button:
da.Update(ds, Students);
MessageBox.Show(Data Saved to database);
------------------------------------------------Under Close Button:
this.Close();

Naresh Tech. Class Notes

Hari

Page126

NagaRaj
.Net -->C#

Sri Sai Ram

Form7.cs

DBOperations RightClick Add WindowForm Form7.cs created


In form7 design Drab & Drop DataGridView Command in the design page, on that right
click view source.
DBOperations Right Click Add Reference OrcleClient.
Connecting with Oracle using OracleClient: Visual Studio doesnt provide default reference to assembly System.Data.OrcleClient, so we need
to first add the reference & then use the classes of it.
Loading Multiple tables into DataSet: If we want to load multiple tables into a dataset we have 2 diff. approaches:
1. Using a single DataAdapter we can load only no. of tables into a dataset by changing the
select command after calling Fill.
Note:- In this approach we cannot perform changes on data of all the tables & send back to
db, because an adapter can hold all the 4 commands only for a single table. That is a last
table.
Ex: da = new DataAdapter(Select* Form Dept, con);
da=Fill(ds,Dept);
da.SelectCommand.CommandText=Select* Form Emp;
da.Fill(ds,Emp);
--------------Load multiple tables in the same approach------------------2. Using a separate DataAdapter for each table multiple tables, can be loaded into the dataset, in
this case we can perform changes on Data of any table & send back on the DB.
Note:-In this approach each table can be loaded from a different data source also.

*** END OF THE DAY ***

Dt:-19-04-2010
DataView: Its a class used for filtering of data from a Data Table, filtering of data means picking out the
required data from the available, this can be done in 2 ways:
1. Using Find Method.
2. Using Data View Class
Find method can be used for filtering of the data on Primary Key column of the table
which returns a single record.
Naresh Tech. Class Notes

Hari

Page127

NagaRaj
.Net -->C#

Sri Sai Ram

DataView class can be used for filtering the data basing on any column of the table
which can return multiple records at a time.
DataView: - it is a class under ADO.NET which is modeled on database object View. Is an act as
mediator between Data Provider & Data Consumer, in this process it filters the data provider & supplies
to the consumer.
Using DataView:
Step 1: Create an object of class DataView by calling DefaultView property on the DataTable which will
create & return an object of DataView with same structure of the table.
DataTable:
DefaultView DataView
e.g.:- DataView dv=ds.Tables[Emp].DefaultView;
Step2: Specify a condition for filter by making use of the RowFilter property of DataView class.
DataView:
RowFilter =<Condition for Filter>
e.g.:
dv.RowFilter=Job=Manager;
dv.RowFilter=Sal>2500;
dv.RowFilter=Job=Manager And Sal>2500;
dv.RowFilter=Job=Manager Or Sal>2500;
Form7.cs
Add a new form and place a ComboBox in the top center and place a DataGirdView control
below and write the following code:
using System.Data.OracleClient;
--------------------------------------------Declaration:
OracleConnection con;
OracleDataAdapter da;
DataSet ds;
bool flag=false;
-------------------------------------------Under Form Load:
con=new OracleConnection(User Id=Scott;Password=tiger);
ds=new DataSet();
da=new OracleDataAdapter(Select * From Dept,con);
da.Fill(ds,Dept);
da.SelectCommand.CommandText=Select * From Emp;
da.Fill(ds,Emp);
comboBox1.DataSource=ds.Tables[Dept];
comboBox1.DisplayMember=Dname;
comboBox1.ValueMenber=Deptno;
dataGridView1.DataSource=ds.Tables[0];
-----------------------------------------------------------Under ComboBox SelectedIndexChanged:
if(flag){
DataView dv=ds.Tables[Emp].DefaultView;
dv.RowFilter=Deptno=+ comboBox1.SelectedValue;
}
ComboBox Controls allows bind atable to with using its DataSource property. But can display
only a single column. Which has to be specifying using its display member property. And access
that value using the text property. We can also bind one more Column by using itsvalues member
property that not visible can be access in the code selected value property.
DataRelation:
It is a class which is used for establishing parent child relationships between tables under a
dataset. Under dbs also we have an option for establishing parent child relationships between
tables with the help of foreign Key constraint.
Naresh Tech. Class Notes

Hari

Page128

NagaRaj
.Net -->C#

Sri Sai Ram

To use foreign Key constraint we need a parent table that contains master data & child table that
contains detailed data corresponding to master data. Parent tables should contain a Reference Key
Column with a Primary Key or Unique Key Constraints imposed on it, and child table should
contain a Foreign Key Column with Foreign Key Constraint imposed on it which refers into the
values of Reference Key Column.
Once relationship was established between tables we cannot put a value in foreign key column if
the given value is not present in reference key column. If we want to establish same type of
relations between tables of a dataset it can be done with the help of DataRelation class.
DataRelation(string name, DataColumn RKcol, DataColumn FKcol)
After creating object of DataRelation it has to be added explicitly to the DataSet under which
tables were present using Relations. Add method of DataSet.
e.g.:<dataset>.Relations.Add(DataRelation dr)
Now for deleting or updating reference key values in parent table there were some rules that
comes into picture separately for delete & update known as DeleteRules & UpdateRules, those
were:
1. None: - Cant delete or update reference key value of parent table when corresponding
child records exists in child table, this was applied by default under DBs.
2. Cascade:- In this case we can delete or update reference key values of parent table, but
the corresponding child records in child table will also be deleted or updated, this is by
default applied in case of DataSets.
3. SetNull: - In this case also we can delete or update reference key values of parent but the
corresponding child records foreign key value changes to Null.
4. SetDefault: - This is same as SetNull, but in this case the corresponding child records
foreign key value changes to default value of the column.
Note:- We need to apply required rule for delete or update on DataRelation using following
Statements:
<datarelation>.ChildKeyConstraint.DeleteRule=Rule.<value>;
<datarelation>.ChildKeyConstraint.UpdateRule=Rule.<value>;
To use SetDefault rule first we need to set a default value for foreign column using the following
statement:
<datatable>.Columns[name].DefaultValue=<value>
--------------------------------------------------------------------------------------------------------- Form 8.cs
Add a new form and place a SplitContainer on it, which with 2 panels, place a DataGridView
control on each panel and set their Dock Property as fill and then write the following code:
using System.Data.OracleClient;
----------------------------------------Declarations:
OracleConnection con;
OracleDataAdapter da1, da2;
DataSet ds;
DataRelation dr;
-------------------------------------------------Under Form Load:
con= new OracleConnection(User Id=Scott;Password=tiger);
da1=new OracleDataAdapter(Select * From Dept, con);
da2=new OracleDataAdapter(Select * From Emp, con);
ds=new DataSet();
da1.Fill(ds,Dept);
da2.Fill(ds,Emp);
Naresh Tech. Class Notes

Hari

Page129

NagaRaj
.Net -->C#

Sri Sai Ram

dr=newDataRelation(EmpDept,ds.Table[0].Columns[Deptno],ds.Tables[1].Columns[Deptno
]);
ds.Relations.Add(dr);
dr.ChildKeyConstraint.DeleteRule=Rule.None;
dr.ChildKeyConstraint.UpdateRule=Rule.None;
dataGridView1.DataSource=ds.Tables[Dept];
dataGridView2.DataSource=ds.Tables[Emp];
------------------------------------------------------------------------Note:-Use the following statement if required for setting a default value to foreign key column:
ds.Tables[Emp].Columns[Deptno].DefaultValue=40;
Dock Property: Its a property available to all the controls which decides the location where control sits on the
container as well as the size of the control.
It can be set with any of the following values:
1. None: - In this case he size & location of the control will be same as what we
have specified while creating the control, which will not change in the runtime.
2. Left, Right, Top & Bottom:- In this case the control gets placed on any of the
4 chosen options with in the containers & also adjusts it self according to the
size of Container.
3. Fill: - In this case the control occupies the complete available space of the
container.
Split Container: Its a container with 2 panels init, where the sizes of panel can be adjusted in runtime. The 2
panels by default sits in vertical orientation which can be changed horizontal using the orientation
property.

*** END OF THE DAY ***


Dt:-20-04-2010
Delete Rules:- None[Default for every db]
- Cascade[Default for dataset]
- SetNull
- SetDefault
Drawback of a DataSet: As we are a dataset is a local copy of data which allows changes, but modification on a
local copy may lead to concurrency problems, i.e., change performed at location may not
be reflecting to other immediately.
- Conclusion: Use data sets only for retrieving of data but not for performing manipulations, as local
copy changes are not advised in app development.
*** END OF THE DAY ***
Naresh Tech. Class Notes

Hari

Page130

NagaRaj
.Net -->C#

Sri Sai Ram

Dt:-21-04-2010
Connecting To Stored Procedure:SQL Server2005 connection:-

After Connecting to the SQL Server Authentication:-

Using Visual Studio: Stored Procedure we also creating using Visual StudioFollowing ways:

Naresh Tech. Class Notes

Hari

Page131

NagaRaj
.Net -->C#

Sri Sai Ram

Stored Procedures:-

When ever we want to interact a database from an application we use sql statements. These
statements when used with in an application has a problem. i.e., when we run the application
statements will be sent to db for execution where the statements requires to be parsed (compile)
and then execute. The process of parsing and execution takes place each time we run the
application, which increases work load on db server so performance of our application decreases.
To over come the above drawback write sql statements directly under db only, with in an object
known as Stored Procedure and call them for execution. As a SP is a pre compiled block of code
which is ready for execution will directly execute the statements with out parsing each time, so
that DB performance will not be de grated.
Syntax to define a Stored Procedure:
CreateProcedure<Name>[(<param1>[out]<dtype>[Output],,<paramn>[out]<dtype>[Output])]
As
Begin
<Stmts>
Naresh Tech. Class Notes

Hari

Page132

NagaRaj
.Net -->C#

Sri Sai Ram

End

A Stored Procedure is similar to a method in our language, which is a collection of Sql


Statements.
As parameters can be passed to methods, they can also be passed to Stored Procedures,
which is optional. If we want to pass a parameter to Stored Procedure under Sql Server
before parameter name use the special character @.
Oracle: Create Procedure Add (x number, y number)
Sql Server: Create Procedure Add (@x int, @y int)
As Stored Procedure can also return values, to return a value we use Out or Output
clause, Out in oracle and Output in Sql Server.
Ex:Csharp:
Public void Test(int x, ref int y)
Oracle:
Create Procedure Text (x number, y out number)
Sql Server:
Create Procedure Text (@x int, @y int output)
Creating a Stored Procedure:
We can create a SP on Sql Server either by using Sql Management Studio or from Visual
Studio .Net also.
To create a SP from Visual Studio first we need to configure our db CSharp under the
Server Explorer, to do this go to View menu, select Server Explorer which gets launched
on LHS of the studio. To configure it right click on the node Data Connections & select
Add Connection, which opens a window asking to choose a Data Source select MS
Sql Server and click ok, which opens Add Connectionwindow, under it provide the
following details:
1. Server Name:<name of the Server machine>
2. Authentication: Windows or Sql Server, if Sql provide User Name & Password.
3. Database:Csharp
Click on the OK button which adds the DB under Server Explorer, expand it, right click
on the node Stored Procedures & select Add New Stored Procedure which opens a
window, write the following code it:
Create Procedure Select_Students
As
Begin
Select Sno, Sname, Class, Fees From Students
End
Click on save button on top the studio which creates the SP on Database Server.
Calling a SP from .Net Application:
Step-1:Command class is responsible in calling of a SP, so first we need to create the object of class
command by passing SP name as an argument to it.
Ex:- Command cmd=new Command(Select_Students, con);
Step-2:Change CommandType property of Command as StoredProcedure, because by default its
configured to call Sql statements after changing the property it can call SPs.
Ex:- cmd.CommandType=CommandType.StoredProcedure;
Step-3:It the SP has any parameters, pass the values to parameters option of Command or else it was
optional.

Naresh Tech. Class Notes

Hari

Page133

NagaRaj
.Net -->C#

Sri Sai Ram

Step-4: If the procedure contains insert, update or delete statements in it, call ExecuteNonQuery method
on method to execute the SP. If the SP contains select statement in it and if we want to load the data into a
DataSet, create an object of DataAdapter by passing the object of command as an argument and then call
Fill() Method, so that command executes the SP and Adapter loads data into the dataset.
Add a New Windows Form9.cs:- Open a new form place a DataGridView Control on it and write following code:
using System.Data.SqlClient;
--------------------------------------Declarations:
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
------------------------------Under Form Load:
con=new SqlConnection(User Id=Sa;Password=123;Database=Csharp);
cmd=new SqlCommand(Select_Students, con);
cmd.CommandType=CommandType.StoredProcedure;
da=new SqlDataAdapter(cmd);
ds=new DataSet();
da.Fill(ds,Students);
dataGridView1.DataSource=ds.Tables[0];
Form9.cs(Design):

Using SP to perform Select & DML Operations:


Add a New Windows Form10.cs:-create a form as below & place an OpenFileDialog control on
it.
Design:-

Naresh Tech. Class Notes

Hari

Page134

NagaRaj
.Net -->C#

Sri Sai Ram

PictureBox Control:
Its a control used for displayed image with an application, to bind an image to the control
we can use any of the following option.
ImageLocation=<path of the image>
Image=Image.FromFile(<path of the image>)
Image=Image.FromStream()
we can control the image size under the PictureBox using a enumerative property on the
PictureBox.
Drap & Drop on button goto properties Text=loadimage.
Dialog Controls:
These are controls from which the user can select a designed value we were provide with 5 dialog
controls under .Net language those are,
1. ColorDialog
2. FontDialog
3. OpenFileDialog
4. SaveFileDialog
5. FolderBrowserDialog
To consume a dialog controls first add it to the form and then column a ShowDialog method to
make it visible.
A Dialog control never perform any action, it only responsible in returning back the value chosen
by the User. That to be explicitly capture using the billow properties.
ColorDialog
Color
FontDialog
Font
OpenFileDialog
filename
SaveFileDialog
filename
FolderBrowserDialog
Selected path
ToolBox Dialogs
Ex: {
colorDialog1.ShowDialog();
this.BackColor=colorDialog1.Color;
}
{
openDialog1.ShowDialog();
pictureBox1.ImageLocation=openFile
}
*** END OF THE DAY ***
Naresh Tech. Class Notes

Hari

Page135

NagaRaj
.Net -->C#

Sri Sai Ram

Dt:-22-04-2010

Step-1: Command:
Command cmd=new Command(Select_Students,con);
Execute any Sql Statement
Invoke a SP
Retrive data from a table
Step-2: Command:
cmd.CommandType=CommandType.StoreProcedure;
Text[d]
StoredProcedure
TableDirect

Note: Goto SqlDatabase Server.Csharp7.dbo Stored Procedure Select_Student.


Goto SqlDatabase Server.Csharp7.dbo Stored Procedure (Right Click) New Stored
Procedure (Insert_Student).
Define the following SP first:
Alter Procedure Select_Students(@Sno Int=Null)
As
Begin
If @Sno Is Null
Select Sno, Sname, Class, Fees From Students Where Stutas=1
Else
Select Sname, Class, Fees, Photo From Students Where Sno = @Sno And Status =1
End
------------------------------------------------------------------------------------------------------Create Procedure Ins_Upd_Students (@Sno Int, @Sname Varchar(50), @Class Int,
@Fees Money, @Photo Image)
As
Begin
If Not Exists (Select Sno From Where Sno = @Sno and Status = 1)
Insert Into Students (Sno, Sname, Class, Fees, Photo) Values(@Sno, @Sname, @Class,
@Fees, @Photo)
Update Students Set Sname=@Sname,Class=@Class,Fees=@Fees,Photo=@Photo
Where Sno=@Sno
End
------------------------------------------------------------------------------------------------------Create Procedure Delete_Students (@Sno Int)
As
Update Students Set States=0 Where Sno=@Sno
------------------------------------------------------------------------------------------------------Code Under the Form:using System.IO;
using System.Data.SqlClient;
using System.Drawing.Image;
------------------------------------------------------------------------------------------------------Naresh Tech. Class Notes

Hari

Page136

NagaRaj
.Net -->C#

Sri Sai Ram

Declarations:
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
MemeryStream ms;
------------------------------------------------------------------------------------------------------Under Form Load:
con=new SqlConnection(User Id=Sa;Password=123;Database=Csharp);
cmd=new SqlCommand();
cmd.Connection=con;
cmd.CommandType=CommandType.StoredProcedure;
------------------------------------------------------------------------------------------------------Under Get Button:
cmd.Parameters.Clear();
cmd.CommandText=Select_Students;
cmd.Parameters.AddWithValue(@Sno, textBox1.Text);
da=new SqlDataAdapter(cmd);
ds=new DataSet();
da.Fill(ds,Students);
if(ds.Tables[0].Rows.Count>0)
{
textBox2.Text=ds.Tables[0].Rows[0][0].ToString();
textBox3.Text=ds.Tables[0].Rows[0][1].ToString();
textBox4.Text=ds.Tables[0].Rows[0][2].ToString();
//Converting byte[] into Image
if(ds.Tables[0].Rows[0][3]!=System.DBNull.Value)
{
byte[]data=(byte[]) ds.Tables[0].Rows[0][3];
ms=new MemoryStream()data;
pictureBox1.Image=Image.FromStream(ms);
}
else
pictureBox1.Image=null;
}
else
MessageBox.Show(Record does not exists);
---------------------------------------------------------------------------------------------------------Under Clear Button:
textBox1.Text=textBox2.Text=textBox3.Text=textBox4.Text=;
pictureBox1.Image=null;
textbox.Focus();
-------------------------------------------------------------------------------------------------------Under Insert Button:
try {
cmd.Parameters.Clear();
cmd.CommandText=Ins_Upd_Students;
Naresh Tech. Class Notes

Hari

Page137

NagaRaj
.Net -->C#

Sri Sai Ram

cmd.Parameters.AddWithValue(@Sno, textBox1.Text);
cmd.Parameters.AddWithValue(@Sname, textBox2.Text);
cmd.Parameters.AddWithValue(@Class, textBox3.Text);
cmd.Parameters.AddWithValue(@Fees, textBox4.Text);
//Converting an Image into byte[]
ms=new MemoryStream();
pictureBox1.Image.Save(ms,ImageFormat.Jpeg);
byte[]data=new byte[ms.Length];
ms.Position=0;
ms.Read(data, 0, Convert.ToInt32(ms.Length));
cmd.Parameters.AddWithValue(@Photo,data);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(Executed);
}
catch(Exception ex){
MessageBox.Show(ex.Message);
}
finally{
con.Close();
}
--------------------------------------------------------------------------------------------------------Under Update Button:
button3.PerformClick(); //button3 is Insert button
--------------------------------------------------------------------------------------------------------Under Delete Button:
try
{
cmd.Parameters.Clear();
cmd.CommandText=Delete_Students;
cmd.Parameters.AddWithValue(@Sno, textBox1.Text);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(Executed);
button2.PerformClick(); //button2 is Clear button
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
--------------------------------------------------------------------------------------------------------Under Load Image Button:
openFileDialog1.ShowDialog();
Naresh Tech. Class Notes

Hari

Page138

NagaRaj
.Net -->C#

Sri Sai Ram

pictureBox1.ImageLocation=openFileDialog1.FileName;
------------------------------------------------------------------------------------------------------Storing Images in Database: It is possible to store images, Audios & videos contain on a database server, but only in binary
format. So, your application show first convert them in to binary (byte) And them send in to the
database for storing.
To store binary data we use image or Varbinary data types under SqlServer with a Capacity of 2
GB and Blob data type in case of oracle with a capacity of 4 GB.

Parameter:
It is an object we need to use in our.net app while calling a SP with parameters. If the procedure
has multiple parameters while calling it form our app for each parameter we need to create a
matching parameters i.e., for input matching input and for output matching output parameter.
Output parameters are used by the SP to return a value after its execution where as input
parameter is used for taking a value into the SP for execution.
Every parameter that is created under the app has 5 attributes to it, like Name, Value, SqlDbType,
size & Direction(Input(d) or Output or InputOutput (Only for Oracle)).
Name refers to name of the parameter under SP.
Value refers to the being assigned for parameter in case of input or value we are expecting in case
of output.
SqlDbType refers to type of the parameter in terms of Sql DBs.
Size refers to size of the type under Sql DBs.
Direction specifies whether parameter was input or output or InputOutput.
-----------------------------------------------------------------------------------------------Procedure with input & output parameters:
Create Procedure Add(@x int, @y int, @z output)
As
Begin
Set @z=@x + @y
End
While calling the above procedure from .net application we need to create input & output
parameters by specifying following attributes:
Input
Output
I/P
- Name
Yes
Yes
Yes
- Value
Yes
No
Yes
- SqlDbType
No
Yes
No
- Size
No
Yes [Only for variable length types]
No
- Direction
No
Yes
Yes
----------------------------------------------------------------------------------------------------Naresh Tech. Class Notes

Hari

Page139

NagaRaj
.Net -->C#

Sri Sai Ram

Creating Input parameter under Application:


cmd.Parameters.AddWithValue(pname, pvalue);
Creating Output parameter under Application:
cmd.Parameters.Add(pname, sqldbtype).Direction=ParameterDirection.Output;
cmd.Parameters[pname].Size=<size>; //For Variable length types only
Call ExecuteNonQuery method on command to execute the procedure & then capture
the value as following:
<type><var>=cmd.Parameters[pname].Value;
---------------------------------------------------------------------------------------------------CREATE PROCEDURE Get_SDetails(@Sno, Int, @Sname Varchar(50) Output, @AFees
Money Output)
As
Begin
Declare @Fees Money
Select @Sname=Sname, @Fees = Fees From Students Where Sno = @Sno where
Set (@AFees = @Fees*9) + ((@Fees*3)*0.3)
End
---------------------------------------------------------------------------------------------------------Note:-if a SP is returning any values we need to use ExecuteNonQuery method of call the procedure.
-------------------------------------------------------------------------------------------------------*** END OF THE DAY ***
Dt:-23-04-2010

Form11.cs(Design)

using System.Data.SqlClient;
--------------------------------------------------------------------------------------------------Declarations:
SqlConnection con;
SqlCommand con;
---------------------------------------------------------------------------------------------------Under Form Load:
con =new SqlConnection(User Id=Sa;Password=123;Database=CSharp);
cmd=new SqlCommand(Get_SDetails, con);
cmd.CommandType=CommandType.StoredProcedure;
---------------------------------------------------------------------------------------------------Under Execute:
try
{
Naresh Tech. Class Notes

Hari

Page140

NagaRaj
.Net -->C#

Sri Sai Ram

cmd.Parameters.Clear();
cmd.Parameters.AddWithValue(@Sno,textBox1.Text);
cmd.Parameters.Add(@Sname,SqlDbType.VarChar).Direction=
ParameterDirection.Output;
cmd.Parameters[@Sname].Size=50;
cmd.Parameters.Add (@AFees, SqlDbType.Money).Direction=
ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
textBox2.Text=cmd.Parameters [@Sname].Value.ToString();
textBox3.Text=cmd.Parameters[@AFees].Value.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
-----------------------------------------------------------------------------------------------Under Close Button:
this.Close();
-----------------------------------------------------------------------------------------------*** END OF THE DAY ***
Dt:-24-04-2010
Communication with DataSources using ODBC:- Odbc is a collection of drivers which were part of need to OS but our application. To use them
first we need to configure the required driver to connect with a data source by supplying all the
required data or details using odbc.DataSource Administrator, which will be saved internally
with a name DSN (Data Source Name) which should be given by us.
- After configuring the DSN from our .NET application using odbc classes we need to connect
with the DSN we created which will internally connect with the DataSource.
- In case of oledb providers directly from the application we connect with DataSource, but in case
of odbc, application connects with drivers & they will connect with DataSources.

Naresh Tech. Class Notes

Hari

Page141

NagaRaj
.Net -->C#

Sri Sai Ram

To use odbc classes first we need to configure the odbc drivers installed on the machine with
data source using a DSN(Data Source Name) & them refer to the DSN from our application.
Note:- DSN internally contains info about the driver that has been chosen & details of the DataSource
like user id, password, database, server, path, etcto which we want to connect.
- To create a DSN goto start Menu settings control panel Administrative Tools
DataSources (ODBC), click to open ODBC data source administrator window, in that click on
add button choose a driver for oracle or Sql Server or MS Access or MS Excel etc click
Finish which opens a window in that first give a name to the DSN & then supply the
connection details like user id, password, Database, server, etc..& click finish, which is add the
DSN under ODBC DataSource Administrator window.
- Now from .NET application we can connect with the DSN using odbcconnection class as
following:
OdbcConnection con=new OdbcConnection(DSN=<name of dsn we have created >);
Note:- connecting with dataSources using odbc drivers leads to OS dependency because drivers were not
managed.
------------------------------------------------------------------------------------------------------OdbcConnection con=new OdbcConnection (DSN=<DSN Excel DSN>);
OdbcCommand cmd=new OdbcCommand(Select * From[Emp$], con);
---------------------------------------------------------------------------------------------------------------- Interacting with MS-Excel from .NET Application:
- Excel is a file system which can store data in the form of rows & columns i.e., Table Format.
- An Excel document referred as a Workbook contains work Sheets in it, where work book is
modeled on a database & each sheet can be considered as a Table. The first row of the sheet is
considered as column names of the table.
- To create a Excel document go to Start Menu programs MS Office MS Excel, now in
the document opened under sheet1 enter column names in first row as following:
Empno
Ename
Job
Salary
Location
- Now from the second row enter data as for your requirement.
- Save the worksheet as Emp to do this right click or sheet in the bottom of document and select
rename then give the name, save the document in desired locations as company which take the
default extension as xls.
Eg: - D:\\Csharp7\comapany.xls
- If we want to access an excel document from a .NET application we can use odbc classes, so
first configure the odbc driver for excel, to do this open odbc data source administrator window,
click on add Button, select driver for Microsoft Excel (*.xls)& click finish which opens a
window, under that enter the following details:
1. DataSource Name: ExcelDsn
2. Description: Connects with Excel document.
3. Click on the .xls we have created previously click on OK Button OK Button.

Naresh Tech. Class Notes

Hari

Page142

NagaRaj
.Net -->C#

Sri Sai Ram

Add a new Form12.cs (Design)

Code:
using System.Data.Odbc;
--------------------------------Declaration:
odbcConnection con;
odbcCommand cmd;
odbcDataReader dr;
-----------------------------------------------------------------------------------------------Under Form Load:
con=new odbcConnection(Dsn=ExcelDsn);
cmd=new odbcCommand(Selece *From[Emp$], con);
con.Open();
dr=cmd.executeReader();
label1.Text=dr.GetName(0);
label2.Text=dr.GetName(1);
label3.Text=dr.GetName(2);
label4.Text=dr.GetName(3);
label5.Text=dr.GetName(4);
ShowData();
-------------------------------------------------------------------------------------------------private void ShowString()
{
if(dr.Read())
{
textBox1.Text=dr[0].ToString();
textBox2.Text=dr[1].ToString();
textBox3.Text=dr[2].ToString();
textBox4.Text=dr[3].ToString();
textBox5.Text=dr[4].ToString();
Naresh Tech. Class Notes

Hari

Page143

NagaRaj
.Net -->C#

Sri Sai Ram

}
else
MessageBox.Show(Last Record);
}
----------------------------------------------------------------------------------------------Under Next Button:
ShowData();
-------------------------------------------------------------------------------------------------Under Insert Button:
- Create a table in Sql Server as Emp with same Columns as above, define a SP for insert & insert
each record that comes from Excel document into the table from here.
- ----------------------------------------------------------------------------------------------Under Close Button:
if(con.State != ConnectionState.Closed)
con.Close();
this.Close();
------------------------------------------------------------------------------------------------------ Text documents have formatting Problem. Over come this problem using HTML, it is a
formatting language.
A language is representing in a form of Tag is called as Markup Language.
HTML interpreter is understanding & responsible for HTML.

*** END OF THE DAY ***

Dt:-26-04-2010
XML[eXtensible Markup Language]
It was a language that has been designed to describe the content present under text
documents. So, it was known as describing languages & also platform independent.
Any language that represents data in the form of Tags can be called as Markup. Language &
any thing that gets enclosed under angular braces is a Tag.
HTML & XML are 2 different Markup Languages, where HTML is used for formatting
content of a text document & XML is used for describing content of a text document, so
html formatting & XML was describing language.
The software that understands HTML was HTML interpreter & in case of XML it was XML
parses, both these were part of a Browser.
HTML is an error free language where as xml is not, to create an xml document we need to
satisfy as set of rules that were prescribed by W3C, as following:
1. An XML document has to be saved with .XML extension.
2. An XML document can not be left empty.
3. Data under xml document should be present only under Tags, where every Tag should
have a start & end element.
Eg:<Tag>1</Tag>
<Tagid=1/>
Note:- Tags can also have attributes which were user defined a value to attribute should be
enclosed under double Touts.
Naresh Tech. Class Notes

Hari

Page144

NagaRaj
.Net -->C#

Sri Sai Ram

4. While defining tags start & end tag should match in case.
Ex:- <abc> Hello</abc>
<xyz>How are you</xyz>
5. An XML document can have any one top level elements, but can have multiple child
elements.
Note:- parser under the Brower verifier whether xml document satisfies all predefined
rules or not.
Ex:-SaveAs:- student.xml
<students>
<student>
<sno>1</sno>
<sname>AAA</sname>
<class>10</class>
<fees>5000</fees>
</student>
<student>
<sno>2</sno>
<sname>BBB</sname>
<class>9</class>
<fees>4500</fees>
</student>
<student>
<sno>3</sno>
<sname>CCC</sname>
<class>8</class>
<fees>4000</fees>
</student>
</students>
O/p:
Students
Student
-1
-AAA
-10
-5000
Student
-2
-BBB
-9
-4500
Student
-3
-CCC
-8
-4000
If we want we can also impose our own rules on XML data (or) document in the form of a
Schema. Which gets defined under a separate file with in extension .xsd

Naresh Tech. Class Notes

Hari

Page145

NagaRaj
.Net -->C#

Sri Sai Ram

Accessing xml files from .net application:


With .net application DataSets hold the data in xml format only. So, they were referred as inmemory DBs.
We can view content of a dataset using following methods which copies the content in to a file:
WriteXml(string path)
WriteXmlSchema(String path)
Ex:da.Fill(ds, Students);
ds.WriteXml(D:\\Csharp7\\Stud.xml);
ds.WriteXmlSchema(D:\\Csharp7\\Stud.xsd);
Note: Open any form where we used a dataset with students table & add the above last 2 statements
under the Fill method.
In the same way we can also read xml files into a dataset by using following methods:
ReadXml(string path)
ReadXmlSchema(String path)
Add a new windowsForm.cs
Creating an XML file:
Naresh Tech. Class Notes

Hari

Page146

NagaRaj
.Net -->C#

Sri Sai Ram

Create a folder with the name school in any desired location. Copy a few jpgimages in the school
folder where each image representing one student. Open a notepad write the following code in it:
Ex:
<students>
<student>
<sno>1</sno>
<sname>XXX</sname>
<class>10</class>
<fees>5000</fees>
<photo>any jpg image name</photo>
</student>
<student>
<sno>2</sno>
<sname>YYY</sname>
<class>9</class>
<fees>4500</fees>
</student>
<student>
<sno>3</sno>
<sname>ZZZ</sname>
<class>8</class>
<fees>4000</fees>
</student>
</students>
- Store the XML file in the School folder only as Students.xml
Code:Declarations:
DataSet ds;
int rno=0;
string dir;
---------------------------------------------------------------------------------------------Under Form Load:
Ds = new DataSet();
--------------------------------------------------------------------------------------------Under Load Button():
openFileDialog1.ShowDialog();
String.fpath=openFileDialog1.FileName;
Ds.ReadXml(fpath);
Dir=fpath.Substring(0,fpath.LastIndexOf(\\)+1);
ShowData();
----------------------------------------------------------------------------------------------private void ShowData()
{
textBox1.Text=ds.Tables[0].Rows[rno][0].ToString();
textBox2.Text=ds.Tables[0].Rows[rno][1].ToString();
textBox3.Text=ds.Tables[0].Rows[rno][2].ToString();
textBox4.Text=ds.Tables[0].Rows[rno][3].ToString();
pictureBox1.ImageLocation=dir+ds.Tables[0].Rows[rno][4].ToString();
}
Now under First, Prev, Next & Last buttons write the code for scrolling b/w records, and then
under insert button write code to insert the record retrieved from xml we created earlier.
Collections: these are similar to arrays which can hold multiple values in them. The basic difference in an
array & collection are,
Naresh Tech. Class Notes

Hari

Page147

NagaRaj
.Net -->C#

Sri Sai Ram

1. Array can store similar type values only. Whereas collection can store dissimilar type values.
2. Arrays were fixed length & static in size, were as collection were dynamic, variable length.
3. The array what we declared has a parent, that is a class array present in the system namespace.
Where collection were implemented separately as class under System.Collections Namespace.
If we want to use any data structures like stack, queues etc they were available directly
under .Net in the form of collection classes which we dont require to implement again they can
be directly consumed.

Under collection we have been provided No. of classes like stack, queues, LinkedList,SortedList,
ArrayList etc which we were as data structures in our traditional C, C++ languages.
Data structures in our traditional languages has to be explicitly constructor & consume. Where as
under .Net languages they were directly constructor & provided in the form of classes which can
be consume directly.
Stack:-which was a class that represent a simple last in

Naresh Tech. Class Notes

Hari

Page148

NagaRaj
.Net -->C#

Naresh Tech. Class Notes

Sri Sai Ram

Hari

Page149

Vous aimerez peut-être aussi