P. 1
Object Oriented Programming

Object Oriented Programming

|Views: 217|Likes:
Published by praptiitm

More info:

Published by: praptiitm on Sep 07, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

10/11/2011

pdf

text

original

Aprash Technologies +91-9953904262

Net stands for Network Enabled Technologies. It is a system, which can be used for developing applications of various types like Console, Windows, Web Apps and Mobiles Applications. .Net Contains Three major things: 1. Languages: -- c-sharp, V.B etc. 2. Technologies:--Ado.Net, Asp .Net etc. 3. Servers: -- Web Servers, Database Servers etc. Why .Net Introduce? It was introduced for two major reasons: 1. To overcome the drawbacks in its own traditional technology i.e. (Component Object Model) which is used for developing apps? 2. To compete Java language. .Net:- It is a collection of languages where a programmer can choose a language as per his requirements. Any .Net language compiled with an appropriate language compiler will generate the same type of Intermediate language (IL) code, which is Platform Independent. Compilation and Execution Process C-# .Net ---->CSC -----> CIL ------>CLR ------->Machine Code V.B. Net ---->VBC------> CIL ------>CLR ------>Machine Code CSC: - C Sharp Compiler VBC: - VB Compiler CIL:-Common Intermediate language. CLR:-Common language Runtime Note: The CIL code can be executed on any Machine provided the CLR is Available for thr Machine, which will take the responsibility of converting IL Code to Machine Code. Language Interoperability: C#.Net -----> CSC ---CIL ---Reverse in Any .Net Language. The Advantage of all languages generating same type of I.L Code is called Language Interoperability. i.e. the IL Code generated from in any .Net Language can be Re-Used from the Others remaining .Net languages

Any .Net Language -----Compile------CIL Code------Reuse in Any .Net Language

MailId:ashvin.kumar01@gmail.com

1

Aprash Technologies +91-9953904262
Features of 2.0 versions 1. 2. 3. 4. 5. 6. Partial classes, which allows class implementation across more than one source files. Generic and Parameterized type. Static classes cannot be Instantiated. The accessibility of property assessors can be se independently. Nullable value types, which provide improved interaction with SQL Server. Coalesse operator (??), which returns the first of its operands that, is not null or null if no such operands exist. 7. Anonymous Delegates. Features of 3.0 versions 1. 2. 3. 4. 5. 6. LINQ Object Initializes and collections Implicit Type Array Lambda Expressions Automatic properties Partial methods

Goals of C-Sharp language 1. It is intended to be simple, modern, Genarl purpose and oops language. 2. Language should include strong type checking array bound checking; detection of attempts, to use UN initialized variables, source code portability and Automatic Memory management by Garbage Collection. 3. The language is intended for use in developing software components that can take advantage of Distributor Environment. (Sql) 4. Programmer portability is very important for those programmers already familiar with c, c++ than c –Sharp. 5. It is intended to be suitable for writing applications to both Hosted and Embedded Systems. Data types can be classified in two ways. Value type: 1. It store data in stack form. 2. It is a place where data stores in affixed length such as int, float , 3. Every program has its own stack no other program can share its. 4. It allocate at the time of program execution. 5. Stack works as a principal LIFO and it was under control of operating systems, which doesn’t support dynamic memory allocation and destruction Reference type: 1. It stores references in a heaped form. In .net heap is now more managed and is called managed heaped.

MailId:ashvin.kumar01@gmail.com

2

Aprash Technologies +91-9953904262
2. When an application is created, the first reference type memory allocated for the type at the base address of managed heaped.

3. When the application is created the next object then the garbage collector allocates the memory for it in the address space immediately following the first object.As soon as address is available the garbage collector continues to allocate space for new object in this manner.

Note must read: string and object type only comes under the category of reference type String str=null; Int x=null; ----------invalid

If u wants to store null values in data type, you can us nullable value types like. Int? X=null ------------ valid Float? X=null----------valid;

Nullable value type: - It was a new featured added from 2.0 version specification, which allows storing null values in value type also (traditionally not possible) this provides improved interaction while communicating with any databases.

Data types categories: Integer: Byte Short Int Long Sbyte Ushort Uint Ulong Decimal or Float: Float ------------------------ 4 bytes Double --------------------- 8 bytes Decimal --------------------16 bytes Boolean type: Bool ----------true or false

MailId:ashvin.kumar01@gmail.com

3

which allows declaring variable by using a var Keyword.Aprash Technologies +91-9953904262 Character Type: Char--------------------------2 byte String------------------------variable length (depend on input text. 1. var x = 100---------------x as integer 2. The type of the variable will be considered depending upon the value by assign to a variable. var x= true----------------x as bool 3. ---------------------Invalid.its length. dynamic) Root type: Object------------------------variable length (dynamic) String type: It was not a fixed length type like int. Arrays is a set of similar type values 2. and it can change according to number of characters assign.com 4 . Collection is a set of dissimilar type values.kumar01@gmail. is also variable. float char. it at the time of declaration only. If at all. Object obj= x. the Reference type is again being converted into value type as referred as UnBoxing. ----------UnBoxing Loops: Foreach: It was a special Loop designed for Processing of Array and Collections. Note Must Read: To declare a variable using var keyword it is mandatory to assign a value to. it was variable length.0 specifications. ---------Boxing int y = obj. Example: 1. Implicit type Variables: It was a featured added under 3. Object type: It was a type. which can store anytype of value in it. var x. Example: Int x =100. type is called as BOXING. Boxing and UnBoxing: If a value type is stored on managed Heap in the form of a Reference. Jump Statements: MailId:ashvin.

Jagged Array It is a set of similar type values. Reverse(arrayname) 4. Length MailId:ashvin. } } Output: Go to statement called. Arrays: 1. Sort 2. Memory allocation to an array gets performed either with the use of new operator of assigning of values to the Array.Aprash Technologies +91-9953904262 C-Sharp provides a number of statements that allow jumping immediately to another line in a program. 1. In C-Sharp – Arrays can be declared as a fixed length and Dynamic.com 5 . Return Example: using System. 2. Fixed Length can store a pre-defined number of items while size of dynamic array increases as u added new items to the Array. Note: 1. Console. Go to 2. which were stored in a sequential order. as we have a chance of declaring and initializing later it gets the memory allocated on Managed Heap Array Class: It was a class under System Namespace. class GoText { static void Main() { goto xx Console. Copy(source. Array were Reference type because they are not in fixed size. xx. and Properties (variables).kumar01@gmail. Single Dimension 2. Break 3. destination) 3. which provides a set of methods a set of methods. Which can be applied in an Array? 1. Two Dimension 3.WriteLine (“hello “). Continue 4.WriteLine (“Go to statement called”).

} Console. Array.WriteLine(k). Array.WriteLine(k).com 6 . foreach (int k in arr) { Console. 3 }. brr = arr.Length.WriteLine(). } Console. foreach (int k in brr) { Console.kumar01@gmail. 5).Sort(arr). 8. } Console. foreach (int k in arr) { Console.Aprash Technologies +91-9953904262 Example: using System: class Arraycalss { static void Main(string[] args) { int[] arr ={ 5. } } MailId:ashvin. for (int i = 0.WriteLine(arr[i]).WriteLine(). } Console.WriteLine(). crr. foreach (int k in crr) { Console.WriteLine().WriteLine(k). i++) { Console. Array. int[] brr = new int[5].Copy(arr.Reverse(arr). int[] crr = new int[10]. 6.WriteLine(). } Console.WriteLine(k). i < arr. 8.

5}. MailId:ashvin. } Console. i++) { foreach (int k in array[i]) { Console.5}. 4.Parse(Console. 6}. array[0] = new int[4]. j++) { array[i][j] = int.Write(k + " "). it is also as Array of Arrays because Multiple single dimensional array were combined together to form a New Array i.Length.9.Aprash Technologies +91-9953904262 Jagged Array: It is same as Two-D array but in Two-D array . } } } Static values assigned to a Jagged Array: int [] [] array = { new int [4] {2.com 7 . j < array[i]. class Program { static void Main(string[] args) { int[][] array = new int[3][]. }. i < 3. i++) { for (int j = 0. Pointing to each row of the array we need to specify the number of columns to row.kumar01@gmail.e. array[1] = new int[5]. new int [4] {6. //Input From User for (int i = 0. Jagged Array. using System. 3. Syntax: dataType [][] arrayname=new dataType [no of rows] [ ].ReadLine()). new int [4] {4. array[2] = new int[2]. } } //display by for loop for (int i = 0. i < 3. whereas In case of Jagged Array each row can have varying number of columns .WriteLine(). the number of columns to each row should be fixed.

In case of second way while executing the program from command prompt we can supplied a list of values separated with a white space. foreach (string str in args) { Console. i.com 8 .ReadLine(). Example: File Name: example. using Redline () of Console Class.WriteLine(str).Aprash Technologies +91-9953904262 Supplying Command inputs to a Program We can supply input to a program.e.kumar01@gmail. using Command line Parameters. } } } Compile : csc example. which can be captured into the program in two ways: 1.cs Run : example 67 78 90 Aprash [press Enter] Output: 67 78 90 Aprash MailId:ashvin.cs using System. all the values provided will directly sit Under the string array of Main (). class Program { static void Main(string[] args) { Console. 2. Note: To captured the values supplied to the Program we can makes use of string array Parameter in main method.

In C Sharp “void” is Keyword. Polymorphism 4. the receive is known as Polymorphism. which can be done as following [Ref]<Type><variable> […………n]. Method: A method or a Sub Program was a block of code. 4. Abstraction 3. 3. which can be Reuse by calling it. MailId:ashvin.kumar01@gmail. language “void” is Type like data Type. 5. 2.com 9 . Encapsulation 2. which lacks of features like security and Reusability. Inheritance Encapsulation: It prescribes the code under object oriented under an Object Oriented Programming has to be enclosed under a wrapper or container known as class. Parameters definitions were the parameters wants to pass to the method(Optional). Syntax :[< Modifiers> void/ type Name ([Parameters]) { <Statements> } 1. this. To call method defined under a class should be explicitly create the object of class. 1. Which provides basic securities for your code? Abstraction: A talks about Hiding of complexity and provide with a set of Interfaces to consume the Functionality. 2. they need to be called explicitly for execution. Object oriented programming is a set of rules that has to be satisfied by languages to be called as Object Oriented those are: 1. Modifiers were optional which can be like public private etc. In C. To provide the security and Reusability a new approached in programming has been introduced known as OOPs.Aprash Technologies +91-9953904262 Object Oriented Programming Traditionally we were using procedural programming. Inheritance: It talks about acquiring the properties of a class into another class by establishing the Parent – Child relationships that provides Reusability of the Code. Load += new Evanthandler (Test). “Void” or type tells whether the method is returning a value or not. Polymorphism: Entity is behaving in different ways depending upon the input. After defining a method in a class.

Net Languages. ch1.Add(10. Using the Reference u can call all the abstract and Non-abstract members of parent. To check this rewrite the following code under the Main () method of child class.WriteLine("Result is "+x+y). 80).Multiply(10. 90). we can create the reference of parent class by using child class object. int y).Aprash Technologies +91-9953904262 Syntax : <class> <object>=new <class> ([<list of values>]) Example: Class1 c1=new Class1 (). Program prg = ch1. } public abstract void Multiply(int x. Example: using System. ch1. Abstract Class: An abstract class is not useful to itself because its object cannot be created. Console. int y) { Console. 40). but generally it is created under Main () method of the class because it was the entry point of the class. prg.com 10 . } static void Main(string[] args) { child ch1 = new child(). abstract class Program { public void Add(int x. its child classes can only consume it after implementing the abstract methods of Parent class. Object of the class is created only with the use of new operator under Java and . } class child :Program { public override void Multiply(int x. int y) { Console. MailId:ashvin. prg.WriteLine("Multiplication " + (x * y)).kumar01@gmail. We can create the object of a class anywhere under a class as well as can be created in other classes also.Multiply(10. static void Main(string[] args) { child ch1 = new child().Add(10. 90). } } Note: Under the child Class.ReadLine().

cs abstract class Figure { public double width. MailId:ashvin.Add New Class naming as Rectangle. Figure.5*radius *radius } Circle Class Public override double Get Area () { return ½ *height * width } Triangle Class In the above case the abstract class Figure provide the attributes that are common for all the and imposes restrictions on the child classes to implement the abstract methods as per there requirements without changing their signatures.height = height.com 11 .height.cs class Rectangle:Figure { public Rectangle(double height.kumar01@gmail. width. double GetArea(). double width) { this. this.Aprash Technologies +91-9953904262 } Figure Class Public double height. Example:-Under Same Project 1. radius. Public abstract void Get Area () Public override double Get Area () { return height * width } Rectangle class Public override double Get Area () { return 0.width = width. public abstract } 2.radius. } public override double GetArea() { return height * width.

Select properties option 4.Aprash Technologies +91-9953904262 } } 3. Run The Test. Console. Console.kumar01@gmail.GetArea()).Abstract Members [Assets + Liabilities] : Only Abstract members [Liabilities] MailId:ashvin. Right click on project name from solution explorer 3.WriteLine("Rectangle : "+rect.cs class Circle:Figure { public Circle(double radius) { this.ReadLine(). Console. } public override double GetArea() { return 3.cs Class . Select the test class from startup object dropdown 5. 20). Press F5 or ctrl +f5. 2. } } 4. } } Note : 1.Add new Class naming as Test.cs class Test { static void Main() { Rectangle rect = new Rectangle(10.Add new Class naming as Circle. Note: Non-Abstract Class Abstract Class Interfaces : Only Non-Abstract Members [Assets] : Abstract + Non .GetArea()).14 * radius * radius.com 12 . Circle cir = new Circle(20).radius = radius.WriteLine("Circle : "+cir.

An Interface cannot be declared with variables in its. they supports Multiple Inheritance. Note: Class Class 1 Interface Class 2 Interface Interface 3 Class Interface 4 MailId:ashvin. Every members of an Interface by default public but incase of class it was private.kumar01@gmail. Where as Inheritance what we are using through Interface is known as Interface Inheritance that was Multiple. As a class can inherit from another class and interface can inherit from an Interface. Inheritance can be categorized as Implementation Inheritance and Interface Inheritance The Inheritance what we get through Classes is known as Implementation Inheritance this is always Single. A class can have more than one Interface as its immediate parent.com 13 . 3. Class Single Set of Interfaces Multiple Class Syntax: [<Modifiers>] interface <name> { Abstract members Declaration } 1. Advantage of these Interfaces i.e.Aprash Technologies +91-9953904262 Interfaces: It is type or container in Object Oriented Programming. 2. Every member of an Interface by default abstract. which can be defined only with Abstract Members.

Interface contains only member declarations. The implement method of both the Interfaces in Interclass.cs and write the cod following interface Inter1 { void Add(int x. two and three case is possible but four case is not possible because u cannot define class members in an Interface.Test() { Console.cs and write the cod following interface Inter2 { void Sub(int x. void Test(). Add another interface in Project from Project Menu  Add new item select Interface naming as Inter2. } " + (x + y)).cs 3.Aprash Technologies +91-9953904262 Above one.WriteLine("Inte2 Method"). } If a class was made parent of another class we call it as inheriting from a class where as if an Interface is made as Parent to a class we call it as implementing as Interface because all the abstract methods of the interface should be implemented under the class. Add a New Class in Project from Project Menu  Add new item select class naming as Interclass’s and write the cod following class InterClass:Inter1. Add an interface in Project from Project Menu  Add new item select Interface naming as Inter1. int y) { Console. void Inter2. int y). Example: 1.WriteLine("Result of Add } void Inter1.WriteLine("Inte1 Method"). int y). } 2.com 14 . MailId:ashvin.Test() { Console.kumar01@gmail.Inter2 { public void Add(int x. void Test().

int y) { Console. the Method can be called by using the object of the class directly. the methods can be called only by using the Reference of Interface in which the method was declared.Test(). 1. int1.WriteLine("Test Method of Interfaces Implemented").com 15 . Inter1 int1 = obj. " + (x . obj. int2. Implement the method only once under the class so that both interfaces assume that the method of itself implemented. int1.WriteLine("Result of Subtract } static void Main(string[] args) { InterClass obj = new InterClass().Test().Sub(100.y)). } } Note: When a Class was implementing multiple interfaces and if these interfaces defines the same method while implementing that method under the class we can follow two approaches. Inter2 int2 = obj.Add(40.Test().Aprash Technologies +91-9953904262 } public void Sub(int x. Inter1 int1 = obj. Important Questions: MailId:ashvin. Example: InterClass obj = new InterClass(). Implement the method for multiple times under the class prefixing with the interface name before the method name. 2. Note: In this case.50). Example: public void Test() { Console.kumar01@gmail.70). obj. } Note: In this case.

Note: Now we can consume classes of the assembly by referring with Namespace.kumar01@gmail.com 16 .  How to add the Reference of an assembly in a project? Ans: Right click on Project from Solution Explorer Select Add Reference Click on Browse Tab Select Assembly from project folder/bin/debug/assembly file without any extension Click Ok. Can we consume a class of a project from a class of another project? Ans: “Yes”. 2. Can we consume a class of a project from a class of same project? Ans: “Yes”.Aprash Technologies +91-9953904262 1. we can consume but not directly. MailId:ashvin. as they were under different projects first we need to add the reference of assembly in which the class was present to the project who wants to consume it. we can consume them directly as both those classes were under the same project was considered as Family.

Private: . Protected: .  How to restrict a class not to be accessible to any other class? Ans: This can be done by declaring a constructor of a class as Private.Default scope for members of the class are private only. Protected internal 5.e. A type (Class) under a Namespace cannot be declared as private. Protected 4.kumar01@gmail.Aprash Technologies +91-9953904262 Access Specifiers: These are used to define the scope of type (class or interfaces or structures) or its members i. 2. restrictions appear only when we tried to access them outside of the class. Internal 3.Sharp provides five types of Specifiers. A Non-Child class cannot consume them. MailId:ashvin. How to restrict a class not to be inherited by any other class? Ans: This can be done by declaring a Class as SEALED.com 17 . 1. C. who can access them and who cannot.   Q2: 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 the constructor of the Class as protected. Public Note: Members defined under a class with any specifier or scopes were always accessible within a class.Members declared as private under a type (class) are not accessible outside of the type (class). A type (Class) under a Namespace cannot be declared as protected.Members declared as protected under a class can be accessed only from a child Class. 1. Private 2.

Members declared as protected internal enjoying dual scope i.Aprash Technologies +91-9953904262 3.WriteLine("Protected Method Invoked"). } protected internal void Test4() { Console. } protected void Test3() { Console. 5.WriteLine("Public Method Invoked").WriteLine("Private Method Invoked").WriteLine("Internal Method Invoked"). namespace TestAccess { public class Program { private void Test1() { Console. First Step: using System.A type (Class) or members of type (class) are declared as public is Global and can be accessed from anywhere.kumar01@gmail. } internal void Test2() { Console. Public: .e. Internal: .WriteLine("ProtectedInternal Method Invoked").com 18 . Example: Note: Make the Default Program class as public and write the following. Protected Internal: . } MailId:ashvin. 4. within the project they behave as internal and provide access to all other classes outside the project and still provide access to their child classes. } public void Test5() { Console.Members declared as internal under a type (Class) or accessible only within the project from a child or Non-Child class. Default scope of a class is internal only.

t1. prg. prg.Test1().Test2().Test5().Test4(). namespace TestAccess { class Two:Program { static void Main() { Two t1 = new Two().Test4(). prg. prg.cs. t1.Aprash Technologies +91-9953904262 static void Main(string[] args) { Program prg = new Program(). prg.cs using System. t1.Test3().kumar01@gmail. } } } Note: Run the Two.Test2().com 19 . } } } Second Step: Add a new class naming as Two. t1.Test3(). by following below steps: Right click on project Name from solution explorer Select Properties Select startup project then select TestAccess.Test5().two Press ctrl+f5 MailId:ashvin.

Test4(). Step 4: 1. MailId:ashvin.Program { Four f1 = new Four(). Adding Assembly of TestAccess Project In TestAccess2 project. T2. Right click on TestAccess2 Project from Solution Explorer Select Add Reference Click on Browse Tab Select Assembly from project folder/bin/debug/assembly file without any extension Click Ok.Test2(). T2.Aprash Technologies +91-9953904262 Step3: Add a new class naming as Three.cs. using System. T2.Test4().cs using System. Add new project naming TestAccess2 than Add a New class Four.Test5().Test2().cs 2.com 20 . } } } Note: Now check it out Run the Three. f1. namespace TestAccess { class Three:Program { static void Main() { Three T2 = new Three ().kumar01@gmail. namespace TestAccess2 { class Four : TestAccess. f1.

2.net languages could interoperate with each other i. 1. Class1.Program { Program f5 = new Program (). } } Language Iteroperability As we were aware that .cs under as: Public Class Class1 Public Function Fun1(ByVal str As String) As String Return "Welcome " + str End Function End Class Note:Compile the Project (press f6) 3. code of one language can we consume other languages. consume.com 21 . F5.Aprash Technologies +91-9953904262 f1. Note: Class Library is a collection of classes. there is a class name i.To consume the VBLibProject Class in any Other language like reference Of VBLibProject in CSharpProject. } } Step5: Add New Class in TestAccess2 naming as Five. C Sharp by adding the writes the code Right click on CSharpProject from Solution Explorer MailId:ashvin. Add new Project under a solution by choosing the language as VB and template as class Library by naming it as VBLibProject. By default under VBLibProject.e.Test5().cs using System. which cannot be executed but only.Test5().e.kumar01@gmail. namespace TestAccess2 { class Five : TestAccess.

using System. Fields (variables) Methods Constructors Properties Delegates Events Enumerations Properties: Some times.ReadLine(). Console. 6.cs File of CSharpProject Members of a Class 1.Fun1()).Class1().com 22 .kumar01@gmail. namespace CsharpProject { class Test { static void Main() { VBLibProject.WriteLine(c1. 5. } } } Note: run The Test.dll from project folder/bin/debug/. Access to the value outside of a class can be provided in two ways. Public Note: 2.properties MailId:ashvin. we have a value under a class.Class1 c1 = new VBLibProject. Click Ok. 2. which should be accessible outside of the class.Aprash Technologies +91-9953904262 Select Add Reference Click on Browse Tab Select VBLibProject . 1.dll file. 4. Console. 3. 7.

Aprash Technologies +91-9953904262
1. If a variable is declared as public i.e. accessible to everyone either to get the value or set the value. 2. If the access to the same value and if provided with property we can use in three ways. Read Write Property: Where the User can get or set the value Read Only Property: Where the User can get the value but not set the value. Write Only Property: Where the User can set the value but not get the value. Syntax: [<Modifiers>] <Type> <name> { [ get { Statements; } set { Statements; } ] } 1. If the property is defined with both get and set blocks i.e. Read write property. 2. If the property is defined with get and set block only i.e. Read only property. 3. If the property is defined with block only i.e. write property.

Enumerations: - It is also a type, which is a collection of values. (It is Value Type) Syntax: [<modifiers>] enum <name> {<List of Values>} public enum Days {Monday, Tuesday, Wednesday}; Enum type can be declared under either a namespace as well as a class also. Advised to declare under a namespace. As enum is a type to consume it, we required to create a copy of the type as well as initialized with a value. Example: Days d=0; Or Days d= Days. Monday; Example of Property and enum: using System; namespace PropClass { public enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday }; class Propert { Days _weekday=Days.Monday; int _cid = 101,_age=15;

MailId:ashvin.kumar01@gmail.com

23

Aprash Technologies +91-9953904262
string _cname = "Amit", _city = "Delhi"; //Read Only Property public int Custid { get { return _cid; } } //ReadWrite property with condition public int Age { get { return _age; } set { if (value > 18) _age = value; } } //ReadWrite Property public string Cname { get { return _cname; } set { _cname = value; } } //scope of property accessor set independently (2.0 version) public string City { get { return _city; } protected set { _city = value; } } //Automatic property(3.0 version)

MailId:ashvin.kumar01@gmail.com

24

Aprash Technologies +91-9953904262
//Doesnt requre a variable cannot write the code inside the block public string State { get; set; } public Days Weekday { get { return _weekday; } set { _weekday = value; } } } } To Consume all the above properties add a new Class Program.cs Example: using System; namespace PropClass { class Program { static void Main(string[] args) { Propert p1 = new Propert(); Console.WriteLine("Cust prev Id "+p1.Custid); //p1.Custid = 102; Invalid because it is read only property Console.WriteLine("After Changed Id "+p1.Custid); p1.Age = 12; Console.WriteLine("Age

"+p1.Age);

Console.WriteLine(p1.Cname); p1.Cname = "ankit"; Console.WriteLine(p1.Cname); Console.WriteLine(p1.City); //p1.City = "Haryana"; it will set on only child classes u cannot set the value //p1.State = "Uttar Pradesh"; //Console.WriteLine("state" = p1.State);

MailId:ashvin.kumar01@gmail.com

25

Console.kumar01@gmail. which is called for execution of the method.A delegate is a pointer to a method. 2.WriteLine(p1. The creation and destruction of stack each time is a time consuming process.State = "Haryana". Whenever a function is called to execute that.WriteLine(x + y).WriteLine("Changed weekday " +p1. } } } Note: 1.Aprash Technologies +91-9953904262 Console.Weekday). public static void Add(int x.com 26 . it creates a stack and destroys after execution. After defining the delegate for a method. Syntax: [<Modifiers>] delegate <void | type> Name ([<parameters>]) How to use delegate follow 3 steps give below: Step1:-Declare the Delegate Note: the Input Output parameters of a delegate should be same as the Input Output parameters of the method. Console. which is similar to the concept of function pointers under c and c++ languages. } MailId:ashvin. under 3.Weekday).Weekday = Days. p1. which uses the same stack even if method requires executing for multiple times.0 specifications we have been provided with automatic properties . where u can define a property without under code get & set blocks. //Cannot access have as this was not a child class p1.WriteLine("default weekday " + p1.Tuesday. It is only a delegate. State). This can be overcome with the help of function pointers or delegates.0 specifications. int y) { Console. we never call the method directly for execution. Under 2. int y). we were given the feature of setting the property accessor that scope or accessibility. Example: public delegate void AddDelagate(int x. which the delegate has to call. but the restrictions here was both get & set blocks were mandatory Delegate: .

it has to call as parameter.WriteLine("Multiply "+ (x*y)). Arithemetic arth = new Arithemetic(obj. Types of Delegate 1. 90). int y) { Console. Example: AddDelegate Ad = new AddDelegate(Add).kumar01@gmail. Ad (80. Step3: Call the delegate for execution.WriteLine("Subtract "+ (x-y)). } static void Main(string[] args) { Program obj = new Program(). } public void Mult(int x. using System. 90). int y) { Console. it is a single “Single cast Delegate” Where as if a delegates invokes multiple methods of a class that was “Multi cast Delegate”.As a delegate is also Reference type to consume it we need to create object of it by passing the target method name. public void Add(int x. Multi cast Delegate If a delegate invokes a single method of the class.WriteLine("Add "+ (x+y)). namespace MultiCast { class Program { public delegate void Arithemetic(int x. we want to call multiple methods the input and output parameters of all these methods should be same. Using a single delegate. int y). MailId:ashvin.Aprash Technologies +91-9953904262 Step2:. Example: Ad (100.Add).com 27 . which will execute the method internally. } public void Sub(int x. Single cast Delegate 2. Example of Delegate. int y) { Console.

2 It gets the memory allocated on Managed Heap Memory.Add. 5 Can contain variable declaration and initialization. Using new operator to create object was optional. Can contain variable declaration but cannot initialization. Faster in Access. arth -= obj. arth(10. It can be initializing either by referring with object of structure or under a Constructor. It gets memory allocated on stack memory where we do not have memory management with Garbage Collector. 4 Required to use new operator for creating a object. which can be defined with every member that can be defined under a class. arth(20. Console. arth += obj. } } } Structures: It was also a user-defined type similar to a class. MailId:ashvin.kumar01@gmail.WriteLine(). 3 Not Faster in access than Structure.WriteLine("Removing Add method from Delegate and Adding New Mult method"). It was a value type. Console.com 28 . 20).Sub.WriteLine().Mult. Console. Difference between Class and Structures? S.Aprash Technologies +91-9953904262 arth += obj. This has support of Garbage Collector for allocation and destruction.No Class Structures 1 It was a reference type. 90).

Example: using System.WriteLine("Result is } " + x). namespace Structures { struct Mystruct { int x.display().x = 1000. It was must. 8 It supports inheritance. public Mystruct(int x) { this. it should contain a default constructor. were implemented as a structure where as a type. If Defined with n constructor contains n+1 constructors or else only one constructor. contains n number of constructors or else one Constructor.com 29 . static void Main(string[] args) { Mystruct My. which comes under reference type (object and string) were implemented as a class.kumar01@gmail. which will be always defined implicitly.(Not oops) 7 If Class defined with n number of constructors. It does not support Inheritance. } } } MailId:ashvin.//Invokes Default constructor My.x = x. where a programmer cannot define it. My.display(). which come under value type category. My2. Mystruct My2 = new Mystruct(100). } public void display() { Console.Aprash Technologies +91-9953904262 6 May or May not contain a default constructor in it. Note: All the pre-defined types.

is known as Exception handling. which may come into picture while the execution of the program. namespace Structures { class MyStruct2 { static void Main() { Mystruct My3 = new Mystruct(2000). not related with exception also. Run Time Errors:-These are the errors. My3. Exception Handling:As a program is terminating abnormally when an exception occurs without executing the code i. } } } Exception and Exception Handling In the development of an Application. which may be due to some reasons like wrong implementation of logic. wrong input supplies to the program etc.e.cs File.  These Run time errors were also know as exceptions. Compile Time Errors 2.com 30 .kumar01@gmail.display(). Run Time Errors  Compile Time Errors:-These are the errors. these were a big problem because Whenever the exception occurs program terminated automatically on the same line by displaying an error Message without executing the next line of the code. Exception Class MailId:ashvin. To stop the abnormal termination and execute all the code. Threading namespace.Aprash Technologies +91-9953904262 If u want to consume a structure under a class or structure it is still possible by creating its object. 1. we may be coming across a set of errors. using System. which was not related with an exception. There were number of exceptions in applications where all these exceptions were internally implemented in the form of classes mostly comes under in System. which come into picture due to the syntactical mistakes within a language these are considered as a big problem. which can be of two different types. Add a new MyStruct2.

kumar01@gmail. To handle this we can use the try catch block. Whenever an exception scenario comes into picture within a program execution. then Exception Manager Gets invoked which identifies the type of exception that creates the object of related Exception class and throws it. which will cause an exception Statements related with Exception. Syntax: try { Statements. namespace ExceptionDemo { class Program MailId:ashvin. which should not execute when exception occurs } catch (<exception> variable) { Statements that has to execute only when exception occurs } [<Multiple catch blocks if required>] .Aprash Technologies +91-9953904262 Abnormal Termination Return an Error Msg with Exception Return an Error Msg with Exception Return an Error Msg with Exception DivideByZero NullRefObject IndexOutofRange FileNotFound Format Exception Process Of Execution while Exception Occurs. Example: Exception Handling using System. This will terminate the program abnormally and displays the related error message.com 31 .

WriteLine("Exception caught"+e3).ReadLine()). try { Console.Parse(Console. x = int. try { Console. z = x / y. Example: using System.ReadLine()). Exception occurred or not.WriteLine("Input value is not in correct format"+e2). } Console. Console. z. namespace ExceptionDemo { class FinallyDemo { static void Main() { int x.WriteLine("Enter X value ").WriteLine("Result is " + z). y. } } } Finally: It is a block of code. MailId:ashvin.WriteLine("Enter Y value ").WriteLine("Enter X value ").WriteLine("Division cannot be zero"+e1). } catch (DivideByZeroException e1) { Console.z. } catch (FormatException e2) { Console.kumar01@gmail. which can be paired with try the code written under this block will be executed at any coast. I.Parse(Console.e.WriteLine("End of the Program"). y = int. Console.Parse(Console.Aprash Technologies +91-9953904262 { static void Main(string[] args) { int x. x = int.ReadLine()). } catch (Exception e3) { Console.com 32 . y.

MailId:ashvin. } catch (Exception ex1) { Console.WriteLine("End of the Program"). Try catch and finally blocks can be used in three different combinations. 1.WriteLine("Enter Y value "). Console. If a Programmer wants to raise its own exception under a program. if (y == 1) return.WriteLine(ex1.ReadLine(). but only after executing the finally block . Application Exception:-programmer within a program on their own conditions can also raise Exceptions. catch and finally 3.Message). if the value to a divisor is one (1) the execution of the program suspends because of the return statement.kumar01@gmail. which returns the Error message that is associated with the exception that has occurred. z = x / y.WriteLine("Finally Block Executed"). try and catch 2.com 33 . y = int. try. Message is a property of exception class.Parse(Console.WriteLine("Result is " + z). try and finally Exceptions are of two types:1. } Console. System Exception: .Aprash Technologies +91-9953904262 Console. } finally { Console.ReadLine()).An exception that is raised internally on some predefined error or conditions is known as System Exception. we need to do following steps. 2.because once the control enters into try block we can not stop the execution without executing Finally block. Console. } } } Note: In the above program.

WriteLine("Enter Y value "). z. UNIX ---Multi tasking O/S MailId:ashvin.WriteLine("Enter X value ").Parse(Console.Aprash Technologies +91-9953904262   Create the object of any Exception class Throw the object by using throw statement. Multitasking:-if more than one program can be executed at a given point of time. This is generally supported in the Operating System. Threading: Thread:-A thread can considered as a unit of execution responsible for executing the code.e. Note: Programmer can also create its own exception by inheriting the Application Exception Class.ReadLine()).ReadLine()).WriteLine("Result is "+z). then exception is raised. Console. z = x / y. y = int.com 34 .   Dos -------------------Single tasking O/S Windows. } } } In the above program if the value to the divisor is an odd number. thread. Question:-Can we throw the object of any exception class to raise an exception? Ans:-“Yes”. every program has one thread for execution i.Parse(Console. By default. y.kumar01@gmail. Example: using System. Console. x = int. we can throw the object of any exception class for raising an exception but the error message will be the same error message associated with that exception. Console.ReadLine(). namespace ExceptionDemo { class ThrowDemo { static void Main() { int x. we call it as Multitasking. Console. if(y %2>0) throw new ApplicationException("Attended exceptionto odd number").

if multiple a method has to be executed. which the languages with the help of O/S generally support. MailId:ashvin. which may be poor in performance. which makes the current executing thread to sleep up to the specified time. the control gets transferred to the other thread in execution. 6.Time Sharing:-In this. Abort ():-It is used for terminating the execution of a thread. In Multithreading. Creating Thread:To create a thread we need to create the object of thread class by passing the method name. first will exit from the program First. the execution should also end with Main () only because it controls the complete program. which completes its work. In a Single thread model. Join ():-By default the execution of a program starts from Main () because it was the entry point as well as the controller of a program. Thread class available under the namespace i. If Main () complete its work it will leave the program as well as leaving the control to other threads in execution which should not be happens a point of time.Aprash Technologies +91-9953904262 Multithreading: . it has to call as an argument. Start ():-It is used for starting the execution of thread.e. In this scenario if we want the Main () thread to wait until all the other threads exiting the program and then exit we need to call the method Join () on all the other thread in execution. 3.e. one method after the other.System. Maximum Utilization of CPU Resources:-This comes into the picture when the first principal violate i.kumar01@gmail. Resume ():-It is used to resume the thread that has been suspended. Suspend ():-Causes the thread to suspending its execution until resume was called. 2.A single Application performing multiple activities simultaneously is known as multithreading. if a thread could not execute within its given time without wasting the time then. the thread.Threading. 1. the O/S allocates some time period for each method to execute and keeps on transferring the control between each thread giving equal importance to all methods.e. Example:Thread (Method name) Thread th1=new Thread (method) Methods of thread Class 1.e. was elapsed.com 35 .e. we have a problem i. 2. a separate thread for each method to execute where the execution takes place as following 1. The other way of executing multiple methods in an execution is using Multithreading i. 5. 4. they are executed in queue based i. Sleep (int milliseconds):-It was a static method.

kumar01@gmail.WriteLine("Check2 " + i). MailId:ashvin. t2. t2. } static void Main() { ThreadDemo obj = new ThreadDemo(). } } Console. } Console. i++) { Console.Whereas in some cases multiple threads may access the same resource. } public void Check1() { for (int i = 1. } } } Thread Synchronization: . t2 = new Thread(Check2). } public void Check2() { for (int i = 1.Start().WriteLine("Check1 " + i).t1.Join().A multithreading we use a separate thread for calling an each method as in our previous example . namespace ExceptionDemo { class ThreadDemo { Thread t1. t1. i <= 100.Sleep(10000). public ThreadDemo() { t1 = new Thread(Check1).Aprash Technologies +91-9953904262 Example:using System. i++) { Console. obj.WriteLine("Thread2 Exit").Join(). obj.WriteLine("MainThread Exit").WriteLine("Thread1 Exit"). if (i == 5) { Thread.Threading. i <= 100. in this situation we may be getting some un expected result results as following. Console.Start(). using System.t2.com 36 .

Start(). t1. } } } Note: In the above case. namespace ThreadSynExample { class ThreadSyn { Thread t1..t2. namespace ThreadSynExample { class ThreadSyn { Thread t1. t2.Join(). two threads were calling the same method Display () where as get some unexpected result: Output of above Program like. which allows only one thread to access the method at a time. using System.WriteLine("Microsoft ").com 37 . t2.Write(".Net is a: .Join(). using System.kumar01@gmail. public ThreadSyn() { t1 = new Thread(Display). SynThr. t2 = new Thread(Display). Thread. } static void Main(string[] args) { ThreadSyn SynThr = new ThreadSyn().Aprash Technologies +91-9953904262 using System.Net is Product of :-").Sleep(5000). } public void Display() { Console.Threading.Threading.Start(). Console. SynThr. Example: using System. t2. public ThreadSyn() { MailId:ashvin.Net is a: .Microsoft Microsoft To overcome the above problem we can use the thread Synchronization or thread locking mechanism.t1.

2. SynThr. Lower Below Normal Normal (default) Above Normal Highest Example: using System. 5.Write(". Priority to a thread can be set with 5 different values.Aprash Technologies +91-9953904262 t1 = new Thread(Display).Net is Product of :-"). SynThr.t1.t2.Start(). Console. 4. } public void Display() { lock (this) { Console. using System.they can’t enter inside the monitor until the thread inside the monitor out.kumar01@gmail. MailId:ashvin. If u wants to give any additional priority to a thread for execution.Sleep(5000). By default. Thread. we can make a request to the operating system for allocating more time to consume the CPU resources by setting priorities.WriteLine("Microsoft "). t2 = new Thread(Display). } } static void Main(string[] args) { ThreadSyn SynThr = new ThreadSyn(). which was the Normal.Join().Start(). Thread Priorities:-By default when there were multiple threads in execution.Net is product of Microsoft When the method is locked . 1. the operating system gives same priority for all the threads in execution.a monitor gets created around the class which allows only one thread can enter into it at a time when one thread under the monitor even if the other thread start their execution .Threading. 3. t1.Join().Net is product of Microsoft . t2. The operating system allocates some time to each thread in execution and transfers the control between each thread. } } } Result: .com 38 .

Abort().WriteLine("Count 1 " + obj. obj. t1. } } } Windows Application Traditionally we were using various type of application like Console as known as CUI.Priority = ThreadPriority.cnt2). cnt2.t1.Aprash Technologies +91-9953904262 namespace ThreadSynExample { class ThreadPrior { Thread t1. } public void IncCount2() { while (true) cnt2 += 1. Thread. obj.com 39 . Console.WriteLine("Count 2 " + obj. } static void Main() { ThreadPrior obj = new ThreadPrior(). } public void IncCount1() { while (true) cnt1 += 1.t1.Start(). Console. t2. t2. Examples are-Dos.Abort(). CUI has Many Disadvantages’ like- MailId:ashvin.kumar01@gmail.Priority = ThreadPriority. long cnt1.t2. obj. obj.Start(). public ThreadPrior() { t1 = new Thread(IncCount1).Sleep(4000).WriteLine("Please Wait Thread is in Process").Join().Lowest.t2.cnt1). UNIX operating System.Highest. t2. t2 = new Thread(IncCount2). t1.Join(). Console.

Label Textbox.Panel. it was introduced under 2. the support for developing windows Applications has given in all .Aprash Technologies +91-9953904262 1. Application. 2. 2.Windows. action or method like Click. We can work on windows application by using some components called Controls which are in under the namespace of System. Split Container and Tab Control. 3. Properties:-Attributes of control.Form. public class MyForm: Form { static void Main () { MyForm obj=new MyForm (). } } Note: Save the File App.Net introduced. To develop Windows Application Microsoft has introduced in 90’s Visual Basic language. Method:-Perform an Action. Container Controls: . Non-Container Controls:-Button. which solves the above disadvantages. which is specifying u to perform an Key Press. Partial Class: It is an approach. GUI is Graphical User Interface. 2. Treeview etc. Later when .Net languages along with Visual Basics. Controls categorize in two ways:1. Events:-It is a period.com 40 .Windows.kumar01@gmail. which allows defining a class in more than one file.0 specifications the advantages of this approach will be MailId:ashvin. Do not allow to navigate from one field to another. using System. Example of Developing Application through Notepad.Forms. There was not user friendly.cs and execute it through command prompt. using System. Every control has three things in common 1. Run (obj).

Multiple programmers’ works on a class at a time.<event> +=new <delegate> (<event procedure>) Ex: this. Splitting of huge volume of code into multiple files that make managing easier.kumar01@gmail.com 41 . this. The code Written under event procedure will be internally executed by the event with the help of delegate. which takes the responsibility of executing code under the Event Procedure. Syntax: <Control>. An Event Procedure is a block of code i. Load +=new EventHandler (form1_Load).Visual studio writes a mapping statement as following. Eventargs e) { <Statements> } MailId:ashvin. Bounds Control Event Procedure Delegate Description:-In the above case whenever the event raises it will call the delegate. Click +=new EventHandler (button1_Click). Q3: Can we define Event Procedure manually? Ans: Yes. Q2: How does the Event and Delegate & Event Procedure is linked with each other? Ans: Events and Delegate were predefined under the base class Library. 2. what we define here only an event procedure under the form to link the delegate and event procedure .Aprash Technologies +91-9953904262 1. Q1:-What is the method under which we were writing the code corresponding to an event? Ans:-The method under which we write the code has a special name known as Event Procedure. bound with an event of a control and is executed whenever the Event raises.e. we can define event procedure manually as follow [<Modifiers>] void <name> (object sender.

so they were always void.Form. } Private void Test (object sender. public class MyForm1: Form { public MyForm1 () { IntializeComponent (). this. Height=400. this. Examples are . this. Load += new EvantHandler (Test).Windows.com 42 . button1_Click Every Event Procedure should have two mandatory parameters   Object sender EventArgs e Example in Notepad: App.cs using System. } Private void IntializeComponent () { this. We can specify any name to an Event procedure but Visual studio Follows a convention while naming them. this. } } MailId:ashvin. Run (new MyForm1 ()). Width=400.Show (“Event raised”). } static void Main () { Application. Text=”My Form”.Aprash Technologies +91-9953904262 Note:   Event Procedure is Non Returning value method.kumar01@gmail. Click += new EvantHandler (Test).Form1_Load. using System. EventArgs e) { MessageBox.

JET (Joint Engine Technology) Drivers. Databases.They were again Two Types. 2.Aprash Technologies +91-9953904262 Note: Run the App.kumar01@gmail. Designer code and Business Logic were defined under a class present under a file. Business Logic 1.Net2. 1.cs file through Command prompt. Examples: Files.Net2. 2. To facilitate the process of communication’s.0 with introduction of partial classes’ designer code and business logic code were separated into two different files but on the same class only. 1. From . method and Business programmers in the form of event procedure define logic. is known as Business Logic? Before .Ms has provided a solution in the form of drivers and providers. A data source (or) data store is a place where we stored the information. MailId:ashvin. Business Code: which is responsible for execution of the form. Data Source:1. Designer Code 2. ADO. Drawbacks’ of Drivers  They were initially designed only to communicate with Databases. code is categorized in two ways:1. ODBC (Open Database Connectivity). 2. Designer Code:-This code is generated by Visual studio Under the Initialize Component (). Jet Drivers: . Indexing Servers.These were the initial solution provided by the Microsoft to communicate with Databases .Odbc Drivers:-These are used for Communicate with Remote Databases. 2.com 43 .These are used for communication with local Databases.0. A language cannot communicate directly because each data adopts a different protocol for communication. Applications------> Drivers and Providers------> Data Sources Drivers: .NET In Windows Applications.

OLEBDB:-Object Linking Embedded Database.Aprash Technologies +91-9953904262  The Driver installed and configured on each and every machine where the Application in Executing.kumar01@gmail. as a next solution after drivers.e. The classical Visual basic language could not communicate directly with this drivers and providers because of the Native Code support in them.com 44 . which can communicate with data sources. To overcome the problem MS has designed few Intermediate components for VB language to communicate with drivers and providers. as they were designed by using Native Code Languages they were purely Platform Dependent. and in case of providers we do not required any installations and configurations on each client machine. Providers: OLEB Providers: These were provided. which will intern communicate with data servers as follows:- Visual Basic Data Access Object Remote Data Object Active-X data Object JET Drivers ODBC Drivers OLEDB Drivers Local Databases Remote Database Data Sources MailId:ashvin. Both the Driver and providers suffers from a common problem i.

Note: All the above four namespaces contains some set of classes as following. 2. System.OracleClient: Collection of classes used for communicate with Oracle.OracleClient System.Net:.Net applications.In this process.Data. the best of traditional 3 technologies ADO’S has been redesigned as ADO.Data.Net languages. 4. 5.Net provides various classes.Data. Every Operations we perform on a data source involves three steps    Establishing a Connection Applying a SqlStatement Expecting the result 1. which will intern communicate with data sources. 4. 6.Aprash Technologies +91-9953904262 ADO.com 45 .SqlClient System.Data System.It was the collection of managed providers used for communication with any data source from . System. 5.Odbc System. System. DataColumn. and DataRelation. System. Classes under these were DataSet. Connection Command DataReader DataAdapter CommandBuilder Parameter etc. 3.Oledb System.Data: It is a collection of classes used for holding and managing the data on Client machine.When . System. ADO.Odbc: Collection of classes used for communicate with traditional ODBC drivers. 3. DataTable.Data. which can be used for data source communication under the following Namespaces.Data.kumar01@gmail.Net introduced to communicate with data sources from.SqlClient: Collection of classes and communicate only with Sqlserver.Oledb: Collection of classes used for communicate with any database.Net. To open the channel for communication we use Connection Classes MailId:ashvin. 1.Data. Establishing a Connection: .Data. DataView. 2. we open a class for communication with target machine to perform our operations. 1.Data.

we use a different provider for each Data Source.Indexing Server Msdaora SqlOledb Microsoft. 4.4.Oledb. 2. User Id and Password: . 4. Oracle Scott/Tiger B. 2. Password =Tiger [. User Id=Scott. Provider Data Source User Id and Password Database or Initial Catalog Trusted Connection DSN Provider: . A. MailId:ashvin. does not required to be specified. User Id=SA.kumar01@gmail. Oracle B. 5. State: -Property to find current state of Connection. we required valid username and password.SqlServer SA/<Blank> Initial catalog or Database and Trusted Connection: -These attributes will be used only while connecting with SqlServer. 6. Data Source=<server>]” Methods and Properties of Connection Class 1.com 46 . DSN: -This attribute is used in case of ODBC classes.Aprash Technologies +91-9953904262   Connection () Connection (string ConnectionString) ConnectString is a collection of attributes that is used for connecting with target machine. 3.0 MsIdx Data Source: . Open(): -Method to Open a Connection Close (): -Method to Close a Connection.Jet.It was the name of the target machine where a data source or database is present.MsAccess/Excel D. if it was on Local machine. 3.As we were aware that a provider is required for communicating with data sources. ConnectionString-Property to get or set the Connection String. Data Source=<server>]” Connection String for SqlServer “Provider=SqlOledb.SqlServer C.As databases were secured places for storing data to connect with them. Connection String for Oracle “Provider=Msdaora. A. Those are 1. Password=<pwd> Database=<dbName> [.

Show(con.User Id=sa. Example: 1. 2.Password=123.State.Aprash Technologies +91-9953904262 The object of the connection class can be created in any of the following ways. con.kumar01@gmail.User Id=Scott. Verify The Result.State.com 47 . Connection con= new Connection (). MessageBox. Double Click on Second Button and write the code as following SqlConnection con = new SqlConnection(). 4. Double Click on First Button and write the code as following OleDbConnection con = new OleDbConnection("Provider=Msdaora. con.Create a new Windows Application Project.Password=tiger"). 3. Or Connection con= new Connection (“<ConString> “).Close().Show(con.ToString()). MessageBox. Con. con.Open().ConnectionString= "provider=Sqloledb.database=Master".Open(). Place two Buttons Inside the form. con.Close().ToString()).ConnectionString=” ”. con. MailId:ashvin.

cmd. we send an instruction to the data source specifying the type of activity that has to be performed using a SqlStatement like Insert. 1. Command (string sqlstmt. This captures the data under DataReader. Update. ExecuteScalar() --------> Object (Return) 3. which captures the data under an object variable. cmd. Delete. ExecuteNoneQuery ():-Whenever we want to execute Non-Query Statements(DML)like Insert . ExecuteReader() -------> Data Reader (Return) 2.CommandText=”<sqlStmt”>. 1.com 48 .Aprash Technologies +91-9953904262 Applying a Statement In this process. which was a class. MailId:ashvin. and Select. 3. Command () 2. con).Connection=<con>. Or Command cmd=new Command (“<sqlstmt”>. 2. ExecuteScalar ():-Whenever we want to execute a select statement that returns single value result. modeled on table. ExecuteNonQuery()--. Methods Of Command Class.Whenever we want to execute a select statement that returns values in the form of Rows and Columns. Command Text:-To set or get the Current sqlStatemant associated with Command. 2. Connection:-To set or get the Current Connection Object associated with Command.kumar01@gmail. we need to call any of these three methods to execute the Statement. ExecuteReader ():. Delete . Update . We Use Commend Class for applying a statement. 1.> Integer (Return) Note:- After Creating the Object of Command class. Connection con).so that number of Rows being affected is returned as a integer value. Properties of Command class 1. Object of the Command Class created as below Command cmd= new Command ().

Data. GetName (index): -Returns an string. used for moving the record pointer from current location to next row . 2. after moving the pointer it will return the specifying values were present in the row to which .kumar01@gmail. GetValue (int index):.Returns Boolean value. Used for picking the field value from the row to which pointer was pointing by specifying the column index position. Read ():. <dr> [index] --------> object <dr> [name] --------> object 3. Declaration under class globally. it moves that will be true if present and false if not present.Aprash Technologies +91-9953904262 Accessing data from DataReader. 1. Excersise1: Steps: 1. To access the data from DataReader it provides Methods.com 49 .OleDb. Used getting the name of column for specifying index. Note: . which is modeled on Table.We can also access data pointer by pointer in the form of single dimensional array also by either specifying column index position or name. DataReader is a class. Include Namespace using System. MailId:ashvin.Returns an object.

com 50 . } } 3.Text = dr.Text = dr.User Id=Scott.ToString().Text = dr["City"]. ShowData(). 2. this.Open) { con.GetName(0).Close().Show("Last Record"). label1.Close().GetName(1). 1.ToString(). textBox3. dr = cmd. Create A function in a class private void ShowData() { if (dr.Read()) { //Fetching EmpId . textBox2.State == ConnectionState. OleDbCommand cmd. Code under Close Button if (con.Name and City from emp table textBox1. Code under Next Button ShowData(). OleDbDataReader dr.GetValue(0). } else { MessageBox. con.Text = dr.Aprash Technologies +91-9953904262 OleDbConnection con. MailId:ashvin. con). Execute the Application. label2. cmd = new OleDbCommand("select * from Emp".ExecuteReader(). Write the Code under the Form_Load Event con = new OleDbConnection("Provider=Msdaora. label3.Text = dr.kumar01@gmail.Text = dr[1]. 4. } 5.ToString().Open(). Password=tiger").GetName(2).

LoadData(). Code under form_Load Event con = new OleDbConnection("Provider=Msdaora.Data. Declaration under class globally.State == ConnectionState.Password=tiger"). cmd = new OleDbCommand(). Create functions private void SetStmnt() { if (con. 2.Connection = con.Closed) { MailId:ashvin.kumar01@gmail. OleDbConnection con.User Id=Scott.Aprash Technologies +91-9953904262 Excersie2: Steps: 1. OleDbDataReader dr. 3.OleDb. OleDbCommand cmd.com 51 . string SqlStr. 2. cmd. Include Namespace using System.

if(count>0) { MessageBox.YesNo. textBox1."n\n\Confirm SqlQuery". con. Code under New Button textBox1. Code under Next Button LoadData ().Show("Stmt Failed"). textBox1.Name and City from emp table textBox1.Text = dr[2]. } } private void ExecuteDML() { DialogResult drs=MessageBox.Show("Stmt Executed").ToString().Text = dr[0].Text = "". SqlStr = "select max(Eid) from Emp".MessageBoxIcon.ToString().com 52 .Read()) { //Fetching EmpId . } else { MessageBox.Yes) { SetStmnt(). } else { MessageBox.Show("Last Record").Question).Text = textBox3.ExecuteNonQuery(). SetStmnt().Aprash Technologies +91-9953904262 con. } private void ShowData() { if (dr. } LoadData(). 4. } } 3.kumar01@gmail.ToString(). int count=cmd.CommandText = SqlStr. } cmd.Open().MessageBoxButtons. if(drs==DialogResult. MailId:ashvin.Text = textBox2.Show("Do You want to Execute ?".Open().Text = dr[1].

Text+" '. Execute Application Working with SQl Server Create the table in SQL Server with following fields. under Close Button if (con. textBox2. MailId:ashvin. ExecuteDML(). this.Focus().Aprash Technologies +91-9953904262 textBox1.Text. Code under Insert Button { SqlStr="insert into Emp(EId. set status field as default value is one (1).Text+"')".kumar01@gmail. ExecuteDML().Text = cmd. 7.Text+ "' where EId="+textBox1. '"+textBox2.City)values("+textBox1.Close(). under Update Button SqlStr="update Emp set EName='"+textBox2.'"+textBox3.com 53 . 5.Open) { con. In addition. } 9. } 6.Text+" '.ToString().Ename.Text+". ExecuteDML().ExecuteScalar().Close(). 8.City=' "+textBox3.Text.State == ConnectionState. under Delete Button SqlStr="Delete from Emp where Eid="+textBox1.

Text = dr[2].com 54 . textBox2. Now comes to Windows Application and design the Form as well. 1. Create the Show Data Function private void ShowData() { if (dr. string SqlStr.ToString(). 3. Include namespace-using System.ToString().Name and City from emp table textBox1.Data.kumar01@gmail.Text = dr[0]. SqlDataReader dr. SqlCommand cmd. 2.Text = dr[3].Text = dr[1].SqlClient. Declarations at class level SqlConnection con.Aprash Technologies +91-9953904262 Add some values in it. textBox4. MailId:ashvin.Read()) { //Fetching EmpId .ToString(). textBox3.ToString().

ExecuteReader ().GetName(2).Show("Last Record"). cmd = new SqlCommand("select Sno.SName.Aprash Technologies +91-9953904262 } else { MessageBox. dr = cmd. 2.GetName(1). 5. 8. this. } 7. DataReader: .GetName(0). It can hold multiple tables’ in it at a time to load multiple tables we need to pass multiple select statements as arguments to Command Class Separated by semicolon. ShowData().Close().Text = dr.Fee from students".Text = dr. Example: SqlCommand cmd= new SqlCommand ("select * from Emp .com 55 . con.Integrated Security=True"). under form_load Event con = new SqlConnection(@"Data Source=localhost. } } 4.It is a class modeled on table that can be used for holding data on Client machine.Text = dr. label3.State == ConnectionState. 6.Open) { con. con). MailId:ashvin. 1.ExecuteReader().Text = dr. Execute the Application. label4. under Close Button if (con. label2. select * from Dept "). DataReader dr=cmd.kumar01@gmail.Class.InitialCatalog=Abc.GetName(3).Close(). Features of DataReader. under Next Button ShowData(). label1.Open(). Faster Access to data from Data Source as it was Connection oriented. Rest of buttons code are similar to previous Excersice.

It provides Scrollable Navigation that allows moving any direction. Drawbacks of DataReader 1. Connection con) DataAdapter (Command cmd) MailId:ashvin.com 56 . Data. DataReader <--------Command <------DataSource DataSet <------ DataAdapter <---- DataSource Constructors of DataAdapter DataAdapter (string SqlStmnt. using System. Which will not to allow any changes to data present in it? DataSet It was a class used for holding and managing the data on a client machines apart from DataReader. is Command in it in the same way. It was Updatable. 3. which does not require any permanent connection with Data Source for holding the Data. It was also capable of holding multiple tables.e.Aprash Technologies +91-9953904262 Note:-Use the NextResult () Method on DataReader object to navigate from current table to next Table. if the connection is closed we cannot access data. which will be a burden on database server when multiple clients were accessing data from in it. Features of DataSet 1. DataAdapter is used for communication between Data Source and DataSet.dr. Using DataSet The class. 2. 2.NextResult (). which is responsible for loading of Data into DataReader from DataSet. 3. Example: . allow to go either to Next Record or Table but not to previous record or table. 4. changes can be performed on Data present in it.It was present under namespace. It was designed on Disconnected Architecture.kumar01@gmail. It provides only forward Navigation i. It is designed as connection oriented which requires a permanent connection with data source to access the data. It was a Read Only Object.

DataSet – Collection of Tables (Data Tables) Syntax:<Dataset>.Tables [“student”] Every Data Table is again collection of Rows and Columns where each row is represented as a class i.Used to transfer changes made on data from data source to DataSet. 2. 3. we need to call Update method Accessing Data from DataSet.Tables [0] or Ds. Closes the Connection. Methods of DataAdapter 1. DebaTable and identified by its index position or Name. DataAdapter was internally collection of four Commands 1. if we want to send those changes back to data source. Moreover.kumar01@gmail. 4. 3.com 57 .Tables [0]. 5. DataColumn and identified by its index position or name.e. 3. con). DataTable. If any changes made on DataSet. Select Command Insert Command Update Command Delete Command When we call Fill. method on adapter following things takes place.e. 4. 2.Rows [index] Collection of Columns [Data Columns] <DataTable>. Update ( ):. identified by its index position. collection of Rows [Data Row] <DataTable>.Aprash Technologies +91-9953904262 Example:DataAdpter da= new DataAdapter (“<SqlStmnt”. Executes the Select Command under it and loads data from table to Dataset. Opens a connection with the DataSource.e. 2. DataSet is a collection of tables where each table is represented as a class i. DataRow. 1.Tables [Index] or Tables [“table name”] Ds.Columns [index] or [Column Name] ds.Columns [0] Or MailId:ashvin. Fill ( ):-Used for loading data from data source to dataset. Each column is represented as a class i. 2. 1.

com 58 .Aprash Technologies +91-9953904262 6. write the code under the form. ds.VisualBasics assembly from.Rows [0] [0] Or ds. 2.VisualBasic.Tables [0].Columns [“Sno”]. Referring to cell under a DataTable <DataTable>. Add reference of Microsoft.Tables [0]. SqlDataAdapter ad. using System.kumar01@gmail.Tables [0].Net tab of add Reference window Moreover. using Microsoft.Rows [row] [column] ds. SqlCommandBuilder cmb.Rows [0] [“Sno”] Exercise 3: Steps: 1. int rwno=0. MailId:ashvin.Data. 3.SqlClient. DataSet dst. Declarations: SqlConnection con.

1.Tables[0]. "Students"). dr[1] = textBox2.Text. dst = new DataSet(). Code under Next rwno = dst.Rows. 6.Rows.AddWithKey. dr[3] = textBox4. Code under Form_Load con = new SqlConnection("Data Source=localhost. 5.ReadOnly = true.Tables[0]. ShowData(). cmb = new SqlCommandBuilder(ad). con).Fill(dst.Count . dr[2] = textBox3. ShowData(). Code under Previousbtn if (rwno > 0) { rwno -= 1.Text. ad.Fee from students".Integrated Security=True. ShowData(). Code under FirstBtn rwno = 0.kumar01@gmail. dst.Aprash Technologies +91-9953904262 4.Text. ShowData().Add(dr).com 59 .Show("Last Record"). } else { MessageBox.1) { rwno += 1.Show("First Record").Tables[0].NewRow(). 9. ShowData().Pooling=False"). } else { MessageBox. } 8. dr[0] = textBox1.Count .SName.Text. Code under InsertBtn DataRow dr = dst. Code under Nextbtn if (rwno < dst.MissingSchemaAction = MissingSchemaAction.Initial Catalog=Data.Class. ad = new SqlDataAdapter("Select Sno. ad. textBox1. } 7. MailId:ashvin.Rows.Tables[0].

Text = dst.Text = dr[0].PerformClick(). 11. 200)).Tables[0].Rows[rwno][0]. textBox4. textBox2.kumar01@gmail.Tables[0]. if (dr != null) { textBox1.Text = dst.Rows[rwno][1]=textBox2. Code under DeleteBtn dst. } 14.Rows[rwno][2] = textBox3.Text.Text = dr[2].ToString().Rows[rwno][3] = textBox4. Code under SaveBtn ad. FirstBtn.Text.ToString().Show("Record Updated"). MessageBox.Rows[rwno][3]. Create a Function at class level private void ShowData() { textBox1. dst. DataRow dr = dst.InputBox("Enter Student Number".Rows.Text.Parse( Interaction. Code under UpdateBtn dst. "".Show("Data Saved"). 13.Tables[0].ToString().com 60 . 12.Show("Deleted SuccessFully"). Execute the applicaton MailId:ashvin. textBox2.Tables[0]. 200.//exectes the code under click of first button 10. dst.Tables[0].Text = dr[1].Text = dst.Show("Invalid Student Number").Tables[0].Tables[0].Text = dst. "Students"). MessageBox.Tables[0].Update(dst.Tables[0].Aprash Technologies +91-9953904262 FirstBtn.ToString().Rows[rwno][2]. MessageBox.ToString(). "Information".ToString().PerformClick(). textBox3.Delete(). textBox4.Rows[rwno][1].Rows[rwno].ToString().Find(row).Text = dr[3]. } 15. Code under FindBtn int row =int. } else { MessageBox. textBox3.ToString().

e.Tables [0].DataSource=ds.ToString ().DataSource=<data Table>. dataGridview1. Declaration of classes at class level SqlConnection con. the escepeciallty of this control was any changes performed on data of the controls reflects directly into the datatable to which it was bound.com 61 .g. SqlCommandBuilder cmb. 2. DataSet ds. <Control>. modifying or delete Command. SqlDataAdapter ad. Rows and Columns. 1. 2.e. We can bind the table directly to the control making use of the DataSource property.Aprash Technologies +91-9953904262 DataGridView:-It is a control used for displaying the data in the form of table i. Code under Form_Laod MailId:ashvin. DataControl DataSet Database GridView Datatable Database Tables Exercise: DataGridview 1.kumar01@gmail. DataGridview Control is updatable which will allow adding.

con). Find ():.Fee From Students".DataSource = ds. da.Initial Catalog=Data.Close().”Dept”). because an adapter can hold all the four commands only for single command. Note:-In this approach.CommandText=”Select * from Dept”. da.Update(ds. Using separate dataadapter for each table. Loading Multiple tables in Dataset If we want to load multiple tables into a Dataset. Note:-In this approach.Sname. _______________________________________________________________________________ Filtering Data Under Datasets If we want to filter the data present under the Datasets.kumar01@gmail.Fill (ds. Code under CloseButton this. ad.This method can be used for filtering the data based on primary Key column of the table. 4. 3. Example:da = new DataAdapter (“Select * from Emp “.”Emp”).//any name u can give as temp table bt pref as table name dataGridView1. "Students").Integrated Security=True.Tables[0]. MailId:ashvin.com 62 . cmb = new SqlCommandBuilder(ad). we can load any no of tables into the dataset in this case we can perform changes on the data & send back to database. we cannot perform changes on data on all the tables and send back to Databases.Pooling=False"). ds = new DataSet(). Code under SaveButton ad. ad = new SqlDataAdapter("select SNo. "Students").Fill (ds.Show("Transacion Succeed"). which can retrieve only single Record.Class. we have two different approaches using Single DataAdapter we can load any number of tables into a dataset by changing the select command after calling the Fill method & load tables. each table can be loaded from different sources. MessageBox.Fill(ds. con). we have two approaches  using Find ()  using DataView class.Aprash Technologies +91-9953904262 con = new SqlConnection("Data Source=localhost. da.SelectCommand.

com 63 . 2.RowFilter=”job =’Manager’. which can be used for filtering the data under DataTable & present it to the consumer. It was a class.kumar01@gmail. A view under database was a logical table used for filtering the data.Tables [0]. Using a DataView To use a DataView we follow the below process. which was modeled on the concept of View under Databases. Exercise: MailId:ashvin. which will act as mediator between the Data provider and Consumer. 1. Syntax:DataTable  DefaultView  DataView Example:DataView dv=ds. DataView also provides similar behavior like a View.DefaultView. Create a View by making use of default view property of DataTable class.Aprash Technologies +91-9953904262 DataView Class: This class can be used for filtering the data based on any column of the table and can retrieve multiple rows of Data.RowFilter=<condition> dv. Specify the condition to filter using the RowFilter property of the DataView dv.

Integrated Security=True. we can access either display or ValueMember in our code using SelectedItem and SeclectedValue properties.DataSource = dst.CommandText = "Select * from Emp". flag = true.ToString(). code under comboBox1.Aprash Technologies +91-9953904262 Declarations: SqlConnection con. DataView dv. comboBox1.SelectedIndex if (flag) { dv = dst.DefaultView.  None  Left  Right  Top  Bottom MailId:ashvin.Initial Catalog=Data.RowFilter = "DeptNo=" + comboBox1. ad. bool flag = false.we can bind multiple columns to the controls but only display member column will be visible to end users. 1.com 64 .ListBox controls.ValueMember = "DeptNo".con). Dock Property: It was a property a property available to all controls on the container. Code underForm_Load con = new SqlConnection("Data Source=localhost. } Note: Using DisplayMember & ValueMember properties of ComboBox. ad. "Dept"). comboBox1.Fill(dst. comboBox1. SqlDataAdapter ad. ad = new SqlDataAdapter("Select * from Dept". ad.DisplayMember = "DName". dv.kumar01@gmail.SelectCommand. "Emp").SelectedValue. dataGridView1. DataSet dst.Pooling=False"). which can be set with six different values.Tables["Emp"]. dst = new DataSet().Tables["Emp"].DataSource = dst.Fill(dst.Tables["Dept"].

Excercise: MailId:ashvin.kumar01@gmail. foreign key value changes to default value of the column. DataColumn refKeyColumn. SetNull –We can delete or update Reference key value of parent table but the corresponding child recordsforeign key values changes to Null. iv.<rule>.com 65 . Adding Rules Syntax <DataRelation>.These are the Properties-i. Cascade –we can delete or update reference key values in parent table .Relations.Aprash Technologies +91-9953904262  Fill Split: It was a container control. iii.Add(DataRelation dr).but the corresponding child records in child table will also be deleted & updated.It is by default Fill DataRelations It was a class used for establishing parent-child relationships between tables under dataset.childKeyConstraint. ii. The benefit of this control is the size of two panels can be adjusted at runtime . which comes with two panels left side and right. DataColumn pkColumn) After creating object of DataRelaton it has to be added explicitly to the DataSet under which tables were present using <Dataset>. DataRelation(string relName.DeleteRule=Rule. SetDefault –Same to SetNull. None -Cannot delete or update reference key value of parent table when corresponding child records exists in child table.but in this case the corresponding chil records.this is by Default applied in the case of DataSet. Now for deleting or updating reference key values in parent table there were some rules which comes into the picture separately for Delete and Update known as DeleteRules $ Updaterules.

"Dept").com 66 . Place DataGridView on each panel and set the Dock Property as Fill. DataRelation dr.SetNull.None. Place the Split container on it.Add(dr). "Emp").UpdateRule = Rule.DataSource = dst.SetDefault.ChildKeyConstraint. con).Tables["Dept"].Aprash Technologies +91-9953904262 1. ad1 = new SqlDataAdapter("Select * from Emp". //dr. dst.Relations.ChildKeyConstraint.DeleteRule = Rule. ad2.ChildKeyConstraint. dataGridView1. 2.Tables["Dept"].UpdateRule = Rule.Tables["Emp"]. Declarations SqlConnection con. dr. //dr.Initial Catalog=Data. dr. dst.ChildKeyConstraint. //dst.DeleteRule = Rule.ChildKeyConstraint.Fill(dst. //Setting Default Value. MailId:ashvin. 3. con).DefaultValue = 50. dst = new DataSet().Columns["DeptNo"]). //dr.kumar01@gmail. 4. Code under Form_Load con = new SqlConnection("Data Source=localhost.ad2.Pooling=False"). SqlDataAdapter ad1. DataSet dst.SetNull. ad2 = new SqlDataAdapter("Select * from Dept".Tables["Emp"].Fill(dst. dr = new DataRelation("Dept_Emp". dst.Columns["DeptNo"]. ad1.Integrated Security=True.None.UpdateRule = Rule.DeleteRule = Rule.Columns["DeptNo"].Cascade.ChildKeyConstraint. //dr.

To overcome the above drawback we can write stmnts under Database directly with an Object known as “Stored Procedure “& then call for Execution. Right click on stored procedure select add new stored Procedure MailId:ashvin. View Server Explorer 2. SQl Stmnts Call Sp Only Execution Parse + Execute Sp (SQl Stmnts) Stored procedure is Pre-Compiled block of code. as local copy changes are not advised in Application Environments. we write the SQl Statements in our application whenever we run an Application the statement will compile and execute in multiple times. it will increase the workload on database servers and may kill the performance of our application.e. Note:-Dataset only for retrieving data but not for performing manipulations. to return a value we use the clause out in oracle and output in SQL server. so that we can improve the performance of Database servers. y number) In SQl Server Create procedure Add (@x int. but modifications on a local copy may lead to Concurrency problems i. _________________________________________________________________________________ Drawback of Datasets A Dataset is a local copy of data which allows changes. Steps: 1. Q: How to create SP in Database through Visual Studio. Stored Procedure If we want to interact with databases.com 67 .DataSource = dst. which is ready for Execution will directly execute the Stmnts without parsing (compiling) each time. Examples:In Oracle: Create procedure Add (x number. change performed at allocation may not be reflecting to others immediately.Aprash Technologies +91-9953904262 dataGridView2.Tables["Emp"].kumar01@gmail. @ y int) A sp (stored procedure) can return values.

SName. Note:- If the SP contains DML Stmnts in it. E.kumar01@gmail. so create an object of Command class by passing the SP name as argument. 2.Aprash Technologies +91-9953904262 3. 1. Command cmd =new Command (“Select_Students”.StoredProcedure.Class. call the ExecuteNonQuery() method on command to Execute SP.com 68 . Set the Command Type property of Command as SP because by default it can execute SqlStmnts only.Fee from Students End Calling a stored procedure from .Write the Stored procedure Example: CREATE PROCEDURE Select_Students AS Begin Select SNo. Command class is responsible for calling SP. create the object of Command as argument and then call the Fill() method . so that Commands Executes the SP MailId:ashvin. after setting the property SP’s can be called.Net Application.g.If it contains SELECT statement int it and if we want to load the data into dataset then.CommandType = CommandType. Con). cmd.

Aprash Technologies +91-9953904262 and Adapter loads the Data into Exercise: 1. cmd. SqlDataAdapter ad.Pooling=False").com 69 . dst = new DataSet().kumar01@gmail. DataSet dst. SqlCommand cmd. Declarations: SqlConnection con. "Dept").StoredProcedure.Integrated Security=True.CommandType = CommandType. cmd = new SqlCommand("Select_Students".Initial Catalog=Data. Drag gridview on the form 3. 2.Fill(dst. ad = new SqlDataAdapter(cmd).con). MailId:ashvin. Code under Form_Load con = new SqlConnection("Data Source=localhost. ad.

2.kumar01@gmail. audio or video data also on database but only in binary Format. we use image/varbinary data type in SQLserver (max 2GB) and BLOB data type in Oracle (max 4 GB) Binary Large Object.Picture from Students Where SNo=@Sno and Status=1 End create procedure Ins_Upd_Studsents(@SNo int.Aprash Technologies +91-9953904262 dataGridView1.@Photo Image) As MailId:ashvin.@Fee Money.Tables[0].Fee. To store an image first it should be converted into Binary Data (Byte Array) and then store in database.Fee from Students where status=1 Else Select SName. Exercise: Picture Box Create Procedures _______________________________________________________________ Alter PROCEDURE Select_Students(@Sno int=null) AS Begin if @Sno is null Select SNo. 1.com 70 .Class.DataSource = dst.@SName varchar(20).@Class int. In this database. 3. We can store images.Class. _____________________________________________________________ Storing an Image on Database.SName.

Text). cmd.Read(data.Parameters.Text).@Sname. cmd. cmd = new SqlCommand().Length].Text). textBox2. cmd. Under Form_Load con = new SqlConnection("Data Source=localhost.SName.Position = 0.AddWithValue("Photo". DataSet dst.SqlClient. Declarations SqlConnection con.Class=@Class.Class. cmd.AddWithValue("@SNo".CommandText = "Ins_Upd_Studsents". con. byte[] data = new byte[ms.Fee=@Fee. pictureBox1.Parameters.Connection = con.kumar01@gmail.Clear(). cmd.Integrated Security=True. textBox3. cmd. ms. MemoryStream ms.Parameters.Open(). MailId:ashvin.Parameters.AddWithValue("@SName". data). SqlCommand cmd.ToInt32(ms.@Fee.StoredProcedure. 0. textBox4.Aprash Technologies +91-9953904262 Begin If Not Exists (Select SNo From Students Where SNo=@Sno and Status=1) Insert into Students ( SNo.Picture)Values(@SNo. ms. SqlDataAdapter ad.CommandType = CommandType. using System. using System. ImageFormat.Initial Catalog=Data.Parameters.Jpeg).Image.Text).@Photo) Else Update Students Set SName=@Sname.AddWithValue("@Fee". cmd.Fee. textBox1.Save(ms. //Converting Image To Byte[] ms = new MemoryStream(). cmd.Imaging.Data.IO.Length)).Pooling=False").Parameters.Picture=@Photo Where SNo=@Sno End Namespaces using System. Under InserBtn try { cmd. Convert.@Class.Drawing.AddWithValue("@Class".com 71 .

} MailId:ashvin.Show(ex.ExecuteNonQuery().com 72 . cmd.kumar01@gmail. MessageBox.Open().Aprash Technologies +91-9953904262 cmd. cmd.Parameters. MessageBox. } under DeleteBtn try { cmd. } catch (Exception ex) { MessageBox. textBox1.Message).Message).Text). con.Show("Executed"). } finally { con.Parameters. } catch (Exception ex) { MessageBox. } finally { con.Show("Executed").Show(ex.Close(). button2.PerformClick().ExecuteNonQuery().AddWithValue("@SNo".Clear().Close().

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->