LECTUR#01 Visualprogramming31-10-2006
LECTUR#01 Visualprogramming31-10-2006
C# . Net
Spring 2006
Visual Programming
Lecture 02-03-04-05-06-07-08-09:
using C#
Amjad Mehmood
Lec.IIT 1
.NET Framework and the
Common Language Runtime
• .NET Framework
– Heart of .NET strategy
» Manages and executes applications and Web services
» Provides security, memory management and other programming
capabilities
– Includes Framework class library (FCL)
» Pre-packaged classes ready for reuse
» Used by any .NET language
– Details contained in Common Language Specification
(CLS)
» Submitted to European Computer Manufacturers Association to
make the framework easily converted to other platforms
– Executes programs by Common Language Runtime (CLR)
Amjad Mehmood
Lec.IIT 2
.NET Framework and the
Common Language Runtime (II)
• Common Language Runtime (CLR)
– Central part of framework
» Executes Visual Basic .NET programs
– Compilation process
» Two compilations take place
» Programs compiled to Microsoft Intermediate Language
(MSIL)
Amjad Mehmood
Lec.IIT 3
.NET Framework and the
Common Language Runtime (III)
• Why two compilations?
– Platform independence
» .NET Framework can be installed on different platforms
» Execute .NET programs without any modifications to code
– Language independence
» .NET programs not tied to particular language
» Programs may consist of several .NET-compliant languages
» Old and new components can be integrated
Amjad Mehmood
Lec.IIT 4
The Microsoft .Net Framework Architecture
Micosoft.Net Famework
CLR,Assemblies,Security
Amjad Mehmood
Lec.IIT 5
The .NET Framework class library
Amjad Mehmood
Lec.IIT 6
The JIT process and verification.
• When code is JIT compiled, the common language runtime checks
to make sure that the IL is correct.
• Rules common language runtime uses for verification are
• Common Language Specification (CLS)
• Common Type System (CTS).
Amjad Mehmood
Lec.IIT 7
Namespaces
• Logical grouping rather than physical groupings
• namespace Wrox
• {
• namespace ProCSharp
• {
• namespace Basics
• {
• class namespaceExample
• {
• // Code for the class here...
• }}}}
Amjad Mehmood
Lec.IIT 8
Namespaces Cont…
Amjad Mehmood
Lec.IIT 9
The using Statement
• say classes called NamespaceExample exist both in the
Wrox.ProCSharp.Basics and Wrox.ProCSharp.OOP namespaces. If we
then create a class called Test in the Wrox.ProCSharp namespace, and
instantiate one of the NamespaceExample classes in this class, we need to
specify which of these two classes we're talking about:
• using Wrox.ProCSharp;
• class Test
• {
• public static int Main()
• {
• Basics.NamespaceExample NSEx = new
Basics.NamespaceExample();
• return 0;
• }
• }
Amjad Mehmood
Lec.IIT 11
Console I/O
• Console.Write() - Writes the specified value to the console window
• Console.WriteLine() - Which does the same, but adds a new line character
at the end of the output.
• Example
• The following code lets the user input a line of text, and displays the first
character:
• int x = Console.Read();
• Console.WriteLine((char)x); This is similar, but returns the entire line of
text as a string:
• The following code lets the user input a line of text, and displays the first
character:
• string s = Console.ReadLine();
• Console.WriteLine(s);
Amjad Mehmood
Lec.IIT 12
Console I/O Cont…
• int i = 940;
• int j = 73;
• Console.WriteLine(" {0,4}\n+{1,4}\n ----\n {2,4}", i, j, i + j);
The result of this is:
• 940 + 73 ---- 1013
• StringDescription
• C Local currency format
• .D Decimal format. Converts an integer to base 10, and pads with leading zeros if a precision
specifier is given.
• E Scientific (exponential) format. The precision specifier sets the number of decimal places (6 by
default). The case of the format string (e or E) determines the case of the exponential symbol.
• F Fixed-point format; the precision specifier controls the number of decimal places. Zero is
acceptable.G General format. Uses E or F formatting, depending on which is the most compact.
• N Number format. Formats the number with commas as thousands separators, for example
32,767.44
• P Percent format.
• X Hexadecimal format. The precision specifier can be used to pad with leading zeros
Amjad Mehmood
Lec.IIT 13
• int i = 940;
• int j = 73;
• Console.WriteLine(" {0,4}\n+{1,4}\n ----\n {2,4}", i, j, i + j);
• The result of this is:
• 940
• + 73
----
1013
Example :02
• decimal i = 940.23m;
• decimal j = 73.7m;
• Console.WriteLine(" {0,9:C2}\n+{1,9:C2}\n ---------\n {2,9:C2}", i, j, i + j);
• The output of this in the United States is:
• $940.23
• + $73.70
• ---------
• $1,013.93
Amjad Mehmood
Lec.IIT 14
Our First C# Program
• using System;
• namespace Wrox.ProCSharp.Basics
• {
• class MyFirstCSharpClass
• {
• static void Main()
• {
• Console.WriteLine("This isn't at all like Java!");
• return;
• }
• }
• }
Amjad Mehmood
Lec.IIT 15
Execution Environment
• [C#/IL/CLR] [Java/Byte-Code/JVM]
Source MSIL
.Net Compiler
Code
Running
CLR
Program
Amjad Mehmood
Lec.IIT 16
MSIL
Amjad Mehmood
Lec.IIT 17
JIT Compilation
Amjad Mehmood
Lec.IIT 18
Quiz# 01
Time Allowed:10 Minutes
Marks:10
Amjad Mehmood
Lec.IIT 19
using System;
namespace Shape
{
class cone
{
float height, radius ;
public cone ( float h, float r )
{
height = h ;
radius = r ;
}
public void displaydata( )
{
Console.WriteLine ( "Height = " + height ) ;
Console.WriteLine ( "Radius = " + radius ) ;
}
public void volume( )
{
float v ;
v = ( 1 / 3.0f ) * 3.14f * radius * radius * height ;
Console.WriteLine ( "\nVolume = " + v ) ;
} Amjad Mehmood
} Lec.IIT 20
class Class1
{
static void Main ( string [ ] args )
{
cone c1 = new cone ( 10.0f, 3.5f ) ;
cone c2 = new cone ( 20.0f, 6.2f ) ;
c1.displaydata( ) ;
c1.volume( ) ;
c2.displaydata( ) ;
c2.volume( ) ;
}
}
}
Amjad Mehmood
Lec.IIT 21
using System;
namespace StaticDemo
{
class sample
{
private static int count ;
public sample( )
{
count++ ;
}
Amjad Mehmood
Lec.IIT 22
class Class1
{
static void Main ( string [ ] args )
{
sample s1 = new sample( ) ;
sample.showcount( ) ;
Amjad Mehmood
Lec.IIT 23
using System;
namespace StaticDemo
{
class sample
{
public static int y;
public static int m ;
public static int d ;
static sample( )
{
DateTime dt = DateTime.Now ;
y = dt.Year ;
m = dt.Month ;
d = dt.Day ;
}
Amjad Mehmood
Lec.IIT 25
Scope clashes for local variable
• using System;
• namespace Wrox.ProCSharp.Basics
• {
• public class ScopeTest
• {
• public static int Main()
• {
• for (int i = 0; i < 10; i++)
• {
• Console.WriteLine(i); } // i goes out of scope here We can declare a variable named
i again, because // there's no other variable with that name in scope
• for (int i = 9; i >= 0; i--)
• {
• Console.WriteLine(i);
• } // i goes out of scope here
• return 0;
• }
• }
• }
Amjad Mehmood
Lec.IIT 26
If we try to compile this, we'll get an error:
Amjad Mehmood
Lec.IIT 27
Scope clashes Cont…
• using System;
• namespace Wrox.ProCSharp.Basics
• {
• class ScopeTest2
• {
• static int j = 20;
• public static void Main()
• {
• int j = 30;
• Console.WriteLine(j);
• return;
• }
• }
• }
• C# makes a fundamental distinction between variables that are declared at
the type level (fields), and variables declared within methods (local
variables): Main() method hides the class-level variable with the same name, so when we
run this code, the number 30 will be displayed.
Amjad Mehmood
Lec.IIT 28
Scope clashes Cont…
• ...
• public static void Main()
• {
• int j = 30;
• Console.WriteLine(ScopeTest2.j);
• }
• ...
Amjad Mehmood
Lec.IIT 29
Constants
Amjad Mehmood
Lec.IIT 30
Predefined Data Types
• Value Types
• Stores the value directly
• stored in different places in memory; value types in an area known as the
stack
• Int, char, double
• Reference Types
• Stores a reference to the value.
• Reference types are stored in an area known as the managed heap
• Class
• Interface
• Delegates
• Object
• String
Amjad Mehmood
Lec.IIT 31
Predefined Data Types Cont…
• The basic predefined types recognized by C# are not intrinsic (native) to the language but part
of the .NET Framework
• Name CTS Type Description Range (min:max)
• sbyte System.SByte 8-bit signed integer -128:127 (-27:27-1)
• short System.Int16 16-bit signed integer -32,768:32,767 (-215:215-1)
• int System.Int32 32-bit signed integer -2,147,483,648:2,147,483,647 (-231:231-1)
• decimal System.Decimal 128-bit high precision decimal notation 28±1.0 × 10-28 to ±7.9 × 1028
• bool System.Boolean true or false
Amjad Mehmood
Lec.IIT 32
Diagram description
Amjad Mehmood
Lec.IIT 33
Examples of Val and Ref Type
• using System;
• namespace cSharp_ValueReference
• {
• class Class1
• {
• static public int x;
• [STAThread]
• static void Main(string[] args)
• {
• x=4; int y; y = x; x=0; //
• Console.WriteLine(x);
• Console.WriteLine(y);
• Class2 Class2 ref1 = new Class2();
Amjad Mehmood
• ref1.refValue=5; Lec.IIT 34
Example Val and Ref Type Cont…
Amjad Mehmood
Lec.IIT 36
Interface
• Interface interfaceCar
• {
• Void Move();
• Void Stop();
• }
• Class Car1:interfaceCar
• {
• Void Move()
• {
• //wirte code
• }
• Void Stop()
• {
• //write code here
• }
• }
Amjad Mehmood
Lec.IIT 37
Delegate
• namespace Example
• {
• using System;
• /// <summary>
• /// Delegatge
• /// </summary>
• delegate void FirstDelegate();//declare the delegate
• public class Delegate1
• {
• public static void hello()
• {
• Console.WriteLine("Hello Delegate");
• }
• public static int Main(string[] args)
• {
• FirstDelegate fd=new FirstDelegate(hello);// Instantiation
• fd();// invocation of the delgate
• return 0;
• }
• }
Amjad Mehmood
• } Lec.IIT 38
Object
Amjad Mehmood
Lec.IIT 39
String
Amjad Mehmood
Lec.IIT 40
Conversion of the Type
• Implicit conversion
• Explicit conversion via casting
• Use of a conversion method
Amjad Mehmood
Lec.IIT 41
Implicit conversion
• using System;
• public class testConversion1
• {
• public static void Main()
• {
• int i=7;
• long l=i;
• Console.WriteLine("The long is converted to int {0}",i);
• }
• }
Amjad Mehmood
Lec.IIT 42
Implicit conversion
• double F;
• int X = 2;
• F = X; // implicit conversion
Amjad Mehmood
Lec.IIT 43
Explicit conversion via casting
• using System;
• public class testConversion1
• {
• public static void Main()
• {
• long l=2.0;
• int i=l;
• Console.WriteLine("The long is converted to int {0}",i);
• }
• }
Amjad Mehmood
Lec.IIT 44
Explicit conversion via casting
• {
• byte b=90,c=45;
• byte d=b+c;
• Console.writeLine(“result is{0}”, d);
• }
• Solution
• byte d=(byte) b+c;
• Console.writeLine(“result is{0}”, d);
• Error messege
Amjad Mehmood
Lec.IIT 45
Use of a conversion method
• Sytem.Convert.ToString
• Sytem.Convert.ToInt
• Sytem.Convert.ToBoolean
• string s = i.ToString();
Amjad Mehmood
Lec.IIT 46
Boxing and Unboxing
• When a value type is converted into a reference type then it is
known as boxing
• Int b=145;
• Object o=b;//Boxing (implicit converted into object)
• Int j=(int) o;//UnBoxing(explicitly converted into int)
• Console.writeLine(“result is{0}”, j);
Amjad Mehmood
Lec.IIT 47
Modifiers in C#
Amjad Mehmood
Lec.IIT 48
•
internal
using System;
• internal class myFirst
• {
• public void hello()
• {
• Console.WriteLine("Hello C#");
• }
• }
• public class Mainclass
• {
• public static void Main()
• {
• myFirst m=new myFirst();
• m.hello();
• }
• }
Amjad Mehmood
Lec.IIT 49
Other modifiers are
• Abstract
• Sealed
• Virtual
• New
• Override
• Static
Amjad Mehmood
Lec.IIT 50
Using Abstract Classes and Methods
• using System;
• abstract class abshello
• {
• protected string s = "";
• public abstract void callhello();
• }
• class mainclass
• {
• public static void Main()
• {
• absDerived ad =new absDerived();
• ad.callhello();
• }
• }
Amjad Mehmood
Lec.IIT 51
• using System;
• abstract class abshello
• {
• protected string s = "";
• public abstract void callhello();
• public abstract void sayhello();// not implemented in the derived
• //class.
• }
• class mainclass
• {
• public static void Main()
• {
• absDerived ad =new absDerived();
• ad.callhello();
• }
• }
Amjad Mehmood
Lec.IIT 52
There are a few points to note about abstract
classes and methods:
Amjad Mehmood
Lec.IIT 53
Declaring Sealed Classes and Methods
• Sealed Classes
• Sealed Methods
• cannot override a sealed method in a derived class. may declare a sealed method
in a non-sealed class, but that sealed method cannot be overridden in a derived
class.
• e.g sealed public override void Accelerate( )
Amjad Mehmood
Lec.IIT 54
Sealed Classes
• using System;
•
class absDerived : abshello // Error
• {
• public override void callhello()
• {
• s="Hello C#";
• Console.WriteLine("{0}",s);
• }
• }
• class mainclass
• {
• public static void Main()
• {
• absDerived ad =new absDerived();
• ad.callhello();
•
Amjad Mehmood
}
Lec.IIT 55
Override
• using System;
• class abshello
• {
• protected string s = "";
• public void callhello()
• {
• s="No Hello to C#";
• }
• }
• class mainclass
• {
• public static void Main()
• {
• Amjad
absDerived ad =new Mehmood
absDerived();
• ad.callhello(); Lec.IIT 56
• using System; Static
• class absDerived {
• string s="Hello C#";
• public static void callhello()
• {
• Console.WriteLine("{0}",s);
• }
• public void normal()
• {
• Console.WriteLine("{0}",s);
• }
• }
• class mainclass
• {
• public static void Main()
• {
• absDerived.callhello();
• absDerived a=new absDerived();
• a.normal();
• }
Amjad Mehmood
• } Lec.IIT 57
Virtual
• using System;
• class shibi
• {
• public void hand() { Console.WriteLine("shibi's hand"); }
• public virtual void eye() { Console.WriteLine("shibi's eye"); }
• }
• class myson: shibi
• {
• public void hand() { Console.WriteLine("myson's hand"); }
• public override void eye() { Console.WriteLine("myson's eye"); }
• }
• class Test
• {
• static void Main() {
• shibi s=new shibi();
• myson m = s;
• s.hand();
• m.hand();
• s.eye();
• m.eye();
• }
• }
• whenever you call the virtual method it will search for the overriden method in the deri
Amjad Mehmood
Lec.IIT 58
IL Disassembler (ILDASM)
• Go to Start—visual studio commamd prompt and
type ildasm.exe Microsoft .NET Framework IL
Disassembler (ILDASM). (Debug)
Amjad Mehmood
Lec.IIT 59
Amjad Mehmood
Lec.IIT 60
Flow Control
• Conditional Statements
• The if Statement
• if (condition)
• statement(s)
• else
• statement(s)
• bool isZero;
• if (i == 0)
• {
• isZero = true;
• Console.WriteLine("i is Zero");
• }
• else
• {
• isZero = false;
• Console.WriteLine("i is Non-zero");
• }
Amjad Mehmood
Lec.IIT 61
•
Else-if
using System;
• namespace
• Wrox.ProCSharp.Basics
• {
• class MainEntryPoint
• {
• static void Main(string[] args)
• {
• Console.WriteLine("Type in a string");
• string input;
• input = Console.ReadLine();
• if (input == "")
• {
• Console.WriteLine("You typed in an empty string"); }
• else if (input.Length < 5)
• {
• Console.WriteLine("The string had less than 5 characters");
• }
• else if (input.Length < 10)
• {
• Console.WriteLine("The string had at least 5 but less than 10 characters"); }
Console.WriteLine("The string was " + input); } } }
Amjad Mehmood
Lec.IIT 62
The switch Statement
• switch (integerA)
• {
• case 1:
• Console.WriteLine("integerA =1"); break;
• case 2:
• Console.WriteLine("integerA =2"); break;
• case 3:
• Console.WriteLine("integerA =3"); break;
• default:
• Console.WriteLine("integerA is not 1,2, or 3"); break;
• }
Amjad Mehmood
Lec.IIT 63
Loops
• The for Loop
• The syntax is:
• for (initializer; condition; iterator) statement(s)
•
• static void Main(string[] args)
• {
• // This loop iterates through rows...
• for (int i = 0; i < 100; i+=10)
• {
• // This loop iterates through columns...
• for (int j = i; j < i + 10; j++)
• {
• Console.Write(" " + j);
• }
• Console.WriteLine();
• }
• }
Amjad Mehmood
Lec.IIT 64
The while Loop
• while(condition)
• statement(s);
• bool condition;
• Do
• {
• // this loop will at least execute once, even if
condition = CheckCondition();
• } while (condition);
Amjad Mehmood
Lec.IIT 66
The foreach Loop
Amjad Mehmood
Lec.IIT 67
Jump Statements
Amjad Mehmood
Lec.IIT 68
Statements in branching
Amjad Mehmood
Lec.IIT 69
Arrays
Types of arrays
Two main types
One Dimensional Arrays
Multidimensional Arrays
Amjad Mehmood
Lec.IIT 71
Arrays
• The declaration
• int[ ] c = new int[ 12 ];
Amjad Mehmood
Lec.IIT 72
Allocating an Array and Initializing Its Elements
• class InitArray
• {
• // main entry point for application
• static void Main( string[] args )
• {
• string output = "";
• int[] x; // declare reference to an array
• x = new int[ 10 ]; // dynamically allocate array and set
• // default values
• int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
• const int ARRAY_SIZE = 10; // named constant
• int[] z; // reference to int array
Amjad Mehmood
Lec.IIT 73
Allocating an Array and Initializing Its Elements
• MessageBox.Show( output,
• "Initializing an array of int values",
• MessageBoxButtons.OK, MessageBoxIcon.Information );
• } // end Main
• } // end class InitArray Amjad Mehmood
Lec.IIT 74
Output …
Amjad Mehmood
Lec.IIT 75
Totaling the Elements of an Array
• class SumArray
• {
• // main entry point for application
• static void Main( string[] args )
• {
• int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
• int total = 0;
• for ( int i = 0; i < a.Length; i++ )
• total += a[ i ];
• MessageBox.Show( "Total of array elements: " + total,
• "Sum the elements of an array",
• MessageBoxButtons.OK, MessageBoxIcon.Information );
• } // end Main
• } // end class SumArray
Amjad Mehmood
Lec.IIT 76
Passing Arrays to Methods
Amjad Mehmood
Lec.IIT 77
• private void showOutputButton_Click( object sender,
• System.EventArgs e )
• {
• int[] a = { 1, 2, 3, 4, 5 };
• outputLabel.Text = "Effects of passing entire array " +
1. Rectangular array
In rectangular arrays every row of the array is of the same length.
OR
All the rows have the same numbers of elements
EXAMPLE
Int [ , ] arr1=new int [ , ]{{ 3,5,7,9},{11,13,15,17}};
OR
Int [ , ] arr1={{2,4,6,8,},{10,12,14,16}};
Amjad Mehmood
Lec.IIT 80
DIAGRAM OF RECTANGULAR ARRAYS
Stack
Heap
arr1
3 5 7 9
11 13 15 17
Amjad Mehmood
Lec.IIT 81
• using System ;
• class rectarray
• {
• static void Main ( string[ ] args )
• {
• int [ , ] arr1 = new int [ 2, 3 ] { { 1, 2, 3 }, { 4, 5, 6 } } ;
• int [ , ] arr2 = new int [ 2, 3 ] ;
Stack Heap
arr1[0] 3 5 7 9
arr1[1] 11 13
arr1
Amjad Mehmood
Lec.IIT 84
EXAMPLE
• using System ;
• class jaggedarray
• {
• static void Main ( string[ ] args )
• {
• int [ ][ ] arr1 = new int [ 2 ] [ ] ;
• arr1 [ 0 ] = new int [ 3 ] { 1, 2, 3 } ;
• arr1 [ 1 ] = new int [ 2 ] { 4, 5 } ;
• Console.WriteLine ( "Elements of arr1: " ) ;
• for ( int i = 0 ; i < arr1.Length ; i++ )
• {
• for ( int j = 0 ; j < arr1[ i ].Length ; j++ )
• Console.Write ( arr1 [ i ] [ j ] ) ;
• Console.WriteLine( ) ;
• }
• }
• }
Amjad Mehmood
Lec.IIT 85
The System.Array Type
Amjad Mehmood
Lec.IIT 86
EXAMPLE
• using System ;
• class onedarray
• {
• static void Main ( string[ ] args )
• {
• int[ ] arr1 = new int [ 5 ] { 1, 4, 7, 8, 9 } ;
• int[ ] arr2 = new int [ 10 ] ;
• arr1.CopyTo ( arr2, 0 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;
• arr2.SetValue ( 5, 0 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;
Amjad Mehmood
Lec.IIT 87
• Array.Copy ( arr1, 2, arr2, 6, 2 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;
• Array.Reverse ( arr2 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " ") ;
• Console.WriteLine( ) ;
• Array.Sort ( arr2 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;
• Array.Clear ( arr2, 3, 3 ) ;
• Console.WriteLine ( "Elements of arr2: " ) ;
• foreach ( int i in arr2 )
• Console.Write ( i + " " ) ;
• Console.WriteLine( ) ;
• }
• }
Amjad Mehmood
Lec.IIT 88
String
• The string is a data type in C# holds the text enclosed in double quotes.
• String is the alias of System. String
• Instance of the string type represent Unicode character strings
EXAMPLE
string s=“Hello”;
• using System;
• namespace sample
• {
• class Class1
• {
• static void Main ( string[ ] args )
• {
• string s1 = "Good Morning" ;
• string s2 ;
• s2 = s1 ;
• s1 = "Wake Up" ;
• Console.WriteLine ( s1 ) ;
• Console.WriteLine ( s2 ) ;
•
• } OUTPUT
• } Wake up
• } Good Morning
Press any key to continue
Amjad Mehmood
Lec.IIT 89
@ Symbol
• C# support two types of string variables quoted and @- quoted.
• If we do not want the compiler to process escape sequences then we use @-quoted string a
prefix
• @ -qouted string simplifies the expression path names
EXAMPLE
string s2=@ “C:\Articles\text.txt”; equilent to
string s2= “C:\\Articles\\text.txt”;
Escape Sequence
Escape sequence print out the tabs
EXAMPLE
String s1=“hi \t there”;
OUTPUT
hi there
Amjad Mehmood
Lec.IIT 90
System. String type
System. String class performs various operations on string data type
EXAMPLE
• using System ;
• namespace sample
• {
• class Class1
• {
• static void Main ( string[ ] args )
• {
• string s1 = "kicit" ;
• string s2 = "Nagpur" ;
• Console.WriteLine ( "Char at 3rd position: " + s1 [ 2 ] ) ;
• s3 = string.Copy ( s2 ) ;
• Console.WriteLine ( s3 ) ;
• int c = s2.CompareTo ( s3 ) ;
• if ( c < 0 )
• Console.WriteLine ( "s2 is less than s3" ) ;
Amjad Mehmood
•
Lec.IIT 91
• if ( c == 0 )
• Console.WriteLine ( "s2 is equal to s3" ) ;
• if ( c > 0 )
• Console.WriteLine ( "s2 is greater than s3" ) ;
• if ( s1 == s3 )
• Console.WriteLine ( "s1 is equal to s3" ) ;
• else
• Console.WriteLine ( "s1 is not equal to s3" ) ;
• s3 = s1.ToUpper( ) ;
• Console.WriteLine ( s3 ) ;
• s3 = s2.Insert ( 6, "Mumbai" ) ;
• Console.WriteLine ( s3 ) ;
• s3 = s2.Remove ( 0, 1 ) ;
• Console.WriteLine ( s3 ) ;
• }
• } Amjad Mehmood
• } Lec.IIT 92
Parsing String to other data types
• Console.ReadLine() can take input as a string from the user.
• We need to type cast string for mathematical operations .
• For this we need Parse() method to type cast string into other data type .
• using System ;
• namespace sample
• {
• class Class1
• {
• static void Main ( string[ ] args )
• {
• Console.WriteLine ( "Enter an integer: " ) ;
• string s = Console.ReadLine( ) ;
• int i = int.Parse ( s ) ;
• float t = f + i ;
• Console.WriteLine ( t ) ;
• }
• }
Amjad Mehmood
• }
Lec.IIT 93
Windows Form Controls
Amjad Mehmood
Lec.IIT 94
Windows Form Controls
Amjad Mehmood
Lec.IIT 95
Common Windows Form Controls
• Buttons
• TextBoxes
• Labels
• ComboBox
• Radio buttons
• CheckBoxes
• PictureBoxes
• Toolbars etc
Amjad Mehmood
Lec.IIT 96
Amjad Mehmood
Lec.IIT 97
• All Controls have three things in common
All have a set of properties
All have a set of events to which the control can respond
All have methods (Functions) that can be used for performing
different operations related to that control.
Properties:
Properties are the characteristics that can
describe a control and can be muted at runtime.
e.g Name of control,text,backcolr,forecolor
etc.
Amjad Mehmood
Lec.IIT 98
Common Properties
Amjad Mehmood
Lec.IIT 99
Event
Amjad Mehmood
Lec.IIT 100
• An event handler may be of two types
1. Local
2. Global
Local event handlers are executed when an event at
application level is raised and there is no hook
installed for it.
Hook: A hook is a function that is executed before the
event reaches to your application. e.g. stopping an
application from running before it starts.
Amjad Mehmood
Lec.IIT 101
• Global event handlers (HOOKS):
are executed at O.S level. For example if we write a
Hook for a click event. Then it will be executed each
time a click occurs even if it is out of your
application.
Amjad Mehmood
Lec.IIT 102
Event-Handling Model
Amjad Mehmood
Lec.IIT 103
Common Controls Events
Amjad Mehmood
Lec.IIT 104
Methods
Amjad Mehmood
Lec.IIT 105
Amjad Mehmood
Lec.IIT 106
Amjad Mehmood
Lec.IIT 107
Amjad Mehmood
Lec.IIT 108
Amjad Mehmood
Lec.IIT 109
Amjad Mehmood
Lec.IIT 110
Amjad Mehmood
Lec.IIT 111
Amjad Mehmood
Lec.IIT 112
Simple application
Amjad Mehmood
Lec.IIT 113
Amjad Mehmood
Lec.IIT 114
Amjad Mehmood
Lec.IIT 115
Amjad Mehmood
Lec.IIT 116
Amjad Mehmood
Lec.IIT 117
Amjad Mehmood
Lec.IIT 118
Amjad Mehmood
Lec.IIT 119
Amjad Mehmood
Lec.IIT 120
Amjad Mehmood
Lec.IIT 121
Amjad Mehmood
Lec.IIT 122
Amjad Mehmood
Lec.IIT 123
Amjad Mehmood
Lec.IIT 124
Amjad Mehmood
Lec.IIT 125
Amjad Mehmood
Lec.IIT 126
Amjad Mehmood
Lec.IIT 127
Amjad Mehmood
Lec.IIT 128
Amjad Mehmood
Lec.IIT 129
Use of Message Box
Amjad Mehmood
Lec.IIT 130
Simple Program: Adding Integers
Amjad Mehmood
Lec.IIT 131
Amjad Mehmood
Lec.IIT 132
Submit Button Code
• string info="Name: "+txtName.Text+"\nFather Name:"+txtFName.Text;
• if(rdMale.Checked)
•
» info=info+"\nGeneder"+rdMale.Text;
•
• else
• info=info+"\nGender:"+rdFemale.Text;
info=info+"\n Hobbies:\n";
•
• if(ChckCricket.Checked)
• info=info+ChckCricket.Text+"\n";
•
• if(chckHocky.Checked)
• info=info+chckHocky.Text+"\n";
•
• if(chckFootball.Checked)
• info=info+chckFootball.Text+"\n";
• if(chckTennis.Checked)
• info=info+chckTennis.Text+"\n";
• info=info+"\nJob Title: "+Title.Text;
• info=info+"\nSalary: "+combSalary.Text;
MessageBox.Show(info);
Amjad Mehmood
Lec.IIT 133
Quiz# 02
Time Allowed:10 Minutes
Marks:10
Amjad Mehmood
Lec.IIT 135
Declaring Methods
• {
• // Method body
• }
Amjad Mehmood
Lec.IIT 136
Invoking Methods
• using System;
• namespace Wrox.ProCSharp.Basics
• {
• class MainEntryPoint
• {
• static void Main()
• {
• // Try calling some static functions
• Console.WriteLine("Pi is " + MathTest.GetPi());
• int x = MathTest.GetSquareOf(5);
• Console.WriteLine("Square of 5 is " + x);
• // Instantiate at MathTest object
• MathTest math = new MathTest(); // this is C#'s way of //
• instantiating a reference type
• // Call non-static methods math.value = 30;
• Console.WriteLine( "Value field of math variable contains " + math.value);
• Console.WriteLine("Square of 30 is " + math.GetSquare());
• }
• }
Amjad Mehmood
Lec.IIT 137
Invoking Methods
• // Define a class named MathTest on which we will call a method
• class MathTest
• {
• public int value;
• public int GetSquare()
• {
• return value*value;
• }
• public static int GetSquareOf(int x)
• { return x*x; }
• public static double GetPi()
• {
• return 3.14159;
• }
• }
• }
Amjad Mehmood
Lec.IIT 138
Passing Parameters to Methods
• namespace Wrox.ProCSharp.Basics
• {
• class ParameterTest
• {
• static void SomeFunction(int[] ints, int i)
• {
• ints[0] = 100; i = 100;
• }
• public static int Main()
• {
• int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]);
• Console.WriteLine("Calling SomeFunction..."); // After this method returns, ints will be changed,
• // but i will not SomeFunction(ints, i);
• Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]);
• return 0;
• }
• }
• }
Amjad Mehmood
Lec.IIT 139
Passing Parameters to Methods
• namespace Wrox.ProCSharp.Basics
ParameterTest
• {
• class ParameterTest i=0
• {
•
•
static void SomeFunction(int[] ints, int i)
{
ints[0] = 0
• ints[0] = 100; i = 100; }
• public static int Main() Calling SomeFunction...
•
•
{ i=0
int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values
• Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]); ints[0] = 100
• Console.WriteLine("Calling SomeFunction..."); // After this method returns, ints
• will be changed, // but i will not
• SomeFunction(ints, i);
• Console.WriteLine("i = " + i);
• Console.WriteLine("ints[0] = " + ints[0]);
• return 0; } } }
Amjad Mehmood
Lec.IIT 140
reference-type behavior
Amjad Mehmood
Lec.IIT 141
The out Keyword
• out parameter isn't assigned a value within the body of the function, the
method won't compile.
• static void SomeFunction(out int i)
• {
• i = 100;
• }
• public static int Main()
• {
• int i; // note how i is declared but not initialized
• SomeFunction(out i);
• Console.WriteLine(i);
• return 0;
• }
Amjad Mehmood
Lec.IIT 142
Array
• int[] integers;
• To initialize the array with specific dimensions, we
can use the new keyword, giving the size in the
square brackets after the type name:
• // Create a new array of 32
• ints int[] integers = new int[32];
• integers[31] = 432;
Amjad Mehmood
Lec.IIT 143
Array
Amjad Mehmood
Lec.IIT 144
unchecked
• Working with Arrays
• Arrays
• int arrayLength = integers.Length;
• using the static Array.Sort() method:
Array.Sort(myArray);
System.Array.Sort() method
• using the static Reverse() method:
• Array.Reverse(myArray);
• string[] artists = {"Leonardo", "Monet", "Van Gogh", "Klee"};
Array.Sort(artists);
• Array.Reverse(artists);
• foreach (string name in artists)
• {
• Console.WriteLine(name);
• }
Amjad Mehmood
Lec.IIT 145
Operators
• Arithmetic+ - * / %
• Logical& | ^ ~ && || !
• String concatenation+
• Increment and decrement++ --
• Bit shifting<< >>
• Comparison== != < > <= >=
• Assignment= += -= *= /= %= &= |= ^= <<= >>=
• Member access (for objects and structs).
• Indexing (for arrays and indexers)[]
• Cast()
• Conditional (the Ternary Operator)?: Object Creationnew Type
informationsizeof (unsafe code only) is typeof as Overflow exception
controlchecked unchecked Indirection and Address* -> & (unsafe code
only) []
Amjad Mehmood
Lec.IIT 146
Operator Shortcuts
• The following table shows the full list of shortcut assignment operators available
in C#:
• Shortcut OperatorEquivalent To
• x++, ++x x = x + 1
• x--, --x x=x–1
• x += y x=x+y
• x -= y x=x–y
• x *= y x=x*y
• x /= y x=x/y
• x %= y x=x%y
• x >>= y x = x >> y
• x <<= y x = x << y
• x &= y x=x&y
• x |= y x=x|y
• x ^= y x=x^y
Amjad Mehmood
Lec.IIT 147
Checked and Unchecked
• When we try to run this, we will get an error message like this:
Unhandled Exception: System.OverflowException: Arithmetic operation
• Consider the following code:
• byte b = 255;
• b++;
• Console.WriteLine(b.ToString());
• byte b = 255;
• checked
• {
• b++;
• }
• Console.WriteLine(b.ToString());
Amjad Mehmood
Lec.IIT 148
unchecked
• no exception will be raised, but we will lose data –
since the byte type can't hold a value of 256, the
overflowing bits will be discarded, and our b variable
will hold a value of zero.
• byte b = 255;
• unchecked
• {
• b++;
• }
• Console.WriteLine(b.ToString());
Amjad Mehmood
Lec.IIT 149
is
• The is operator allows us to check whether an object is
compatible with a specific type. For example, to check
whether a variable is compatible with the object type:
• By the phrase is 'compatible', we mean that an object is either
of that type or is derived from that type.
• int i = 10;
• if (i is object)
• {
• Console.WriteLine("i is an object");
• }
Amjad Mehmood
Lec.IIT 150
sizeof
• We can determine the size (in bytes) required by a
value type on the stack using the sizeof operator:
• string s = "A string";
• Unsafe
• {
• Console.WriteLine(sizeof(int));
• }
• This will display the number 4, as ints are four bytes
long
Amjad Mehmood
Lec.IIT 151
Enumerations
Amjad Mehmood
Lec.IIT 153
How to retrieve the string?
Amjad Mehmood
Lec.IIT 154
Classes and Inheritance
• class MyClass
• {
• private int someField;
• public string SomeMethod(bool parameter)
• {}
• }
• MyClass myObject;
• myObject = new MyClass();
• You can, in fact, declare and initialize an instance at the same time:
• MyClass myObject = new MyClass();
• Consider the following line:
• MyClass myObjectRef = myObject;
• myObjectRef will also refer to the same MyClass() instance as myObject.
Amjad Mehmood
Lec.IIT 155
Single Implementation Inheritance
Amjad Mehmood
Lec.IIT 156
Method Overloading
• class MyBaseClass
• {
• public virtual string VirtualMethod()
• {
• return "This method is virtual and defined in MyBaseClass";
• }
• }
• class MyDerivedClass : MyBaseClass
• {
• public override string VirtualMethod()
• {
• return "This method is an override defined in MyDerivedClass";
• }
• }
Amjad Mehmood
Lec.IIT 158
Method Overriding and Hiding
Amjad Mehmood
Lec.IIT 159
Properties
• To define a property in C#, we use the following syntax.
• public string SomeProperty
• {
• get
• {
• return "This is the property value";
• }
• Set
• {
• // do whatever needs to be done to set the property
• }
• }
Amjad Mehmood
Lec.IIT 160
Properties Cont…
• private string foreName;
• public string ForeName
• {
• Get
• {
• return foreName;
• }
• set
• {
• if (value.Length > 20) // code here to take error recovery action //
• (
• eg. throw an exception)
• else foreName = value;
• }
• }
Amjad Mehmood
Lec.IIT 161
Read-Only and Write-Only Properties
Amjad Mehmood
Lec.IIT 162
Inlining
Amjad Mehmood
Lec.IIT 166
Structure Vs Class
(a) We can not add our own zero argument constructor to the structure
(b) The structures are implicitly sealed . Hence structures can not be inherited
(c) Being sealed structure can not be marked with abstract modifier.
(d) Since structures can’t be inherited , so their members can not have protected access
modifier . Also there can not be virtual methods in structure.
(e) Structure mebers can not be initialized with the point of declaration eg
struct mypoint
{
int i=10;
int j=20;
}
This result in error . However if the member is static then we are permitted to initialize it.
(f) The structures are value type where as classes are reference type.
Amjad Mehmood
Lec.IIT 167
Value type And Reference Type
• The data of value type gets store on the stack while the data of reference type gets stored on the
heap
• The variable of value type directly contains the data, whereas reference type contains
references or address of the data.
i 10 10
C1
j 20 20
C1 Object
Amjad Mehmood
Lec.IIT 168
EXAMPLE
Using System;
Namespace sample
{
struct mystruct
{
public int I;
}
class Class1
{
static void Main(string [] args)
{
mystruct x=new mystruct();
x.i=9;
mystruct y;
y=x;
y.i=5;
Console.WriteLine(x.i);
Console.WriteLine(y.i);
}
} OUTPUT
} 5 5
Amjad Mehmood
Lec.IIT 169
When to use structure and class
STRUCTURE.
When we group dissimilar data types , we must use structure .
When we want fast access as structures are stored on stack which is faster than heap.
CLASS
Classes are more efficient as only reference is copied but when we pass a structure variable as a
parameter or assign it to another structure variable then the full contents of the structure
variable get copied.
Amjad Mehmood
Lec.IIT 170
ADO.Net
• .Net managed library that exposes functions to access data that exists outside of an
application. i.e to access persistent data.
• ADO.Net can work both in Connected and Disconnected Manner.
Road To ADO.Net:
“Great things doest not come in impulse but it is a series of small steps.
So ADO.Net is not such that comes in that shape directly that we see
today. But it is a revolutionary form of Microsoft’s Past technologies for
data access.
To understand the history of ADO.Net and Microsoft Data Access
Technologies, we need to understand the following.
Amjad Mehmood
Lec.IIT 171
Data Access Libs( DAO, RDO, ADO, and ADO.Net )
To Connect to DB through
Translation Layer
Converts User’s Call to appropriate Proprietary Function calls
Amjad Mehmood
Lec.IIT 172
Data Access Today: ( ADO. Net )
ADO. Net is developed for two basic goals.
1. To overcome the problems of existing data access technologies.
2. To cope up with the future data access methods.
ADO. Net Structure:
• ADO. Net have two fundamental parts.
i. DataSets
ii. .Net Data Providers
i. DataSets: Normally, used in Disconnected approach and is used to hold data that comes
from the database. Once, we get data in a dataset, we can insert, delete and update data
in it as if it we are working with database.
ii. .Net Data Providers: .Net data providers are used to extract and post data to a
database. ADO. Net support three sort of providers.
a ). Data Provider for SQL Server b ). Data Provider for OLEDB c ). Data Provider for ODBC
Each of these providers are contained within different namespaces.
Amjad Mehmood
Lec.IIT 173
• ADO. Net Objects and Classes:
• ADO. Net objects can be divided into two categories.
» i. Data Provider Objects
» ii Consumer Objects
DataSet Connection
DataTable Command
DataRow CommandBuilder
DataColoumn DataReader
DataRelation DataReader
Amjad Mehmood
Lec.IIT 174
• Data Provider Objects: They are used to extract and post data to a data source. Once extracted the data is put
into the clients memory of client application. Separate provider objects are used to interact with different type of data
sources.
• Data Consumer Objects: Consumer objects are used to hold and manipulate the data that is being extracted with
provider objects. Normally, they are used when we are using the disconnected approach.
3
Consumer Objects hold and RAM Space Reserved for User Application
manipulate the extracted data
Application Extracted Data
1 2
And Places the extracted data 4
in
Provider Objects Extract Data Application reserved RAM
Database
Manipulated data is posted back to
Amjad Mehmood database with provider objects
Lec.IIT 175
• ADO. Net Programming
.Net provides two ways to do database programming.
1. Through Wizards and Objects Manipulation
2. Doing Everything by Coding
1. Wizards provides an easy way to build up database applications but they do not let you to do quite complex
programming.
2. Here programming is little harder but provide everything that you want to do with a database.
Amjad Mehmood
Lec.IIT 176
Steps : 1
( a ) Connecting to Database: First, we need to connect to a database.
1. Click on “Server Explorer and then right click on “Data Connection ” and select
“add Connection “.
2. A wizard connection creation will get started
3. Click on the “Providers tag and select “Microsoft OLE DB Provider for SQL-
Server “ and Click Next.
4. In the sever name text box, give “localhost” and in the database combo box select
any database (here Northwind ) and click on
“Test
“Test Connection button” to check that whether connection has been successfully
created.
4 2
3
Amjad Mehmood
Lec.IIT 177
• ( b ) Adding Data Adapter: Data Adapter is 5
used to perform different sort of operations like
updating data, filling data sets etc.
5. In toolbox, click on “Data” tab and select
“SqlDataAdapter” and a wizard will get started.Click
“Next”
Amjad Mehmood
Lec.IIT 178
8. Next you will be presented with all the tables present in the database. This time select 8
“Customers” click “Add” and then Close.
9. Next, you will be asked for selecting the “fields” in the table, Check all the fields tab and
click “OK” and “Finish” the wizard.
10. Right click on “DataAdapter1” object created through wizard and select “Generate Data
Set” and if you
do not want to change its name
then just click ok.
( c ) Binding the controls: By binding we mean,
10
telling a control what data it is supposed to
display.
(i) Binding the Employee Name text Box:
select the text box and go to properties and 9
click on “Data Binding” select tag
And then click on
First Name.
Amjad Mehmood
Lec.IIT 180
The Command Classes
Amjad Mehmood
Lec.IIT 181
Coding
• class Class1
• {
• /// <summary>
• /// The main entry point for the application.
• /// </summary>
• [STAThread]
• static void Main(string[] args)
• {
•
• string source = "server=File_Server;" +
• "uid=sa;pwd=;" +
• "database=northwind" ;
•
• string select = "SELECT CustomerID,CompanyName,ContactName FROM Customers" ;
•
• SqlConnection conn = new SqlConnection( source ) ;
• }
• }
Amjad Mehmood
• }
Lec.IIT 182
• /*
• SelectIntoDataSet.cs
• illustrates how to perform a SELECT statement
• and store the returned rows in a DataSet object
• */
• using System;
• using System.Data;
• using System.Data.SqlClient;
• class SelectIntoDataSet
• {
• public static void Main()
• {
• // step 1: formulate a string containing the details of the
• // database connection
• string connectionString
• ="server=kust;database=Northwind;uid=sa;pwd=sa";
• // step 11: close the database connection using the Close() method
• // of the SqlConnection object created in Step 1
• mySqlConnection.Close();
• // step 12: get the DataTable object from the DataSet object
• DataTable myDataTable = myDataSet.Tables["Customers"];
Amjad Mehmood
Lec.IIT 185
• // step 13: display the columns for each row in the DataTable,
• // using a DataRow object to access each row in the DataTable
• foreach (DataRow myDataRowmyDataTable.Rows)
• {Console.WriteLine("CustomerID = "+
myDataRow["CustomerID"]);
• Console.WriteLine("CompanyName = "+
myDataRow["CompanyName"]);
• Console.WriteLine("ContactName = "+
myDataRow["ContactName"]);
• Console.WriteLine("Address = "+
myDataRow["Address"]);
• }
• }
• }
Amjad Mehmood
Lec.IIT 186
Introduction to DataForm
Amjad Mehmood
Lec.IIT 187
MYSQLCONNECTION.CS
/* MySqlConnection.cs illustrates how to use a SqlConnection object to connect to a SQL Server
database */
using System;
using System.Data;
using System.Data.SqlClient;
class MySqlConnection
{
public static void Main()
{
// formulate a string containing the details of the // database
connection string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa";
// create a SqlConnection object to connect to the
// database, passing the connection string to the constructor
• Console.WriteLine("mySqlConnection.ConnectionTimeout = "+
mySqlConnection.ConnectionTimeout);
• // close the database connection using the Close() method // of the SqlConnection object
mySqlConnection.Close();
• }
• }
Amjad Mehmood
Lec.IIT 189
The output from this program is as follows
• mySqlConnection.ConnectionString = server=localhost;database=Northwind;uid=sa;
• mySqlConnection.ConnectionTimeout = 15
• mySqlConnection.Database = Northwind
• mySqlConnection.DataSource = localhost
• mySqlConnection.PacketSize = 8192
• mySqlConnection.ServerVersion = 08.00.0194
• mySqlConnection.State = Open
• mySqlConnection.WorkstationId = JMPRICE-DT1
Amjad Mehmood
Lec.IIT 190
CONNECTIONPOOLING.CS
• /* ConnectionPooling.cs illustrates connection pooling */ using System;
• using System.Data;
• using System.Data.SqlClient;
• class ConnectionPooling
• {
• public static void Main()
• {
• // create a SqlConnection object to connect to the database,
• // setting max pool size to 10 and min pool size to 5 SqlConnection mySqlConnection = new
SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa;" + "max pool size=10;min pool size=5" );
• // open the SqlConnection object 10 times
Amjad Mehmood
Lec.IIT 191
CONNECTIONPOOLING.CS
• // open the database connection using the
• // Open() method of the SqlConnection object
• mySqlConnection.Open();
• // subtract the current date and time from the start,
• // storing the difference in a TimeSpan
• mySqlConnection.Close();
• }
• }
Amjad Mehmood
• } Lec.IIT 192
The output from this program is as follows
• count = 1 Milliseconds = 101
• mySqlConnection.State = Open
• count = 2
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 3
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 4
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 5
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 6
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 7
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 8 Milliseconds = 0
• mySqlConnection.State = Open
• count = 9
• Milliseconds = 0
• mySqlConnection.State = Open
• count = 10
• Milliseconds = 0
• mySqlConnection.State = Open
Amjad Mehmood
Lec.IIT 193
• Use the GetOrdinal() method of the DataReader object
• using System;
• using System.Data;
• using System.Data.SqlClient;
• class UsingColumnOrdinals
• {
• public static void Main()
• {
• SqlConnection mySqlConnection = new
SqlConnection( "server=localhost;database=Northwind;uid=sa;pwd=sa" );
• mySqlConnection.Open();
• int productNameColPos =
productsSqlDataReader.GetOrdinal("ProductName");
• int unitsInStockColPos =
productsSqlDataReader.GetOrdinal("UnitsInStock");
• int discontinuedColPos =
productsSqlDataReader.GetOrdinal("Discontinued");
Amjad Mehmood
Lec.IIT 195
Reading Rows from a SqlDataReader Object
• You read the rows from a DataReader object using the Read() method. This method returns the
Boolean true value when there is another row to read, otherwise it returns false.
• Let's take a look at two code snippets that illustrate these two ways of reading column values. The
first code snippet uses the column names to read the column values:
• The second code snippet uses the numeric column positions to read the column values:
Amjad Mehmood
Lec.IIT 196
• while (productsSqlDataReader.Read())
• {
• Console.WriteLine("ProductID = " + productsSqlDataReader[productIDColPos]);
Amjad Mehmood
Lec.IIT 197
• while (productsSqlDataReader.Read())
• {
• int productID = productsSqlDataReader.GetInt32(productIDColPos);
Console.WriteLine("productID = " + productID);
Amjad Mehmood
Lec.IIT 198
• Boxing and UnBoxing
• while (productsSqlDataReader.Read())
• {
• object productID = productsSqlDataReader[productIDColPos];
Amjad Mehmood
Lec.IIT 199
Reading Null Values
• you'll get the following exception:
• System.Data.SqlTypes.SqlNullValueException
• You can check if a column contains a null value using the IsDBNull()
method of a DataReader object.
• This method returns a Boolean true or false value that indicates
whether the column value is null.
• You can then use that Boolean result to decide what to do. For
example:
Amjad Mehmood
Lec.IIT 200
• if (productsSqlDataReader.IsDBNull(unitPriceColPos))
• {
• Console.WriteLine("UnitPrice column contains a null value");
• }
•
else
• {
• unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);
• }
Amjad Mehmood
Lec.IIT 201
• /*
• using System;
• using System.Data;
• using System.Data.SqlClient;
• class ExecuteSelect
• {
• public static void Main()
• {
• SqlConnection mySqlConnection =new SqlConnection(
• "server=localhost;database=Northwind;uid=sa;pwd=sa");
• SqlCommand mySqlCommand =
• mySqlConnection.CreateCommand();
Amjad Mehmood
Lec.IIT 202
•
• Amjad Mehmood
Lec.IIT 203
• mySqlConnection.Open();
• mySqlDataReader.Close();
• mySqlConnection.Close();
• }
• } Amjad Mehmood
Lec.IIT 204
POPULATEDATASETUSINGSELECT.CS
Amjad Mehmood
Lec.IIT 205
// create a SqlDataAdapter object and set its SelectCommand
// property to the SqlCommand object
• SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand =
mySqlCommand;
// create a DataSet object
• DataSet myDataSet = new DataSet();
• // open the database connection mySqlConnection.Open(); // use the Fill() method of the SqlDataAdapter
object to
• // retrieve the rows from the table, storing the rows locally // in a DataTable of the DataSet object
Console.WriteLine("Retrieving rows from the Products table");
• int numberOfRows = mySqlDataAdapter.Fill(myDataSet, "Products");
• Console.WriteLine("numberOfRows = " + numberOfRows);
• // close the database connection
• mySqlConnection.Close();
• // get the DataTable object from the DataSet object
• DataTable myDataTable = myDataSet.Tables["Products"];
• // display the column values for each row in the DataTable,
• // using a DataRow object to access each row in the DataTable
• foreach (DataRow myDataRow in myDataTable.Rows)
• {
• Console.WriteLine("ProductID = " + myDataRow["ProductID"]); Console.WriteLine("ProductName = " +
myDataRow["ProductName"]); Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
• }
• }
• } Amjad Mehmood
Lec.IIT 206
• /*
• PopulateDataSetUsingRange.cs illustrates how to populate a DataSet
• object with a range of rows from a SELECT statement
• */
• using System;
• using System.Data;
• using System.Data.SqlClient;
• class PopulateDataSetUsingRange
• {
• public static void Main()
• {
• SqlConnection mySqlConnection =
• new SqlConnection(
• "server=kust;database=Northwind;uid=sa;pwd=sa"
• );
• // create a SqlCommand object and set its CommandText property
• // to a SELECT statement that retrieves the top 5 rows from
• // the Products table
• SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
• mySqlCommand.CommandText =
• "SELECT TOP 5 ProductID, ProductName, UnitPrice " +
• "FROM Products " +
• "ORDER BY ProductID";
•
Amjad Mehmood
Lec.IIT 207
• SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
• mySqlDataAdapter.SelectCommand = mySqlCommand;
• DataSet myDataSet = new DataSet();
• mySqlConnection.Open();
• // use the Fill() method of the SqlDataAdapter object to
• // retrieve the rows from the table, storing a range of rows
• // in a DataTable of the DataSet object
• Console.WriteLine("Retrieving rows from the Products table");
• int numberOfRows = mySqlDataAdapter.Fill(myDataSet, 1, 3, "Products");
Console.WriteLine("numberOfRows = " + numberOfRows); mySqlConnection.Close();
• DataTable myDataTable = myDataSet.Tables["Products"];
• foreach (DataRow myDataRow in myDataTable.Rows)
• {
• Console.WriteLine("ProductID = " + myDataRow["ProductID"]);
Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
• }
• }
• }
Amjad Mehmood
Lec.IIT 208
• /*
• PopulateDataSetUsingProcedure.cs illustrates how to populate a
• DataSet object using a stored procedure
• */
• using System;
• using System.Data;
• using System.Data.SqlClient;
• class PopulateDataSetUsingProcedure
• {
• public static void Main()
• {
• SqlConnection mySqlConnection =
• new SqlConnection(
• "server=kust;database=Northwind;uid=sa;pwd=sa"
• );
Amjad Mehmood
Lec.IIT 210