Upload
aftab-alam-afridi
View
220
Download
0
Embed Size (px)
Citation preview
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 1/210
11
Amjad Mehmood
Lec.IIT
Visual ProgrammingVisual ProgrammingLecture 02Lecture 02--0303--0404--0505--0606--0707--0808--09:09:
using C#using C#
C# . NetC# . Net
Spring 2006Spring 2006
Oct 10Oct 10--20062006--Nov 07 Nov 07--20062006
Kohat University of Science and TechnologyKohat University of Science and Technology
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 2/210
22
Amjad Mehmood
Lec.IIT
.NET Framework and the.NET Framework and theCommon Language RuntimeCommon Language Runtime
.NET Framework .NET Framework
± ± Heart of .NET strategyHeart of .NET strategy
»» Manages and executes applications and Web servicesManages and executes applications and Web services
»» Provides security, memory management and other programmingProvides security, memory management and other programming
capabilitiescapabilities
± ± Includes Framework class library (FCL)Includes Framework class library (FCL)
»» PrePre--packaged classes ready for reuse packaged classes ready for reuse
»» Used by any .NET languageUsed by any .NET language
± ± Details contained in Common Language SpecificationDetails contained in Common Language Specification(CLS)(CLS)
»» Submitted to European Computer Manufacturers Association toSubmitted to European Computer Manufacturers Association tomake the framework easily converted to other platformsmake the framework easily converted to other platforms
± ± Executes programs by Common Language Runtime (CLR)Executes programs by Common Language Runtime (CLR)
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 3/210
33
Amjad Mehmood
Lec.IIT
.NET Framework and the.NET Framework and theCommon Language Runtime (II)Common Language Runtime (II)
Common Language Runtime (CLR)Common Language Runtime (CLR)
± ± Central part of framework Central part of framework
»» Executes Visual Basic .NET programsExecutes Visual Basic .NET programs
± ± Compilation processCompilation process
»» Two compilations take placeTwo compilations take place
»» Programs compiled to Microsoft Intermediate LanguagePrograms compiled to Microsoft Intermediate Language(MSIL)(MSIL)
Defines instructions for CLR Defines instructions for CLR
»» MSIL code translated into machine codeMSIL code translated into machine code
Machine code for a particular platformMachine code for a particular platform
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 4/210
44
Amjad Mehmood
Lec.IIT
.NET Framework and the.NET Framework and theCommon Language Runtime (III)Common Language Runtime (III)
Why two compilations?Why two compilations?
± ± Platform independencePlatform independence
»» .NET Framework can be installed on different platforms.NET Framework can be installed on different platforms
»» Execute .NET programs without any modifications to codeExecute .NET programs without any modifications to code
± ± Language independenceLanguage independence
»» .NET programs not tied to particular language.NET programs not tied to particular language
»» Programs may consist of several .NETPrograms may consist of several .NET--compliant languagescompliant languages
»» Old and new components can be integratedOld and new components can be integrated
Other advantages of CLR Other advantages of CLR ± ± ExecutionExecution--management featuresmanagement features
»» Manages memory, security and other featuresManages memory, security and other features
»» Relieves programmer of many responsibilitiesRelieves programmer of many responsibilities
»» More concentration on program logicMore concentration on program logic
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 5/210
55
Amjad Mehmood
Lec.IIT
The Microsoft .Net Framework ArchitectureThe Microsoft .Net Framework Architecture
Micosoft.Net Famework
Application Programming Model
Class Lib,Data,debug tool etc
CLR,Assemblies,Security
ASP.NET Win Form
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 6/210
66
Amjad Mehmood
Lec.IIT
The .NET Framework class libraryThe .NET Framework class library
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 7/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 8/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 9/210
99
Amjad Mehmood
Lec.IIT
Namespaces Cont«Namespaces Cont«
We can use this syntax to organize the namespaces in our We can use this syntax to organize the namespaces in our namespace definitions too, so the code above could also benamespace definitions too, so the code above could also bewritten:written:
namespace Wrox.ProCSharp.Basicsnamespace Wrox.ProCSharp.Basics
{ {
class NamespaceExampleclass NamespaceExample
{{
// Code for the class here...// Code for the class here...
} }
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 10/210
1010
Amjad Mehmood
Lec.IIT
The using StatementThe using Statement
say classes calledsay classes called NamespaceExample NamespaceExample exist both in theexist both in theWrox.ProCSharp.BasicsWrox.ProCSharp.Basics andand Wrox.ProCSharp.OOPWrox.ProCSharp.OOP namespaces. If wenamespaces. If wethen create a class calledthen create a class called TestTest in thein the Wrox.ProCSharpWrox.ProCSharp namespace, andnamespace, andinstantiate one of theinstantiate one of the NamespaceExample NamespaceExample classes in this class, we need toclasses in this class, we need tospecify which of these two classes we're talking aboutspecify which of these two classes we're talking about::
using Wrox.ProCSharp;using Wrox.ProCSharp;
class Testclass Test
{{
public static int Main() public static int Main()
{{
Basics.NamespaceExample NSEx = newBasics.NamespaceExample NSEx = new
Basics.NamespaceExample();Basics.NamespaceExample();
return 0;return 0;
} }
} }
CTS types contained within this namespace, as is much of .NET's coreCTS types contained within this namespace, as is much of .NET's corefunctionality, such as console I/O.functionality, such as console I/O.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 11/210
1111
Amjad Mehmood
Lec.IIT
Namespace AliasesNamespace Aliases
Two or more name of the same namespaceTwo or more name of the same namespace
usingusing aliasalias == NamespaceName; NamespaceName;
using System;using System;
using Introduction = Wrox.ProCSharp.Basics;using Introduction = Wrox.ProCSharp.Basics;
class Testclass Test
{{
public static int Main() public static int Main()
{{
Introduction.NamespaceExample NSEx = newIntroduction.NamespaceExample NSEx = new
Introduction.NamespaceExample();Introduction.NamespaceExample();
Console.WriteLine(NSEx.GetNamespace());Console.WriteLine(NSEx.GetNamespace()); return 0;return 0;
}}
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 12/210
1212
Amjad Mehmood
Lec.IIT
Console I/OConsole I/O
Console.Write()Console.Write() -- Writes the specified value to the console windowWrites the specified value to the console window
Console.WriteLine()Console.WriteLine() -- Which does the same, but adds a new line character Which does the same, but adds a new line character at the end of the output.at the end of the output.
ExampleExample
The following code lets the user input a line of text, and displays the firstThe following code lets the user input a line of text, and displays the firstcharacter:character:
int x = Console.Read();int x = Console.Read();
Console.WriteLine((char)x); This is similar, but returns the entire line of Console.WriteLine((char)x); This is similar, but returns the entire line of text as a string:text as a string:
The following code lets the user input a line of text, and displays the firstThe following code lets the user input a line of text, and displays the firstcharacter:character:
string s = Console.ReadLine();string s = Console.ReadLine();
Console.WriteLine(s);Console.WriteLine(s);
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 13/210
1313
Amjad MehmoodLec.IIT
Console I/O Cont«Console I/O Cont«
int i = 940;int i = 940;
int j = 73;int j = 73;
Console.WriteLine("Console.WriteLine(" {0,4}{0,4}\\n+{1,4}n+{1,4}\\nn --------\\n {2,4}", i, j, i + jn {2,4}", i, j, i + j););
The result of this is:The result of this is:
940 + 73940 + 73 -------- 10131013
StringDescriptionStringDescription
CC Local currency formatLocal currency format
..DD Decimal format. Converts an integer to base 10, and pads with leading zeros if a precisionDecimal format. Converts an integer to base 10, and pads with leading zeros if a precisionspecifier is given.specifier is given.
EE Scientific (exponential) format. The precision specifier sets the number of decimal places (6 byScientific (exponential) format. The precision specifier sets the number of decimal places (6 bydefault). The case of the format string (e or E) determines the case of the exponential symbol.default). The case of the format string (e or E) determines the case of the exponential symbol.
FF FixedFixed--point format; the precision specifier controls the number of decimal places. Zero is point format; the precision specifier controls the number of decimal places. Zero isacceptable.G General format. Uses E or F formatting, depending on which is the most compact.acceptable.G General format. Uses E or F formatting, depending on which is the most compact.
N N Number format. Formats the number with commas as thousands separators, for example Number format. Formats the number with commas as thousands separators, for example32,767.4432,767.44
PP Percent format.Percent format.
XX Hexadecimal format. The precision specifier can be used to pad with leading zerosHexadecimal format. The precision specifier can be used to pad with leading zeros
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 14/210
1414
Amjad MehmoodLec.IIT
int i = 940;int i = 940;
int j = 73;int j = 73;
Console.WriteLineConsole.WriteLine((" {0,4}" {0,4}\\n+{1,4}n+{1,4}\\nn --------\\n {2,4}", i, j, i + jn {2,4}", i, j, i + j);); The result of this is:The result of this is:
940940
+ 73+ 73
--------
10131013
Example :02Example :02
decimal i = 940.23m;decimal i = 940.23m;
decimal j = 73.7m;decimal j = 73.7m;
Console.WriteLineConsole.WriteLine(" {0,9:C2}(" {0,9:C2}\\n+{1,9:C2}n+{1,9:C2}\\nn ------------------\\n {2,9:C2}", i, j, i + j);n {2,9:C2}", i, j, i + j);
The output of this in the United States is:The output of this in the United States is:
$940.23$940.23
+ $73.70+ $73.70
------------------
$1,013.93$1,013.93
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 15/210
1515
Amjad MehmoodLec.IIT
Our First C# ProgramOur First C# Program
using System;using System;
namespace Wrox.ProCSharp.Basicsnamespace Wrox.ProCSharp.Basics
{{
class MyFirstCSharpClassclass MyFirstCSharpClass
{{
static void Main()static void Main()
{{
Console.WriteLine("This isn't at all like Java!");Console.WriteLine("This isn't at all like Java!");
return;return;
}} }}
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 16/210
1616
Amjad MehmoodLec.IIT
Execution EnvironmentExecution Environment
[C#/IL/CLR] [Java/Byte[C#/IL/CLR] [Java/Byte--Code/JVM]Code/JVM]
Source
Code.Net Compiler MSIL
CLRRunning
Program
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 17/210
1717
Amjad MehmoodLec.IIT
MSILMSIL
Microsoft intermediate languageMicrosoft intermediate language
CPUCPU--independent languageindependent language
Set of instruction that can be effectively converted inSet of instruction that can be effectively converted in
to native codeto native code Includes the instructions for Includes the instructions for
loading, storing, initializing, and calling methods onloading, storing, initializing, and calling methods onobjects, arithmetic and logical operations ,controlobjects, arithmetic and logical operations ,control
flow, directly memory access and exceptionflow, directly memory access and exceptionhandling.handling.
Can be converted to native code by JIT CompilationCan be converted to native code by JIT Compilation
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 18/210
1818
Amjad MehmoodLec.IIT
JIT CompilationJIT Compilation
Converts MSIL to native codeConverts MSIL to native code
CPUCPU--specific code that runs on the same computer specific code that runs on the same computer architecture that the JIT compiler is running on.architecture that the JIT compiler is running on.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 19/210
1919
Amjad MehmoodLec.IIT
Quiz# 01Quiz# 01Time Allowed:10Time Allowed:10 MinutesMinutes
Marks:10Marks:10
Note Please don¶t write more than Note Please don¶t write more than threethree lineslines
What are the attributes of variable?What are the attributes of variable?
Draw the diagram of .Net architectureDraw the diagram of .Net architecture
What is difference between static and Dynamic libraries?What is difference between static and Dynamic libraries?
Need and Use of interface? Need and Use of interface?
What is delegate?What is delegate?
Difference between static and instance variable?Difference between static and instance variable?
What is Message?What is Message?
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 20/210
2020
Amjad MehmoodLec.IIT
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 ) ;
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 21/210
2121
Amjad MehmoodLec.IIT
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( ) ;}
}
}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 22/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 23/210
2323
Amjad MehmoodLec.IIT
class Class1
{
static void Main ( string [ ] args )
{
sample s1 = new sample( ) ;
sample.showcount( ) ;
sample s2 = new sample( ) ;
sample.showcount( ) ;
}
}
}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 24/210
2424
Amjad MehmoodLec.IIT
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 ;
}
public static void showdate( )
{
Console.WriteLine ( "Year: " + y + " Month: " + m
+ " Day: " + d ) ;
}
}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 25/210
2525
Amjad MehmoodLec.IIT
class Class1class Class1
{{
static void Main ( string [ ] args )static void Main ( string [ ] args )
{{ sample.showdate( ) ;sample.showdate( ) ;
}}
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 26/210
2626
Amjad MehmoodLec.IIT
Scope clashes for local variableScope clashes for local variable
using System;using System; namespace Wrox.ProCSharp.Basicsnamespace Wrox.ProCSharp.Basics
{{
public class ScopeTest public class ScopeTest
{ {
public static int Main() public static int Main()
{ { for (int i = 0; i < 10; i++)for (int i = 0; i < 10; i++)
{ {
Console.WriteLine(i); } // i goes out of scope here We can declare a variable namedConsole.WriteLine(i); } // i goes out of scope here We can declare a variable namedi again, because // there's no other variable with that name in scopei again, because // there's no other variable with that name in scope
for (int i = 9; i >= 0; ifor (int i = 9; i >= 0; i----))
{{
Console.WriteLine(i);Console.WriteLine(i);
} // i goes out of scope here} // i goes out of scope here
return 0;return 0;
}}
}}
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 27/210
2727
Amjad MehmoodLec.IIT
If we try to compile this, we'll get an error:If we try to compile this, we'll get an error:
public static int Main() public static int Main()
{{
int j = 20;int j = 20;
for (int i = 0; i < 10; i++)for (int i = 0; i < 10; i++)
{{
int j = 30; // Can't do thisint j = 30; // Can't do this -- j is still in scope j is still in scope
Console.WriteLine(j + i);Console.WriteLine(j + i);
}} return 0;return 0;
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 28/210
2828Amjad Mehmood
Lec.IIT
Scope clashes Cont«Scope clashes Cont« using System;using System;
namespace Wrox.ProCSharp.Basicsnamespace Wrox.ProCSharp.Basics
{ {
class ScopeTest2class ScopeTest2
{{
static int j = 20;static int j = 20;
public static void Main() public static void Main()
{ {
int j = 30;int j = 30;
Console.WriteLine(j);Console.WriteLine(j);
return;return;
} }
}}
}}
C# makes a fundamental distinction between variables that are declared atC# makes a fundamental distinction between variables that are declared atthe type level (fields), and variables declared within methods (localthe type level (fields), and variables declared within methods (localvariables):variables): Main() methodMain() method hideshides the classthe class--level variable with the same name, so when welevel variable with the same name, so when werun this code, the number 30 will be displayed.run this code, the number 30 will be displayed.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 29/210
2929Amjad Mehmood
Lec.IIT
Scope clashes Cont«Scope clashes Cont«
......
public static void Main() public static void Main()
{{
int j = 30;int j = 30;
Console.WriteLine(ScopeTest2.j);Console.WriteLine(ScopeTest2.j);
}}
......
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 30/210
3030Amjad Mehmood
Lec.IIT
ConstantsConstants
const int a = 100; // This value cannot be changedconst int a = 100; // This value cannot be changed
once a value has been assigned, it can never beonce a value has been assigned, it can never beoverwritten.overwritten.
value of a constant must be computable atvalue of a constant must be computable atcompiletimecompiletime
Constants make it easier to avoid mistakes in your Constants make it easier to avoid mistakes in your programs. programs.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 31/210
3131Amjad Mehmood
Lec.IIT
Predefined Data TypesPredefined Data Types
Value TypesValue Types
StoresStores thethe value directlyvalue directly
stored in different places in memory; value types in an area known as thestored in different places in memory; value types in an area known as thestack stack
Int, char, doubleInt, char, double
Reference TypesReference Types
SStores a reference to the value.tores a reference to the value.
R R eference types are stored in an area known as theeference types are stored in an area known as the managed heapmanaged heap
ClassClass
InterfaceInterface DelegatesDelegates
O bjectO bject
StringString
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 32/210
3232Amjad Mehmood
Lec.IIT
Predefined Data Types Cont«Predefined Data Types Cont«
The basic predefined types recognized by C# are not intrinsic (native) to the language but partThe basic predefined types recognized by C# are not intrinsic (native) to the language but partof the .NET Framework of the .NET Framework
Name CTS Type Description Range (min:max) Name CTS Type Description Range (min:max)
sbytesbyte System.SByteSystem.SByte 88--bit signed integer bit signed integer --128:127 (128:127 (--27:2727:27--1)1)
short System.Int16 16short System.Int16 16--bit signed integer bit signed integer --32,768:32,767 (32,768:32,767 (--215:215215:215--1)1)
int System.Int32 32int System.Int32 32--bit signed integer bit signed integer --2,147,483,648:2,147,483,6472,147,483,648:2,147,483,647 ((--231:231231:231--1)1)
long System.Int64 64long System.Int64 64--bit signed integer bit signed integer --9,223,372,036,854,775,808:9,223,372,036,854,775,808:
float System.Singlefloat System.Single 3232--bit single bit single--precision floating precision floating-- point 7 point 7 1.51.5 ×× 1010--45 to45 to 3.43.4 ×× 10381038
double System.Doubledouble System.Double6464--bit double bit double--precision floating precision floating-- point point 15/1615/16 5.05.0 ×× 1010--324 to324 to 1.71.7 ×× 1030810308
decimal System.Decimaldecimal System.Decimal 128128--bit high precision decimal notation 28 bit high precision decimal notation 28 1.01.0 ×× 1010--28 to28 to 7.97.9 ×× 10281028
bool System.Boolean true or false bool System.Boolean true or false
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 33/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 34/210
3434Amjad Mehmood
Lec.IIT
Examples of Val and Ref TypeExamples of Val and Ref Type
using System;using System;
namespace cSharp_ValueReferencenamespace cSharp_ValueReference
{ {
class Class1class Class1
{{
static public int x;static public int x;
[STAThread][STAThread]
static void Main(string[] args)static void Main(string[] args)
{ { x=4; int y; y = x; x=0; // x=4; int y; y = x; x=0; //
Console.WriteLine(x);Console.WriteLine(x);
Console.WriteLine(y);Console.WriteLine(y);
Class2 Class2 ref1 = new Class2();Class2 Class2 ref1 = new Class2();
ref1.refValue=5;ref1.refValue=5;
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 35/210
3535Amjad Mehmood
Lec.IIT
Example Val and Ref Type Cont«Example Val and Ref Type Cont«
Class2 ref2 = ref1;Class2 ref2 = ref1;
ref2.refValue=10;ref2.refValue=10;
Console.WriteLine(ref1.refValue);Console.WriteLine(ref1.refValue);
Console.WriteLine(ref2.refValue);Console.WriteLine(ref2.refValue);
Console.ReadLine();Console.ReadLine();
}}
}}
class Class2class Class2
{{
public int refValue; public int refValue;
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 36/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 37/210
3737Amjad Mehmood
Lec.IIT
InterfaceInterface
Interface interfaceCar Interface interfaceCar {{
Void Move();Void Move();
Void Stop();Void Stop();
}}
Class Car1:interfaceCar Class Car1:interfaceCar
{{
Void Move()Void Move()
{{
//wirte code//wirte code
}} Void Stop()Void Stop()
{{
//write code here//write code here
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 38/210
3838Amjad Mehmood
Lec.IIT
DelegateDelegate namespace Examplenamespace Example
{{
using System;using System; /// <summary>/// <summary>
/// Delegatge/// Delegatge
/// </summary>/// </summary>
delegate void FirstDelegate();//declare the delegatedelegate void FirstDelegate();//declare the delegate
public class Delegate1 public class Delegate1
{{
public static void hello() public static void hello()
{{
Console.WriteLine("Hello Delegate");Console.WriteLine("Hello Delegate");
}}
public static int Main(string[] args) public static int Main(string[] args)
{{
FirstDelegate fd=new FirstDelegate(hello);// InstantiationFirstDelegate fd=new FirstDelegate(hello);// Instantiation
fd();// invocation of the delgatefd();// invocation of the delgate
return 0;return 0;
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 39/210
3939Amjad Mehmood
Lec.IIT
ObjectObject
All the types In C# are directly or indirectly derivedAll the types In C# are directly or indirectly derivedfrom O bject Type.from O bject Type.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 40/210
4040Amjad Mehmood
Lec.IIT
StringString
The string type is directly inherited from the objectThe string type is directly inherited from the objecttype.type.
Sring is an alias for System.String classSring is an alias for System.String class
This is sealed type.This is sealed type.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 41/210
4141Amjad Mehmood
Lec.IIT
Conversion of the TypeConversion of the Type
Three ways to convert from one type to another:Three ways to convert from one type to another:
Implicit conversionImplicit conversion Explicit conversion via castingExplicit conversion via casting
Use of a conversion methodUse of a conversion method
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 42/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 43/210
4343Amjad Mehmood
Lec.IIT
Implicit conversionImplicit conversion
double F;double F;
int X = 2;int X = 2;
F = X; // implicit conversionF = X; // implicit conversion
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 44/210
4444Amjad Mehmood
Lec.IIT
Explicit conversion via castingExplicit conversion via casting
using System;using System;
public class testConversion1 public class testConversion1
{{
public static void Main() public static void Main()
{{
long l=2.0;long l=2.0;
int i=l;int i=l;
Console.WriteLine("The long is converted to int {0}",i);Console.WriteLine("The long is converted to int {0}",i);
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 45/210
4545Amjad Mehmood
Lec.IIT
Explicit conversion via castingExplicit conversion via casting
{{
byte b=90,c=45; byte b=90,c=45;
byte d=b+c; byte d=b+c;
Console.writeLine(³result is{0}´, d);Console.writeLine(³result is{0}´, d); }}
SolutionSolution
byte d=(byte) b+c; byte d=(byte) b+c;
Console.writeLine(³result is{0}´, d);Console.writeLine(³result is{0}´, d);
Error messegeError messege
U f i th dU f i th d
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 46/210
4646Amjad Mehmood
Lec.IIT
Use of a conversion methodUse of a conversion method
Sytem.Convert.ToStringSytem.Convert.ToString
Sytem.Convert.ToIntSytem.Convert.ToInt
Sytem.Convert.ToBooleanSytem.Convert.ToBoolean
string s = i.ToString();string s = i.ToString();
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 47/210
4747Amjad Mehmood
Lec.IIT
Boxing and UnboxingBoxing and Unboxing
When a value type is converted into a reference type then it isWhen a value type is converted into a reference type then it isknown as boxingknown as boxing
When a reference type is converted into value type then it isWhen a reference type is converted into value type then it is
knowing as unboxingknowing as unboxing
Int b=145;Int b=145;
O bject o=b;//BoxingO bject o=b;//Boxing (implicit converted into object)(implicit converted into object)
Int j=(int) o;//Int j=(int) o;//UnBoxing(explicitly converted into int)UnBoxing(explicitly converted into int)
Console.writeLine(³result is{0}´, j);Console.writeLine(³result is{0}´, j);
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 48/210
4848Amjad Mehmood
Lec.IIT
Modifiers in C#Modifiers in C#
Modifiers are keywords used to specify theModifiers are keywords used to specify thedeclared accessibility of a member or a type.declared accessibility of a member or a type.
Access modifiers areAccess modifiers are
1.1. PublicPublic
2.2. ProtectedProtected
3.3. InternalInternal
4.4. PrivatePrivate
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 49/210
4949Amjad Mehmood
Lec.IIT
internalinternal using System;using System;
internal class myFirstinternal class myFirst
{{ public void hello() public void hello()
{{
Console.WriteLine("Hello C#");Console.WriteLine("Hello C#");
}}
}}
public class Mainclass public class Mainclass
{{
public static void Main() public static void Main()
{{
myFirst m=new myFirst();myFirst m=new myFirst();
m.hello();m.hello();
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 50/210
5050Amjad Mehmood
Lec.IIT
Other modifiers areOther modifiers are
AbstractAbstract
SealedSealed
VirtualVirtual
New New
OverrideOverride
StaticStatic
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 51/210
5151Amjad Mehmood
Lec.IIT
Using Abstract Classes and MethodsUsing Abstract Classes and Methods using System;using System;
abstract class abshelloabstract class abshello
{{
protected string s = ""; protected string s = ""; public abstract void callhello(); public abstract void callhello();
}}
class absDerived : abshelloclass absDerived : abshello
{{
public override void callhello() public override void callhello()
{{
s="Hello C#";s="Hello C#";
Console.WriteLine("{0}",s);Console.WriteLine("{0}",s);
}}
}}
class mainclassclass mainclass
{{
public static void Main() public static void Main()
{{
absDerived ad =new absDerived();absDerived ad =new absDerived();
ad.callhello();ad.callhello();
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 52/210
5252Amjad Mehmood
Lec.IIT
using System;using System;
abstract class abshelloabstract class abshello
{{
protected string s = ""; protected string s = "";
public abstract void callhello(); public abstract void callhello(); public abstract void sayhello();// not implemented in the derived public abstract void sayhello();// not implemented in the derived
//class.//class.
}}
class absDerived : abshelloclass absDerived : abshello
{{
public override void callhello() public override void callhello()
{{
s="Hello C#";s="Hello C#";
Console.WriteLine("{0}",s);Console.WriteLine("{0}",s);
}}
}}
class mainclassclass mainclass
{{
public static void Main() public static void Main()
{{
absDerived ad =new absDerived();absDerived ad =new absDerived();
ad.callhello();ad.callhello();
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 53/210
5353Amjad Mehmood
Lec.IIT
There are a few points to note about abstractThere are a few points to note about abstractclasses and methods:classes and methods:
YouYou cannot cannot create objects of an abstract class.create objects of an abstract class.
YouYou cannot cannot mark a constructor as abstract.mark a constructor as abstract.
You may use an abstract class to derive other classes,You may use an abstract class to derive other classes,including other abstract classes.including other abstract classes.
You must override any abstract methods in a base class withYou must override any abstract methods in a base class withmethods that contain code in a derived class.methods that contain code in a derived class.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 54/210
5454Amjad Mehmood
Lec.IIT
Declaring Sealed Classes and MethodsDeclaring Sealed Classes and Methods
Sealed ClassesSealed Classes
cannot use a sealed class to derive a class.cannot use a sealed class to derive a class.
You mark a class or method as sealed using the sealed keyword. The following exampleYou mark a class or method as sealed using the sealed keyword. The following example
declares a sealed class:declares a sealed class:
sealed public class MotorVehicle { ... } sealed public class MotorVehicle { ... }
Sealed MethodsSealed Methods
cannot override a sealed method in a derived class. may declare a sealed methodcannot override a sealed method in a derived class. may declare a sealed methodin a nonin a non--sealed class, but that sealed method cannot be overridden in a derivedsealed class, but that sealed method cannot be overridden in a derivedclass.class.
e.g sealed public override void Accelerate( )e.g sealed public override void Accelerate( )
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 55/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 56/210
5656Amjad Mehmood
Lec.IIT
OverrideOverride using System;using System;
class abshelloclass abshello
{{
protected string s = ""; protected string s = "";
public void callhello() public void callhello()
{{
s="No Hello to C#";s="No Hello to C#";
}}
}}
class absDerived : abshelloclass absDerived : abshello
{{
public override void callhello() public override void callhello()
{{
s="Hello C#";s="Hello C#";
Console.WriteLine("{0}",s);Console.WriteLine("{0}",s);
}} }}
class mainclassclass mainclass
{{
public static void Main() public static void Main()
{{
absDerived ad =new absDerived();absDerived ad =new absDerived();
ad.callhello();ad.callhello();
St tiSt ti
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 57/210
5757Amjad Mehmood
Lec.IIT
StaticStatic using System;using System;
class absDerived {class absDerived {
string s="Hello C#";string s="Hello C#";
public static void callhello() public static void callhello()
{{
Console.WriteLine("{0}",s);Console.WriteLine("{0}",s);
}}
public void normal() public void normal()
{{ Console.WriteLine("{0}",s);Console.WriteLine("{0}",s);
}}
}}
class mainclassclass mainclass
{{
public static void Main() public static void Main()
{{
absDerived.callhello();absDerived.callhello();
absDerived a=new absDerived();absDerived a=new absDerived();
a.normal();a.normal();
VirtualVirtual
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 58/210
5858Amjad Mehmood
Lec.IIT
VirtualVirtual using System;using System;
class shibiclass shibi
{{
public void hand() { Console.WriteLine("shibi's hand"); } public void hand() { Console.WriteLine("shibi's hand"); }
public virtual void eye() { Console.WriteLine("shibi's eye"); } public virtual void eye() { Console.WriteLine("shibi's eye"); }
}}
class myson: shibiclass myson: shibi
{{
public void hand() { Console.WriteLine("myson's hand"); } public void hand() { Console.WriteLine("myson's hand"); }
public override void eye() { Console.WriteLine("myson's eye"); } public override void eye() { Console.WriteLine("myson's eye"); }
}} class Testclass Test
{{
static void Main() {static void Main() {
shibi s=new shibi();shibi s=new shibi();
myson m = s;myson m = s;
s.hand();s.hand();
m.hand();m.hand();
s.eye();s.eye();
m.eye();m.eye();
}}
}}
whenever you call the virtual method it will search for the overriden method in the derwhenever you call the virtual method it will search for the overriden method in the der
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 59/210
5959Amjad Mehmood
Lec.IIT
IL Disassembler (ILDASM)IL Disassembler (ILDASM)
Go to StartGo to Start² ²visual studio commamd prompt andvisual studio commamd prompt andtypetype ildasm.exeildasm.exe Microsoft .NET Framework ILMicrosoft .NET Framework ILDisassembler (ILDASM). (Debug)Disassembler (ILDASM). (Debug)
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 60/210
6060Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 61/210
6161Amjad Mehmood
Lec.IIT
Flow ControlFlow Control
Conditional StatementsConditional Statements
The if StatementThe if Statement
if (if (conditioncondition))
statement(s) statement(s)
elseelse
statement(s) statement(s)
bool isZero; bool isZero;
if (i == 0)if (i == 0)
{{
isZero = true;isZero = true;
Console.WriteLine("i is Zero");Console.WriteLine("i is Zero");
}}
elseelse
{ {
isZero = false;isZero = false;
Console.WriteLine("i is NonConsole.WriteLine("i is Non--zero");zero");
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 62/210
6262Amjad Mehmood
Lec.IIT
ElseElse--if if using System;using System;
namespacenamespace
Wrox.ProCSharp.BasicsWrox.ProCSharp.Basics
{{
class MainEntryPointclass MainEntryPoint
{{
static void Main(string[] args)static void Main(string[] args)
{ {
Console.WriteLine("Type in a string");Console.WriteLine("Type in a string");
string input;string input; input = Console.ReadLine();input = Console.ReadLine();
if (input == "")if (input == "")
{ {
Console.WriteLine("You typed in an empty string"); }Console.WriteLine("You typed in an empty string"); }
else if (input.Length < 5)else if (input.Length < 5)
{{
Console.WriteLine("The string had less than 5 characters");Console.WriteLine("The string had less than 5 characters"); }}
else if (input.Length < 10)else if (input.Length < 10)
{{
Console.WriteLine("The string had at least 5 but less than 10 characters"); }Console.WriteLine("The string had at least 5 but less than 10 characters"); }Console.WriteLine("The string was " + input); } } }Console.WriteLine("The string was " + input); } } }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 63/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 64/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 65/210
6565Amjad Mehmood
Lec.IIT
The while LoopThe while Loop
while(condition)while(condition)
statement(s);statement(s);
bool condition = false; bool condition = false;
while (!condition)while (!condition)
{ {
DoSomeWork();DoSomeWork(); condition = CheckCondition();condition = CheckCondition();
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 66/210
6666Amjad Mehmood
Lec.IIT
The do«while LoopThe do«while Loop
bool condition; bool condition;
DoDo
{{
// this loop will at least execute once, even if // this loop will at least execute once, even if condition = CheckCondition();condition = CheckCondition();
} while (condition);} while (condition);
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 67/210
6767Amjad Mehmood
Lec.IIT
The foreach LoopThe foreach Loop
foreach (int temp in arrayOfInts)foreach (int temp in arrayOfInts)
{{
Console.WriteLine(temp);Console.WriteLine(temp);
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 68/210
6868Amjad Mehmood
Lec.IIT
Jump StatementsJump Statements
The goto StatementThe goto Statement
goto Label1;goto Label1;
Console.WriteLine("This won't be executed");Console.WriteLine("This won't be executed");
Label1: Console.WriteLine("Continuing executionLabel1: Console.WriteLine("Continuing executionfrom here");from here");
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 69/210
6969Amjad Mehmood
Lec.IIT
Statements in branchingStatements in branching
The break StatementThe break Statement
The continue StatementThe continue Statement
The return StatementThe return Statement
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 70/210
7070Amjad MehmoodLec.IIT
Arrays Arrays
array name is an lvalue
Every array in C# ³knows´ its own length. The length of the array is determined by
theexpression: c.Length
Types of arrays
Two main typesOne Dimensional Arrays
Multidimensional Arrays
1. One Dimensional Arrays
In One Dimensional arrays we can use a single subscript to refer the data elements.
One Dimensional arrays consists of one column and more than one rows.E.g.
int [ ] arr1={1,2,3};
2. Multidimensional Arrays
Multidimensional arrays we use more than one subscript to refer the data elements
E.g.
int [ , ] arr1={{2,4,5},{5,4,7},{8,7,9}};
One Dimensional ArraysOne Dimensional Arrays
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 71/210
7171Amjad MehmoodLec.IIT
One Dimensional ArraysOne Dimensional Arrays
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 72/210
7272Amjad MehmoodLec.IIT
Arrays Arrays
The declarationThe declaration
int[ ] c = new int[ 12 ];int[ ] c = new int[ 12 ];
The preceding statement can also be performed in two steps as follows:The preceding statement can also be performed in two steps as follows:
int[ ] c; // declares the arrayint[ ] c; // declares the array
c = new int[ 12 ]; // allocates the reference to thec = new int[ 12 ]; // allocates the reference to the
arrayarray
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 73/210
7373Amjad MehmoodLec.IIT
Allocating an Array and Initializing Its Elements Allocating an Array and Initializing Its Elements
class InitArrayclass InitArray
{{
// main entry point for application// main entry point for application
static void Main( string[] args )static void Main( string[] args )
{{ string output = "";string output = "";
int[] x; // declare reference to an arrayint[] x; // declare reference to an array
x = new int[ 10 ]; // dynamically allocate array and setx = new int[ 10 ]; // dynamically allocate array and set
// default values// default values
int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };
const int ARRAY_SIZE = 10; // named constantconst int ARRAY_SIZE = 10; // named constant
int[] z; // reference to int arrayint[] z; // reference to int array
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 74/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 75/210
7575Amjad MehmoodLec.IIT
Output «Output «
Totaling the Elements of an ArrayTotaling the Elements of an Array
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 76/210
7676Amjad MehmoodLec.IIT
Totaling the Elements of an ArrayTotaling the Elements of an Array
class SumArrayclass SumArray {{
// main entry point for application// main entry point for application
static void Main( string[] args )static void Main( string[] args )
{{
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int total = 0;int total = 0;
for ( int i = 0; i < a.Length; i++ )for ( int i = 0; i < a.Length; i++ )
total += a[ i ];total += a[ i ];
MessageBox.Show( "Total of array elements: " + total,MessageBox.Show( "Total of array elements: " + total,
"Sum the elements of an array","Sum the elements of an array",
MessageBoxButtons.OK, MessageBoxIcon.Information );MessageBoxButtons.OK, MessageBoxIcon.Information );
} // end Main} // end Main
} // end class SumArray} // end class SumArray
Passing Arrays to MethodsPassing Arrays to Methods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 77/210
7777Amjad MehmoodLec.IIT
Passing Arrays to MethodsPassing Arrays to Methods
int[] hourlyTemperatures = new int[ 24 ];int[] hourlyTemperatures = new int[ 24 ];
The method callThe method call
ModifyArray( hourlyTemperatures );ModifyArray( hourlyTemperatures );
The method header for method ModifyArray might be written asThe method header for method ModifyArray might be written as
public void ModifyArray( int[] b ) public void ModifyArray( int[] b )
i t id h O t tB tt Cli k( bj t di t id h O t tB tt Cli k( bj t d
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 78/210
7878Amjad MehmoodLec.IIT
private void showOutputButton_Click( object sender,private void showOutputButton_Click( object sender,
System.EventArgs e )System.EventArgs e )
{{
int[] a = { 1, 2, 3, 4, 5 };int[] a = { 1, 2, 3, 4, 5 };
outputLabel.Text = "Effects of passing entire array " +outputLabel.Text = "Effects of passing entire array " +
"call"call--byby--reference:reference:\\nn\\nThe values of the original " +nThe values of the original " +
"array are:"array are:\\nn\\t";t";
for ( int i = 0; i < a.Length; i++ )for ( int i = 0; i < a.Length; i++ )
outputLabel.Text += " " + a[ i ];outputLabel.Text += " " + a[ i ];
ModifyArray( a ); //ModifyArray( a ); // Array is passed by referenceArray is passed by reference
outputLabel.Text +=outputLabel.Text +=
""\\nn\\nThe values of the modified array are:nThe values of the modified array are:\\nn\\t";t";
// display elements of array a// display elements of array a
for ( int i = 0; i < a.Length; i++ )for ( int i = 0; i < a.Length; i++ )
outputLabel.Text += " " + a[ i ];outputLabel.Text += " " + a[ i ];
outputLabel.Text += "outputLabel.Text += "\\nn\\nEffects of passing array " +nEffects of passing array " +
"element call"element call--byby--value:value:\\nn\\na[ 3 ] before " +na[ 3 ] before " +
"ModifyElement: " + a[ 3 ];"ModifyElement: " + a[ 3 ];
//// Array element passed callArray element passed call--byby--valuevalue
ModifyElement( a[ 3 ] );ModifyElement( a[ 3 ] );
outputLabel.Text +=outputLabel.Text +=
""\\na[ 3 ] after ModifyElement: " + a[ 3 ];na[ 3 ] after ModifyElement: " + a[ 3 ];
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 79/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 80/210
8080Amjad MehmoodLec.IIT
Types of Multidimensional arraysTypes of Multidimensional arraysTwo typesTwo types
1.1. Rectangular arrayRectangular array
2.2. Jagged ArrayJagged Array
1.1. Rectangular arrayRectangular arrayIn rectangular arrays every row of the array is of the same length.In rectangular arrays every row of the array is of the same length.
OR OR
All the rows have the same numbers of elementsAll the rows have the same numbers of elements
EXAMPLEEXAMPLE
Int [ , ] arr1=new int [ , ]{{ 3,5,7,9},{11,13,15,17}};Int [ , ] arr1=new int [ , ]{{ 3,5,7,9},{11,13,15,17}};
OR OR
Int [ , ] arr1={{2,4,6,8,},{10,12,14,16}};Int [ , ] arr1={{2,4,6,8,},{10,12,14,16}};
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 81/210
8181Amjad MehmoodLec.IIT
Stack
arr1
Heap
3 5 7 9
11 13 15 17
DIAGRAM OF RECTANGULAR ARRAYSDIAGRAM OF RECTANGULAR ARRAYS
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 82/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 83/210
8383
Amjad Mehmood
Lec.IIT
Console.WriteLine ( "Number of elements in arr1: " + arr1.Length ) ;Console.WriteLine ( "Number of elements in arr1: " + arr1.Length ) ;
Array.Copy ( arr1, 2, arr2, 2, 3 ) ;Array.Copy ( arr1, 2, arr2, 2, 3 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " " ) ;Console.Write ( i + " " ) ;
arr2.SetValue ( 5, 0, 1 ) ;arr2.SetValue ( 5, 0, 1 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " " ) ;Console.Write ( i + " " ) ;
Array.Clear ( arr2, 0, arr2.Length ) ;Array.Clear ( arr2, 0, arr2.Length ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i ) ;Console.Write ( i ) ;
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 84/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 85/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 86/210
8686
Amjad Mehmood
Lec.IIT
The System.Array TypeThe System.Array Type
TheThe System. ArraySystem. Array class automatically becomes theclass automatically becomes the base class of any type of array base class of any type of array
The array class provides methods for creatingThe array class provides methods for creatingmanipulating , searching , and storing arrays .manipulating , searching , and storing arrays .
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 87/210
8787
Amjad Mehmood
Lec.IIT
EXAMPLEEXAMPLE using System ;using System ;
class onedarrayclass onedarray
{{
static void Main ( string[ ] args )static void Main ( string[ ] args )
{{
int[ ] arr1 = new int [ 5 ] { 1, 4, 7, 8, 9 } ;int[ ] arr1 = new int [ 5 ] { 1, 4, 7, 8, 9 } ;
int[ ] arr2 = new int [ 10 ] ;int[ ] arr2 = new int [ 10 ] ;
arr1.CopyTo ( arr2, 0 ) ;arr1.CopyTo ( arr2, 0 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " " ) ;Console.Write ( i + " " ) ;
Console.WriteLine( ) ;Console.WriteLine( ) ;
arr2.SetValue ( 5, 0 ) ;arr2.SetValue ( 5, 0 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " " ) ;Console.Write ( i + " " ) ;
Console.WriteLine( ) ;Console.WriteLine( ) ;
Console.WriteLine ( "Number of elements in arr1:" + arr1.Length ) ;Console.WriteLine ( "Number of elements in arr1:" + arr1.Length ) ;
Console.WriteLine ( "Number of elements in arr2:" + arr2.Length ) ;Console.WriteLine ( "Number of elements in arr2:" + arr2.Length ) ;
Array.Copy ( arr1, 2, arr2, 6, 2 ) ;Array.Copy ( arr1, 2, arr2, 6, 2 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 88/210
8888
Amjad Mehmood
Lec.IIT
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " " ) ;Console.Write ( i + " " ) ;
Console.WriteLine( ) ;Console.WriteLine( ) ;
Array.Reverse ( arr2 ) ;Array.Reverse ( arr2 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " ") ;Console.Write ( i + " ") ;
Console.WriteLine( ) ;Console.WriteLine( ) ;
Array.Sort ( arr2 ) ;Array.Sort ( arr2 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " " ) ;Console.Write ( i + " " ) ;
Console.WriteLine( ) ;Console.WriteLine( ) ;
Console.WriteLine ( "Index of 8 is " + Array.IndexOf ( arr2, 8 ) ) ;Console.WriteLine ( "Index of 8 is " + Array.IndexOf ( arr2, 8 ) ) ;
Array.Clear ( arr2, 3, 3 ) ;Array.Clear ( arr2, 3, 3 ) ;
Console.WriteLine ( "Elements of arr2: " ) ;Console.WriteLine ( "Elements of arr2: " ) ;
foreach ( int i in arr2 )foreach ( int i in arr2 )
Console.Write ( i + " " ) ;Console.Write ( i + " " ) ;
Console.WriteLine( ) ;Console.WriteLine( ) ;
StringString The string is a data type in C# holds the text enclosed in double quotesThe string is a data type in C# holds the text enclosed in double quotes
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 89/210
8989
Amjad Mehmood
Lec.IIT
The string is a data type in C# holds the text enclosed in double quotes.The string is a data type in C# holds the text enclosed in double quotes.
String is the alias of System. StringString is the alias of System. String
Instance of the string type represent Unicode character stringsInstance of the string type represent Unicode character strings
EXAMPLEEXAMPLE
string s=³Hellostring s=³Hello´;´;
using System;using System;
namespace samplenamespace sample
{{
class Class1class Class1
{{
static void Main ( string[ ] args )static void Main ( string[ ] args ) {{
string s1 = "Good Morning" ;string s1 = "Good Morning" ;
string s2 ;string s2 ;
s2 = s1 ;s2 = s1 ;
s1 = "Wake Up" ;s1 = "Wake Up" ;
Console.WriteLine ( s1 ) ;Console.WriteLine ( s1 ) ;
Console.WriteLine ( s2 ) ;Console.WriteLine ( s2 ) ;
} OUTPUT} OUTPUT
} Wake up} Wake up
} Good Morning} Good MorningPress any key to continuePress any key to continue
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 90/210
System. String typeSystem. String type
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 91/210
9191
Amjad Mehmood
Lec.IIT
y g ypy g ypSystem. String class performs various operations on string data typeSystem. String class performs various operations on string data type
EXAMPLEEXAMPLE using System ;using System ;
namespace samplenamespace sample
{{
class Class1class Class1
{{
static void Main ( string[ ] args )static void Main ( string[ ] args )
{{
string s1 = "kicit" ;string s1 = "kicit" ;
string s2 = "Nagpur" ;string s2 = "Nagpur" ; Console.WriteLine ( "Char at 3rd position: " + s1 [ 2 ] ) ;Console.WriteLine ( "Char at 3rd position: " + s1 [ 2 ] ) ;
string s3 = string.Concat ( s1, s2 ) ;string s3 = string.Concat ( s1, s2 ) ;
Console.WriteLine ( s3 ) ;Console.WriteLine ( s3 ) ;
Console.WriteLine ( "Length of s3: " + s3.Length ) ;Console.WriteLine ( "Length of s3: " + s3.Length ) ;
s3 = s3.Replace ( 'p', 'P' ) ;s3 = s3.Replace ( 'p', 'P' ) ;
Console.WriteLine ( s3 ) ;Console.WriteLine ( s3 ) ;
s3 = string.Copy ( s2 ) ;s3 = string.Copy ( s2 ) ;
Console.WriteLine ( s3 ) ;Console.WriteLine ( s3 ) ;
int c = s2.CompareTo ( s3 ) ;int c = s2.CompareTo ( s3 ) ;
if ( c < 0 )if ( c < 0 )
Console.WriteLine ( "s2 is less than s3" ) ;Console.WriteLine ( "s2 is less than s3" ) ;
if ( c == 0 )if ( c == 0 )
Console.WriteLine ( "s2 is equal to s3" ) ;Console.WriteLine ( "s2 is equal to s3" ) ;
if ( c > 0 )if ( c > 0 )
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 92/210
9292
Amjad Mehmood
Lec.IIT
if ( c > 0 )if ( c > 0 )
Console.WriteLine ( "s2 is greater than s3" ) ;Console.WriteLine ( "s2 is greater than s3" ) ;
if ( s1 == s3 )if ( s1 == s3 )
Console.WriteLine ( "s1 is equal to s3" ) ;Console.WriteLine ( "s1 is equal to s3" ) ;
elseelse
Console.WriteLine ( "s1 is not equal to s3" ) ;Console.WriteLine ( "s1 is not equal to s3" ) ;
s3 = s1.ToUpper( ) ;s3 = s1.ToUpper( ) ;
Console.WriteLine ( s3 ) ;Console.WriteLine ( s3 ) ;
s3 = s2.Insert ( 6, "Mumbai" ) ;s3 = s2.Insert ( 6, "Mumbai" ) ;
Console.WriteLine ( s3 ) ;Console.WriteLine ( s3 ) ;
s3 = s2.Remove ( 0, 1 ) ;s3 = s2.Remove ( 0, 1 ) ;
Console.WriteLine ( s3 ) ;Console.WriteLine ( s3 ) ;
int fin = s1.IndexOf ( 'i' ) ;int fin = s1.IndexOf ( 'i' ) ;
Console.WriteLine ( "First index of i in s1: " + fin ) ;Console.WriteLine ( "First index of i in s1: " + fin ) ;
int lin = s1.LastIndexOf ( 'i' ) ;int lin = s1.LastIndexOf ( 'i' ) ;
Console.WriteLine ( "Last index of i in s1: " + lin ) ;Console.WriteLine ( "Last index of i in s1: " + lin ) ;
string sub = s1.Substring ( fin, lin ) ;string sub = s1.Substring ( fin, lin ) ;
Console.WriteLine ( "Substring: " + sub ) ;Console.WriteLine ( "Substring: " + sub ) ;
}}
}}
Parsing String to other data typesParsing String to other data types Console ReadLine() can take input as a string from the userConsole ReadLine() can take input as a string from the user
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 93/210
9393
Amjad Mehmood
Lec.IIT
Console.ReadLine() can take input as a string from the user.Console.ReadLine() can take input as a string from the user.
We need to type cast string for mathematical operations .We need to type cast string for mathematical operations .
For this we need Parse() method to type cast string into other data type .For this we need Parse() method to type cast string into other data type .
using System ;using System ;
namespace samplenamespace sample
{{
class Class1class Class1
{{
static void Main ( string[ ] args )static void Main ( string[ ] args )
{{ Console.WriteLine ( "Enter an integer: " ) ;Console.WriteLine ( "Enter an integer: " ) ;
string s = Console.ReadLine( ) ;string s = Console.ReadLine( ) ;
int i = int.Parse ( s ) ;int i = int.Parse ( s ) ;
Console.WriteLine ( "Enter a float: " ) ;Console.WriteLine ( "Enter a float: " ) ;
s = Console.ReadLine( ) ;s = Console.ReadLine( ) ;
float f = float.Parse ( s ) ;float f = float.Parse ( s ) ;
float t = f + i ;float t = f + i ;
Console.WriteLine ( t ) ;Console.WriteLine ( t ) ;
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 94/210
9494
Amjad Mehmood
Lec.IIT
Windows Form ControlsWindows Form Controls
Windows Form ControlsWindows Form Controls
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 95/210
9595
Amjad Mehmood
Lec.IIT
Windows Form ControlsWindows Form Controls
Control: A control is anything on a form that a user Control: A control is anything on a form that a user can interact with. For example,can interact with. For example,
Buttons,Labels, textBoxes, toolbars etc.Buttons,Labels, textBoxes, toolbars etc.
Form: A form is a container for controls.Form: A form is a container for controls. .Net provide a rich set of forms like windows forms,.Net provide a rich set of forms like windows forms,
web forms, mobile forms etc. Each have its own setweb forms, mobile forms etc. Each have its own setof controlsof controls
Common Windows Form ControlsCommon Windows Form Controls
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 96/210
9696
Amjad Mehmood
Lec.IIT
Common Windows Form ControlsCommon Windows Form Controls
ButtonsButtons
TextBoxesTextBoxes
LabelsLabels
ComboBoxComboBox
Radio buttonsRadio buttons
CheckBoxesCheckBoxes
PictureBoxesPictureBoxes
Toolbars etcToolbars etc
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 97/210
9797
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 98/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 99/210
EventEvent
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 100/210
100100
Amjad Mehmood
Lec.IIT
EventEvent
An event is any user action, or a system action thatAn event is any user action, or a system action thatcan be recognized by O.S and can execute some codecan be recognized by O.S and can execute some codeagainst it.against it.
Events can be handle at two levels when they areEvents can be handle at two levels when they areraised.raised.
1. At Application Level1. At Application Level
2. At O.S Level (HOOK S)2. At O.S Level (HOOK S)
Event Handler: It is a function that is executed whenEvent Handler: It is a function that is executed whenan event is raised.an event is raised.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 101/210
101101
Amjad Mehmood
Lec.IIT
An event handler may be of two typesAn event handler may be of two types
1.1. LocalLocal
2. Global2. Global
Local event handlers are executed when an event atLocal event handlers are executed when an event atapplication level is raised and there is no hook application level is raised and there is no hook installed for it.installed for it.
Hook: A hook is a function that is executed before theHook: A hook is a function that is executed before theevent reaches to your application. e.g. stopping anevent reaches to your application. e.g. stopping anapplication from running before it starts.application from running before it starts.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 102/210
102102
Amjad Mehmood
Lec.IIT
Global event handlers (HOOK S):Global event handlers (HOOK S):
are executed at O.S level. For example if we write aare executed at O.S level. For example if we write aHook for a click event. Then it will be executed eachHook for a click event. Then it will be executed eachtime a click occurs even if it is out of your time a click occurs even if it is out of your application.application.
EventEvent--Handling ModelHandling Model
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 103/210
103103
Amjad Mehmood
Lec.IIT
EventEvent--Handling ModelHandling Model
O bject A raises event E Delegate for event E
Handler 1 for event E
Handler 3 for event E
Handler 2 for event E
calls
calls
Event Handler Parameters
Two parameters are passed.
1. Sender: it describes that who raises the
event. i.e it identifies the event raiser.
2. System.EventArgs: this contains information that is specific to the event.
For example, what are x,y co-ordinates where the event occurs.
void button1_click(object sender,System.EventArgs e)
Common Controls EventsCommon Controls Events
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 104/210
104104
Amjad Mehmood
Lec.IIT
Common Controls EventsCommon Controls Events
All controls have some events in commonAll controls have some events in common
1.1. Click 2. Paint ( Raised each time when a control or form is redrawn)Click 2. Paint ( Raised each time when a control or form is redrawn)
3.3. MouseDownMouseDown 4. MouseEnter 4. MouseEnter
5.5. MouseLeaveMouseLeave
6.6. MouseUPMouseUP 7.K eyDown7.K eyDown
8 .K eyPress8 .K eyPress
And many many more«And many many more«
MethodsMethods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 105/210
105105
Amjad Mehmood
Lec.IIT
MethodsMethods
Each controls have a rich set of methods that canEach controls have a rich set of methods that caneasy the task for carrying different operations relatedeasy the task for carrying different operations relatedto a control.to a control.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 106/210
106106
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 107/210
107107
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 108/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 109/210
109109
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 110/210
110110
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 111/210
111111
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 112/210
112112
Amjad Mehmood
Lec.IIT
Simple applicationSimple application
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 113/210
113113
Amjad Mehmood
Lec.IIT
Simple applicationSimple application
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 114/210
114114
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 115/210
115115
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 116/210
116116
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 117/210
117117
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 118/210
118118
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 119/210
119119
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 120/210
120120
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 121/210
121121
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 122/210
122122
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 123/210
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 124/210
124124
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 125/210
125125
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 126/210
126126
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 127/210
127127
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 128/210
128128
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 129/210
129129
Amjad Mehmood
Lec.IIT
Use of Message BoxUse of Message Box
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 130/210
130130
Amjad Mehmood
Lec.IIT
Simple Program: Adding Integers
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 131/210
131131
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 132/210
132132
Amjad Mehmood
Lec.IIT
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 133/210
Quiz# 02Quiz# 02Time Allowed:10Time Allowed:10 MinutesMinutes
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 134/210
134134
Amjad Mehmood
Lec.IIT
Marks:10Marks:10
I'm confused. What's the difference between the .NETI'm confused. What's the difference between the .NETFramework and Visual Studio .NET?Framework and Visual Studio .NET?
Should I write all my code in C# because it runs moreShould I write all my code in C# because it runs moreefficiently than Visual Basic .NET or COBOL .NET?efficiently than Visual Basic .NET or COBOL .NET?
What is CLS and CTS and who performs these functionsWhat is CLS and CTS and who performs these functions
Write the purpose of new operator Write the purpose of new operator
What is Boxing and UnBoxing?What is Boxing and UnBoxing?
Draw the execution diagram of .net environmentDraw the execution diagram of .net environment
Override the Tostring MethodOverride the Tostring Method What is up casting and down castingWhat is up casting and down casting
What are the rules for Declaring Sealed Classes and MethodsWhat are the rules for Declaring Sealed Classes and Methods
MethodsMethods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 135/210
135135
Amjad Mehmood
Lec.IIT
Note that official C# terminology does in fact make a Note that official C# terminology does in fact make adistinction between functions and methods.distinction between functions and methods.
In this terminology, the term 'function member' In this terminology, the term 'function member' includes not only methods, but also other nonincludes not only methods, but also other non--datadata
members of a class or struct. This includes indexers,members of a class or struct. This includes indexers,operators, constructors, destructors, and alsooperators, constructors, destructors, and also ± ± perhaps somewhat surprisingly perhaps somewhat surprisingly ± ± properties. properties.
These are contrasted with data members: fields,These are contrasted with data members: fields,constants, and events.constants, and events.
Declaring MethodsDeclaring Methods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 136/210
136136
Amjad Mehmood
Lec.IIT
[[modifiersmodifiers]] return_type MethodNamereturn_type MethodName([([ parameters parameters])])
{ {
// Method body// Method body
} }
Invoking MethodsInvoking Methods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 137/210
137137
Amjad Mehmood
Lec.IIT
using System;using System;
namespace Wrox.ProCSharp.Basicsnamespace Wrox.ProCSharp.Basics
{{
class MainEntryPointclass MainEntryPoint
{{
static void Main()static void Main()
{{
// Try calling some static functions// Try calling some static functions Console.WriteLine("Pi is " + MathTest.GetPi());Console.WriteLine("Pi is " + MathTest.GetPi());
int x = MathTest.GetSquareOf(5);int x = MathTest.GetSquareOf(5);
Console.WriteLine("Square of 5 is " + x);Console.WriteLine("Square of 5 is " + x);
// Instantiate at MathTest object// Instantiate at MathTest object
MathTest math = new MathTest(); // this is C#'s way of // MathTest math = new MathTest(); // this is C#'s way of //
instantiating a reference typeinstantiating a reference type
// Call non// Call non--static methods math.value = 30;static methods math.value = 30; Console.WriteLine( "Value field of math variable contains " + math.value);Console.WriteLine( "Value field of math variable contains " + math.value);
Console.WriteLine("Square of 30 is " + math.GetSquare());Console.WriteLine("Square of 30 is " + math.GetSquare());
} }
} }
Invoking MethodsInvoking Methods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 138/210
138138
Amjad Mehmood
Lec.IIT
// Define a class named MathTest on which we will call a method// Define a class named MathTest on which we will call a method class MathTestclass MathTest
{{
public int value; public int value;
public int GetSquare() public int GetSquare()
{{
return value*value;return value*value; }}
public static int GetSquareOf(int x) public static int GetSquareOf(int x)
{ return x*x; } { return x*x; }
public static double GetPi() public static double GetPi()
{{
return 3.14159;return 3.14159; }}
}}
} }
Passing Parameters to MethodsPassing Parameters to Methods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 139/210
139139
Amjad Mehmood
Lec.IIT
namespace Wrox.ProCSharp.Basicsnamespace Wrox.ProCSharp.Basics
{ {
class ParameterTestclass ParameterTest
{{
static void SomeFunction(int[] ints, int i)static void SomeFunction(int[] ints, int i)
{ {
ints[0] = 100; i = 100;ints[0] = 100; i = 100;
}}
public static int Main() public static int Main() {{
int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values Console.WriteLine("i = " + i);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("ints[0] = " + ints[0]);
Console.WriteLine("Calling SomeFunction..."); // After this method returns, ints will be changed,Console.WriteLine("Calling SomeFunction..."); // After this method returns, ints will be changed,
// but i will not SomeFunction(ints, i);// but i will not SomeFunction(ints, i);
Console.WriteLine("i = " + i);Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);Console.WriteLine("ints[0] = " + ints[0]); return 0;return 0;
} }
}}
} }
Passing Parameters to MethodsPassing Parameters to Methods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 140/210
140140
Amjad Mehmood
Lec.IIT
namespace Wrox.ProCSharp.Basicsnamespace Wrox.ProCSharp.Basics
{{
class ParameterTestclass ParameterTest
{ {
static void SomeFunction(int[] ints, int i)static void SomeFunction(int[] ints, int i)
{{
ints[0] = 100; i = 100; } ints[0] = 100; i = 100; }
public static int Main() public static int Main() {{
int i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original valuesint i = 0; int[] ints = { 0, 1, 2, 4, 8 }; // Display the original values
Console.WriteLine("i = " + i);Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);Console.WriteLine("ints[0] = " + ints[0]);
Console.WriteLine("Calling SomeFunction..."); // After this method returns, intsConsole.WriteLine("Calling SomeFunction..."); // After this method returns, ints
will be changed, // but i will notwill be changed, // but i will not
SomeFunction(ints, i);SomeFunction(ints, i); Console.WriteLine("i = " + i);Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);Console.WriteLine("ints[0] = " + ints[0]);
return 0; } } } return 0; } } }
ParameterTestParameterTest
i = 0i = 0
ints[0] = 0ints[0] = 0
Calling SomeFunction...Calling SomeFunction...i = 0i = 0
ints[0] = 100ints[0] = 100
referencereference--type behavior type behavior
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 141/210
141141
Amjad Mehmood
Lec.IIT
static void SomeFunction(int[] ints, ref int i)static void SomeFunction(int[] ints, ref int i)
{ {
ints[0] = 100; i = 100;ints[0] = 100; i = 100;
}}
We will also need to add the ref keyword when weWe will also need to add the ref keyword when weinvoke the method:invoke the method:
SomeFunction(ints, ref i);SomeFunction(ints, ref i);
The out KeywordThe out Keyword
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 142/210
142142
Amjad Mehmood
Lec.IIT
out parameter isn't assigned a value within the body of the function, theout parameter isn't assigned a value within the body of the function, the
method won't compile.method won't compile. static void SomeFunction(out int i)static void SomeFunction(out int i)
{{
i = 100;i = 100;
}}
public static int Main() public static int Main() {{
int i; // note how i is declared but not initializedint i; // note how i is declared but not initialized
SomeFunction(out i);SomeFunction(out i);
Console.WriteLine(i);Console.WriteLine(i);
return 0;return 0;
} }
ArrayArray
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 143/210
143143
Amjad Mehmood
Lec.IIT
int[] integers;int[] integers;
To initialize the array with specific dimensions, weTo initialize the array with specific dimensions, wecan use the new keyword, giving the size in thecan use the new keyword, giving the size in thesquare brackets after the type name:square brackets after the type name:
// Create a new array of 32// Create a new array of 32
ints int[] integers = new int[32];ints int[] integers = new int[32];
integers[31] = 432;integers[31] = 432;
ArrayArray
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 144/210
144144
Amjad Mehmood
Lec.IIT
string[] myArray = {"first element", "secondstring[] myArray = {"first element", "secondelement", "third element"};element", "third element"};
Note that it is perfectly permissible to use a variable Note that it is perfectly permissible to use a variableto set how many elements the array will contain, liketo set how many elements the array will contain, like
this:this:
int len;int len;
len = GetArraySize(); // assume this function workslen = GetArraySize(); // assume this function works
out how big we want // out how big we want // the array to be string[] myArray = new string[len];the array to be string[] myArray = new string[len];
uncheckedunchecked
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 145/210
145145
Amjad Mehmood
Lec.IIT
W
orkingw
ith
ArraysW
orkingw
ith
Arrays ArraysArrays
int arrayLength = integers.Length;int arrayLength = integers.Length;
using the static Array.Sort() method:using the static Array.Sort() method:
Array.Sort(myArray);Array.Sort(myArray);
S ystem.Array.S ort() method S ystem.Array.S ort() method using the static Reverse() method:using the static Reverse() method:
Array.Reverse(myArray);Array.Reverse(myArray);
string[] artists = {"Leonardo", "Monet", "Van Gogh", "K lee"};string[] artists = {"Leonardo", "Monet", "Van Gogh", "K lee"};
Array.Sort(artists);Array.Sort(artists);
Array.Reverse(artists);Array.Reverse(artists); foreach (string name in artists)foreach (string name in artists)
{{
Console.WriteLine(name);Console.WriteLine(name);
} }
OperatorsOperators
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 146/210
146146
Amjad Mehmood
Lec.IIT
Arithmetic+Arithmetic+ -- * / %* / % Logical& | ^ ~ && || !Logical& | ^ ~ && || !
String concatenation+String concatenation+
Increment and decrement++Increment and decrement++ ----
Bit shifting<< >>Bit shifting<< >>
Comparison== != < > <= >=Comparison== != < > <= >= Assignment= +=Assignment= += --= *= /= %= &= |= ^= <<= >>== *= /= %= &= |= ^= <<= >>=
Member access (for objects and structs).Member access (for objects and structs).
Indexing (for arrays and indexers)[]Indexing (for arrays and indexers)[]
Cast()Cast()
Conditional (the Ternary O perator)?: O bject Creationnew TypeConditional (the Ternary O perator)?: O bject Creationnew Typeinformationsizeof (unsafe code only) is typeof as Overflow exceptioninformationsizeof (unsafe code only) is typeof as Overflow exceptioncontrolchecked unchecked Indirection and Address*controlchecked unchecked Indirection and Address* --> & (unsafe code> & (unsafe codeonly) []only) []
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 147/210
Checked and UncheckedChecked and Unchecked
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 148/210
148148
Amjad Mehmood
Lec.IIT
When we try to run this, we will get an error message like this:When we try to run this, we will get an error message like this:Unhandled Exception: System.OverflowException: Arithmetic operationUnhandled Exception: System.OverflowException: Arithmetic operation
Consider the following code:Consider the following code:
byte b = 255; byte b = 255;
b++; b++;
Console.WriteLine(b.ToString());Console.WriteLine(b.ToString());
byte b = 255; byte b = 255;
checkedchecked
{{
b++; b++; }}
Console.WriteLine(b.ToString());Console.WriteLine(b.ToString());
uncheckedunchecked
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 149/210
149149
Amjad Mehmood
Lec.IIT
no exception will be raised, but we will lose datano exception will be raised, but we will lose data ± ± since the byte type can't hold a value of 256, thesince the byte type can't hold a value of 256, theoverflowing bits will be discarded, and our b variableoverflowing bits will be discarded, and our b variablewill hold a value of zero.will hold a value of zero.
byte b = 255; byte b = 255; uncheckedunchecked
{{
b++; b++;
}}
Console.WriteLine(b.ToString());Console.WriteLine(b.ToString());
isis
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 150/210
150150
Amjad Mehmood
Lec.IIT
The is operator allows us to check whether an object isThe is operator allows us to check whether an object iscompatible with a specific type. For example, to check compatible with a specific type. For example, to check whether a variable is compatible with the object type:whether a variable is compatible with the object type:
B y the phrase is 'compatible', we mean that an object is either B y the phrase is 'compatible', we mean that an object is either of that type or is derived from that type.of that type or is derived from that type.
int i = 10;int i = 10;
if (i is object)if (i is object)
{{
Console.WriteLine("i is an object");Console.WriteLine("i is an object");
} }
sizeof sizeof
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 151/210
151151
Amjad Mehmood
Lec.IIT
We can determine the size (in bytes) required by aWe can determine the size (in bytes) required by avalue type on the stack using the sizeof operator:value type on the stack using the sizeof operator:
string s = "A string";string s = "A string";
UnsafeUnsafe {{
Console.WriteLine(sizeof(int));Console.WriteLine(sizeof(int));
} } This will display the number 4, as ints are four bytesThis will display the number 4, as ints are four bytes
longlong
EnumerationsEnumerations
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 152/210
152152
Amjad Mehmood
Lec.IIT
AnAn enumerationenumeration is a user is a user--defined integer type.defined integer type. We can define an enumeration as follows:We can define an enumeration as follows:
public enum TimeOfDay public enum TimeOfDay
{{
Morning = 0,Morning = 0,
Afternoon = 1,Afternoon = 1,
Evening = 2Evening = 2
} }
We can nowWe can now access these values as members of theaccess these values as members of theenumeration. For example, TimeOfDay.Morning will retur theenumeration. For example, TimeOfDay.Morning will retur the
value 0.value 0.
Enum ExampleEnum Example
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 153/210
153153
Amjad Mehmood
Lec.IIT
class EnumExampleclass EnumExample
{{
public static int Main() public static int Main()
{{
WriteGreeting(TimeOfDay.Morning);WriteGreeting(TimeOfDay.Morning);
return 0;return 0;
}} static void WriteGreeting(TimeOfDay timeOfDay)static void WriteGreeting(TimeOfDay timeOfDay)
{{
switch(timeOfDay)switch(timeOfDay)
{{
case TimeOfDay.Morning: Console.WriteLine("Good morning!"); break;case TimeOfDay.Morning: Console.WriteLine("Good morning!"); break;
case TimeOfDay.Afternoon: Console.WriteLine("Good afternoon!"); break;case TimeOfDay.Afternoon: Console.WriteLine("Good afternoon!"); break;
case TimeOfDay.Evening: Console.WriteLine("Good evening!"); break; default:case TimeOfDay.Evening: Console.WriteLine("Good evening!"); break; default:
Console.WriteLine("Hello!"); break; } } } Console.WriteLine("Hello!"); break; } } }
How to retrieve the string?How to retrieve the string?
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 154/210
154154
Amjad Mehmood
Lec.IIT
You can retrieve the string representation of anYou can retrieve the string representation of anenum. For example, using our earlier TimeOfDayenum. For example, using our earlier TimeOfDayenum:enum:
TimeOfDay time = TimeOfDay.Afternoon;TimeOfDay time = TimeOfDay.Afternoon;
Console.WriteLine(time.ToString());Console.WriteLine(time.ToString());
Classes and InheritanceClasses and Inheritance
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 155/210
155155
Amjad Mehmood
Lec.IIT
class MyClassclass MyClass {{
private int someField; private int someField;
public string SomeMethod(bool parameter) public string SomeMethod(bool parameter)
{ }{ }
} } MyClass myO bject;MyClass myO bject;
myO bject = new MyClass();myO bject = new MyClass();
You can, in fact, declare and initialize an instance at the same time:You can, in fact, declare and initialize an instance at the same time:
MyClass myO bject = new MyClass();MyClass myO bject = new MyClass();
Consider the following line:Consider the following line: MyClass myO bjectRef = myO bject;MyClass myO bjectRef = myO bject;
myO bjectRef will also refer to the same MyClass() instance as myO bject.myO bjectRef will also refer to the same MyClass() instance as myO bject.
Single Implementation InheritanceSingle Implementation Inheritance
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 156/210
156156
Amjad Mehmood
Lec.IIT
C# supports single inheritance of classes. In other C# supports single inheritance of classes. In other words, a class may derive directly from one other words, a class may derive directly from one other class. The syntax for this is as follows.class. The syntax for this is as follows.
class MyDerivedClass : MyBaseClassclass MyDerivedClass : MyBaseClass
{{
// functions and data members here// functions and data members here
} }
Method OverloadingMethod Overloading
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 157/210
157157
Amjad Mehmood
Lec.IIT
C# supports method overloadingC# supports method overloading ± ± several versions of theseveral versions of themethod that havemethod that have
different signatures (name, number of parameters, anddifferent signatures (name, number of parameters, and parameter types), parameter types),
In order to overload methods, you simply declare the methodsIn order to overload methods, you simply declare the methods
with the same name but different numbers or types of with the same name but different numbers or types of parameters: parameters:
class ResultDisplayer class ResultDisplayer
{{
void DisplayResult(string result) { // implementation } void DisplayResult(string result) { // implementation } void DisplayResult(int result) { // implementation }void DisplayResult(int result) { // implementation }
} }
Method Overriding and HidingMethod Overriding and Hiding
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 158/210
158
158
Amjad Mehmood
Lec.IIT
class MyBaseClassclass MyBaseClass
{{
public virtual string VirtualMethod() public virtual string VirtualMethod()
{{
return "This method is virtual and defined in MyBaseClass";return "This method is virtual and defined in MyBaseClass";
} }
} }
class MyDerivedClass : MyBaseClassclass MyDerivedClass : MyBaseClass
{{
public override string VirtualMethod() public override string VirtualMethod()
{ { return "This method is an override defined in MyDerivedClass";return "This method is an override defined in MyDerivedClass";
}}
} }
Method Overriding and HidingMethod Overriding and Hiding
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 159/210
159
159
Amjad Mehmood
Lec.IIT
class MyDerivedClass : HisBaseClassclass MyDerivedClass : HisBaseClass
{{
public new int MyGroovyMethod() public new int MyGroovyMethod()
{ {
// some groovy implementation// some groovy implementation
}}
} }
PropertiesProperties
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 160/210
1601
60
Amjad Mehmood
Lec.IIT
To define a property in C#, we use the following syntax.To define a property in C#, we use the following syntax. public string SomeProperty public string SomeProperty
{{
getget
{{
return "This is the property value";return "This is the property value";
} }
SetSet
{ {
// do whatever needs to be done to set the property// do whatever needs to be done to set the property }}
} }
Properties Cont«Properties Cont«
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 161/210
1611
61
Amjad Mehmood
Lec.IIT
private string foreName; private string foreName;
public string ForeName public string ForeName
{ {
GetGet
{{
return foreName;return foreName;
}}
setset
{{
if (value.Length > 20) // code here to take error recovery action // if (value.Length > 20) // code here to take error recovery action //
((
eg. throw an exception)eg. throw an exception) else foreName = value;else foreName = value;
}}
} }
ReadRead--Only andWriteOnly andWrite--Only PropertiesOnly Properties
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 162/210
1621
62
Amjad Mehmood
Lec.IIT
It is possible to create aIt is possible to create a readread--only propertyonly property by simply by simplyomitting the set accessor from the property definition.omitting the set accessor from the property definition.
public string ForeName { public string ForeName {
GetGet
{{
return foreName;return foreName;
}}
} }
create acreate a writewrite--only propertyonly property by omitting the get accessor. by omitting the get accessor.
InliningInlining
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 163/210
1631
63
Amjad Mehmood
Lec.IIT
C# code is compiled to IL then JITC# code is compiled to IL then JIT--normally compiled atnormally compiled atruntime to native executable code.runtime to native executable code.
Well the JIT compiler is designed to generate highlyWell the JIT compiler is designed to generate highlyoptimized code.optimized code.
Although it is not in general possible to predict what methodsAlthough it is not in general possible to predict what methodswill be inlined in particular circumstances, experience haswill be inlined in particular circumstances, experience hasshown that the JIT compiler is ruthless when it comes toshown that the JIT compiler is ruthless when it comes toinlining any function calls that look suitable.inlining any function calls that look suitable.
A method or property whose implementation simply callsA method or property whose implementation simply calls
another method or returns a field will almost certainly beanother method or returns a field will almost certainly beinlined.inlined.
Decision of where to inline is made entirely by the CLR.Decision of where to inline is made entirely by the CLR.
Quiz 4Quiz 4Time: 15 MinTime: 15 Min Marks: 50Marks: 50
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 164/210
1641
64
Amjad Mehmood
Lec.IIT
Write a names of some important namespaces classes in it andWrite a names of some important namespaces classes in it andmethodsmethods
Difference between heap and stack Difference between heap and stack
Difference between classes and structuresDifference between classes and structures
Write a class with static constructor which includes day, year,Write a class with static constructor which includes day, year,
month and show method which will display the given day,month and show method which will display the given day,year and month.year and month.
Differentiate between static constructor static method andDifferentiate between static constructor static method andconstructor.constructor.
What is enumerators?What is enumerators?
EventEvent--Handling ModelHandling Model
What is hooks?What is hooks?
What command is use to load IL Disassembler (ILDASM)?What command is use to load IL Disassembler (ILDASM)?
StructureStructure
Structure is a data structure which contains different data types of data and with there methods.Structure is a data structure which contains different data types of data and with there methods.
Structure is defined using a key wordStructure is defined using a key word structstruct
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 165/210
1651
65
Amjad Mehmood
Lec.IIT
Structure is defined using a key wordStructure is defined using a key word struct.struct.
EXAMPLEEXAMPLE
using System;using System;
namespace samplenamespace sample
{{
struct employeestruct employee
{{
string name;string name;
int age;int age;
float sal;float sal;
public employee(string n,int a,float s) public employee(string n,int a,float s)
{{
name =n;name =n;
age=a;age=a;
sal=s;sal=s;
}}
public viod showdata() public viod showdata()
{ {
Console.WriteLine(³Name:́ +name);Console.WriteLine(³Name:́ +name);
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 166/210
166
166
Amjad Mehmood
Lec.IIT
Console.WriteLine(³Age:́ +age);Console.WriteLine(³Age:́ +age);
Console.WriteLine(³Salary:́ +sal);Console.WriteLine(³Salary:́ +sal);
}}
}}
class Class1class Class1
{{
Static void Main(string [ ] args)Static void Main(string [ ] args)
{{
employee e1=new employee(³Ali´,35,25000);employee e1=new employee(³Ali´,35,25000);
e1.showdata();e1.showdata();
}}
}}}}
Structure Vs ClassStructure Vs Class(a)(a) We can not add our own zero argument constructor to the structureWe can not add our own zero argument constructor to the structure
(b)(b) The structures are implicitly sealed . Hence structures can not be inheritedThe structures are implicitly sealed . Hence structures can not be inherited
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 167/210
167
167
Amjad Mehmood
Lec.IIT
(b)(b) The structures are implicitly sealed . Hence structures can not be inheritedThe structures are implicitly sealed . Hence structures can not be inherited
(c)(c) Being sealed structure can not be marked with abstract modifier.Being sealed structure can not be marked with abstract modifier.
(d)(d) Since structures can¶t be inherited , so their members can not have protected accessSince structures can¶t be inherited , so their members can not have protected accessmodifier . Also there can not be virtual methods in structure.modifier . Also there can not be virtual methods in structure.
(e)(e) Structure mebers can not be initialized with the point of declaration egStructure mebers can not be initialized with the point of declaration eg
struct mypointstruct mypoint
{{
int i=10;int i=10;int j=20;int j=20;
}}
This result in error . However if the member is static then we are permitted to initialize it.This result in error . However if the member is static then we are permitted to initialize it.
(f) The structures are(f) The structures are value typevalue type where as classes arewhere as classes are reference type.reference type.
Value type And Reference TypeValue type And Reference Type The data of value type gets store on the stack while the data of reference type gets stored onThe data of value type gets store on the stack while the data of reference type gets stored on
the heapthe heap
The variable of value type directly contains the data, whereas reference type containsThe variable of value type directly contains the data, whereas reference type contains
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 168/210
168
168
Amjad Mehmood
Lec.IIT
yp y , ypyp y , ypreferences or address of the data.references or address of the data.
10
20
10
20
Value Type Reference Type
C1
i
j
C1 Object
EXAMPLEEXAMPLE
Using System;Using System;
Namespace sample Namespace sample
{{
struct mystructstruct mystruct
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 169/210
169
169
Amjad Mehmood
Lec.IIT
struct mystructstruct mystruct
{{
public int I; public int I;
}}
class Class1class Class1
{{
static void Main(string [] args)static void Main(string [] args)
{{
mystruct x=new mystruct();mystruct x=new mystruct();
x.i=9;x.i=9;
mystruct y;mystruct y;
y=x;y=x;
y.i=5;y.i=5;
Console.WriteLine(x.i);Console.WriteLine(x.i);Console.WriteLine(y.i);Console.WriteLine(y.i);
}}
} OUTPUT} OUTPUT
} 5 5} 5 5
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 170/210
ADO.NetADO.Net
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 171/210
171171
Amjad Mehmood
Lec.IIT
.Net managed library that exposes functions to access data that exists outside of an.Net managed library that exposes functions to access data that exists outside of anapplication. i.e to access persistent data.application. i.e to access persistent data.
ADO.Net can work both in Connected and Disconnected Manner.ADO.Net can work both in Connected and Disconnected Manner.
Road To ADO.Net:Road To ADO.Net:
³Great things doest not come in impulse but it is a series of small steps.³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 seeSo ADO.Net is not such that comes in that shape directly that we seetoday. But it is a revolutionary form of Microsoft¶s Past technologies for today. But it is a revolutionary form of Microsoft¶s Past technologies for data access.data access.
To understand the history of ADO.Net and Microsoft Data AccessTo understand the history of ADO.Net and Microsoft Data AccessTechnologies, we need to understand the following.Technologies, we need to understand the following.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 172/210
172172
Amjad Mehmood
Lec.IIT
Translation Layer
Data Access Libs( DAO, RDO, ADO, and ADO.Net )
Data Providers ( ODBC and OLEDB )
To Connect to DB through
Can Talk to DB Providers with help of
Converts User¶s Call to appropriate Proprietary Function calls
Data Access Today:Data Access Today: (( ADO. Net )ADO. Net )
ADO. Net is developed for two basic goals.ADO. Net is developed for two basic goals.
1 To overcome the problems of existing data access technologies1 To overcome the problems of existing data access technologies
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 173/210
173173
Amjad Mehmood
Lec.IIT
1. To overcome the problems of existing data access technologies.1. To overcome the problems of existing data access technologies.
2. To cope up with the future data access methods.2. To cope up with the future data access methods.
ADO. Net Structure:ADO. Net Structure:
ADO. Net have two fundamental parts.ADO. Net have two fundamental parts.
i. DataSetsi. DataSets
ii. .Net Data Providersii. .Net Data Providers
i. DataSets:i. DataSets: Normally, used in Disconnected approach and is used to hold data that comes Normally, used in Disconnected approach and is used to hold data that comesfrom the database. Once, we get data in a dataset, we can insert, delete and updatefrom the database. Once, we get data in a dataset, we can insert, delete and update data in it as if itdata in it as if it
we are working with database.we are working with database.
ii. .Net Data Providersii. .Net Data Providers: .Net data providers are used to extract and post data to a: .Net data providers are used to extract and post data to adatabase. ADO. Net support three sort of providers.database. ADO. Net support three sort of providers.
a ). Data Provider for SQL Server b ). Data Provider for OLEDB c ). Data Provider for ODBCa ). Data Provider for SQL Server b ). Data Provider for OLEDB c ). Data Provider for ODBC
Each of these providers are contained within different namespaces.Each of these providers are contained within different namespaces.
ADO. Net O bjects and Classes:ADO. Net O bjects and Classes:
ADO. NetADO. Net objects can be divided into two categories.objects can be divided into two categories.
»» i. Data Provider O bjectsi. Data Provider O bjects
»» ii Consumer Objectsii Consumer Objects
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 174/210
174174
Amjad Mehmood
Lec.IIT
»» ii Consumer O bjectsii Consumer O bjects
DataSet
DataRelation
DataTable
DataRow
DataColoumn
Command
Connection
CommandBuilder
DataReader
DataReader
ADO. Net Consumer O bjects ADO. Net Provider O bjects
Data Provider O bjects:Data Provider O bjects: They are used to extract and post data to a data source. Once extracted the data is putThey 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 datainto the clients memory of client application. Separate provider objects are used to interact with different type of datasources.sources.
Data Consumer O bjects:Data Consumer O bjects: Consumer objects are used to hold and manipulate the data that is being extracted withConsumer objects are used to hold and manipulate the data that is being extracted with
id bj N ll h d h i h di d hid bj N ll h d h i h di d h
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 175/210
175175
Amjad Mehmood
Lec.IIT
provider objects. Normally, they are used when we are using the disconnected approach. provider objects. Normally, they are used when we are using the disconnected approach.
Database
Application
RAM Space Reserved for User Application
Provider O bjects Extract Data
And Places the extracted datain
Application reserved RAM
Extracted Data
Consumer O bjects hold and
manipulate the extracted data
Manipulated data is posted back to
database with provider objects
12
3
4
ADO. Net ProgrammingADO. Net Programming
.Net provides two ways to do database programming..Net provides two ways to do database programming.
1. Through Wizards and O bjects Manipulation1. Through Wizards and O bjects Manipulation
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 176/210
176176
Amjad Mehmood
Lec.IIT
2. Doing Everything by Coding2. Doing Everything by Coding
1. Wizards provides an easy way to build up database applications but they do not let you to do quite complex1. Wizards provides an easy way to build up database applications but they do not let you to do quite complex programming. programming.
2. Here programming is little harder but provide everything that you want to do with a database.2. Here programming is little harder but provide everything that you want to do with a database.
Example Program: ( Through Wizard )Example Program: ( Through Wizard )
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 177/210
( b ) Adding Data Adapter:( b ) Adding Data Adapter: Data Adapter isData Adapter isused to perform different sort of operations likeused to perform different sort of operations likeupdating data, filling data sets etc.updating data, filling data sets etc.
5. In toolbox, click on ³Data´ tab and select5. In toolbox, click on ³Data´ tab and select³S lD t Ad t ´ d i d ill t t t d Cli k³S lD t Ad t ´ d i d ill t t t d Cli k
5
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 178/210
178178
Amjad Mehmood
Lec.IIT
³SqlDataAdapter ́ and a wizard will get started.Click ³SqlDataAdapter ́ and a wizard will get started.Click ³Next´³Next´
6. In the Next, you are asked to select the ³Connection´ 6. In the Next, you are asked to select the ³Connection´ that you will use. So select your recently createdthat you will use. So select your recently created³Connection´ ³Connection´
7. In the next tab, you are asked to select the7. In the next tab, you are asked to select the
³SQL Query type´ and you most of times select³SQL Query type´ and you most of times select³Use Sql Statements´.Click Next³Use Sql Statements´.Click Next
and in the next click and in the next click
³Query Builder Button´.³Query Builder Button´.
6
7
8. Next you will be presented with all the tables present in the database. This time select8. Next you will be presented with all the tables present in the database. This time select³Customers´ click ³Add´ and then Close.³Customers´ click ³Add´ and then Close.
9. Next, you will be asked for selecting the ³fields´ in the table, Check all the fields tab and9. Next, you will be asked for selecting the ³fields´ in the table, Check all the fields tab andclick ³OK´ and ³Finish´ the wizard.click ³OK´ and ³Finish´ the wizard.
10. Right click on ³DataAdapter1´ object created through wizard and select ³Generate Data10. Right click on ³DataAdapter1´ object created through wizard and select ³Generate DataSet´ and if youSet´ and if you
8
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 179/210
179179
Amjad Mehmood
Lec.IIT
do not want to change its namedo not want to change its name
then just click ok.then just click ok.
( c ) Binding the controls: By binding we mean,( c ) Binding the controls: By binding we mean,
telling a control what data it is supposed totelling a control what data it is supposed to
display.display.
(i) Binding the Employee Name text Box:(i) Binding the Employee Name text Box:
select the text box and go to properties andselect the text box and go to properties and
click on ³Data Binding´ select tagclick on ³Data Binding´ select tag
And then click onAnd then click on
First Name.First Name.
In the similar way, Bind the second text Box to ³Phone´In the similar way, Bind the second text Box to ³Phone´
Bind ListBox Control to ³EmployeeID´Bind ListBox Control to ³EmployeeID´
Set the DataGrid DataSource property to ³Set the DataGrid DataSource property to ³mySet.Employees´mySet.Employees´
9
10
Double the form and add the following code.Double the form and add the following code.
sqlDataAdapter1.Fill(this.mySet,0,0,"Employees");sqlDataAdapter1.Fill(this.mySet,0,0,"Employees");
Explanation:Explanation: Fill method is used to fill the specified dataset (IstFill method is used to fill the specified dataset (Ist
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 180/210
180180
Amjad Mehmood
Lec.IIT
Explanation:Explanation: Fill method is used to fill the specified dataset (IstFill method is used to fill the specified dataset (Ist
argument) with data. The second argument specify where to startargument) with data. The second argument specify where to startfilling, the third argument specify how many records to retrievefilling, the third argument specify how many records to retrieveand the last is just a table that will be created in the specifiedand the last is just a table that will be created in the specifieddataset to hold the data.dataset to hold the data.
sqlDataAdapter1.Fill(dataSet11,0,0,"authors");sqlDataAdapter1.Fill(dataSet11,0,0,"authors");
dataGrid1.DataSource=dataSet11.authors;dataGrid1.DataSource=dataSet11.authors;
TheThe Command Command ClassesClasses
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 181/210
181181
Amjad Mehmood
Lec.IIT
There are three Command classes: SqlCommand,There are three Command classes: SqlCommand,OleDbCommand, and OdbcCommand. You use a Command objectOleDbCommand, and OdbcCommand. You use a Command objectto run a SQL statement, such as a SELECT, INSERT, UPDATE,to run a SQL statement, such as a SELECT, INSERT, UPDATE,or DELETE statement.or DELETE statement.
You can also use a Command objectYou can also use a Command object
to call a stored procedureto call a stored procedure
± ± retrieve rows from a specific table. You run the command stored in aretrieve rows from a specific table. You run the command stored in aCommand object using a Connection objectCommand object using a Connection object
CodingCoding class Class1class Class1
{{
/// <summary>/// <summary>
/// The main entry point for the application./// The main entry point for the application.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 182/210
182182
Amjad Mehmood
Lec.IIT
y p ppy p pp
/// </summary>/// </summary>
[STAThread][STAThread] static void Main(string[] args)static void Main(string[] args)
{{
string source = "server=File_Server;" +string source = "server=File_Server;" +
"uid=sa;pwd=;" +"uid=sa;pwd=;" +
"database=northwind" ;"database=northwind" ;
string select = "SELECT CustomerID,CompanyName,ContactName FR OMstring select = "SELECT CustomerID,CompanyName,ContactName FR OMCustomers" ;Customers" ;
SqlConnection conn = new SqlConnection( source ) ;SqlConnection conn = new SqlConnection( source ) ;
SqlDataAdapter da = new SqlDataAdapter ( select , conn ) ;SqlDataAdapter da = new SqlDataAdapter ( select , conn ) ;
DataSet ds = new DataSet() ;DataSet ds = new DataSet() ; da.Fill ( ds , "Customers") ;da.Fill ( ds , "Customers") ;
foreach ( DataRow row in ds.Tables["Customers"].Rows )foreach ( DataRow row in ds.Tables["Customers"].Rows )
Console.WriteLine ( "'{0}' from {1} {2}" , row[0] , row[1],row[2]) ;Console.WriteLine ( "'{0}' from {1} {2}" , row[0] , row[1],row[2]) ;
Console.ReadLine();Console.ReadLine();
/*/*
SelectIntoDataSet.csSelectIntoDataSet.cs
illustrates how to perform a SELECT statementillustrates how to perform a SELECT statement
and store the returned rows in a DataSet objectand store the returned rows in a DataSet object
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 183/210
183183
Amjad Mehmood
Lec.IIT
a d sto e t e etu ed ows a ataSet objecta d sto e t e etu ed ows a ataSet object
*/*/
using System;using System;
using System.Data;using System.Data;
using System.Data.SqlClient;using System.Data.SqlClient;
class SelectIntoDataSetclass SelectIntoDataSet
{{
public static void Main() public static void Main()
{{
// step 1: formulate a string containing the details of the// step 1: formulate a string containing the details of the
// database connection// database connection
string connectionStringstring connectionString
="server=kust;database=Northwind;uid=sa;pwd=sa";="server=kust;database=Northwind;uid=sa;pwd=sa";
// step 2: create a SqlConnection object to connect to the// step 2: create a SqlConnection object to connect to the
// database, passing the connection string to the constructor // database, passing the connection string to the constructor SqlConnection mySqlConnection =newSqlConnection mySqlConnection =new
// step 3: formulate a SELECT statement to retrieve the// step 3: formulate a SELECT statement to retrieve the
// CustomerID, CompanyName, ContactName, and Address// CustomerID, CompanyName, ContactName, and Address
// columns for the first ten rows from the Customers table// columns for the first ten rows from the Customers table
string selectString ="SELECT TOP 10 CustomerID, CompanyName,string selectString ="SELECT TOP 10 CustomerID, CompanyName,
dddd
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 184/210
184184
Amjad Mehmood
Lec.IIT
ContactName, Address "+ContactName, Address "+
"FR OM Customers " +"FR OM Customers " + "ORDER BY CustomerID";"ORDER BY CustomerID";
// step 4: create a SqlCommand object to hold the SELECT statement// step 4: create a SqlCommand object to hold the SELECT statement
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
// step 5: set the CommandText property of the SqlCommand object to// step 5: set the CommandText property of the SqlCommand object to
// the SELECT string// the SELECT string
mySqlCommand.CommandText = selectString;mySqlCommand.CommandText = selectString;
// step 6: create a SqlDataAdapter object// step 6: create a SqlDataAdapter object
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
// step 7: set the SelectCommand property of the SqlAdapter object// step 7: set the SelectCommand property of the SqlAdapter object
// to the SqlCommand object// to the SqlCommand object
mySqlDataAdapter.SelectCommand = mySqlCommand;mySqlDataAdapter.SelectCommand = mySqlCommand;
// step 8: create a DataSet object to store the results of // step 8: create a DataSet object to store the results of
// the SELECT statement// the SELECT statement
DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();
/ / step 9: open the database connection using the/ / step 9: open the database connection using the
// O pen() method of the SqlConnection object// O pen() method of the SqlConnection object
mySqlConnection.O pen();mySqlConnection.O pen();
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 185/210
185185
Amjad Mehmood
Lec.IIT
// step 10: use the Fill() method of the SqlDataAdapter object to// step 10: use the Fill() method of the SqlDataAdapter object to // retrieve the rows from the table, storing the rows locally// retrieve the rows from the table, storing the rows locally
// in a DataTable of the DataSet object// in a DataTable of the DataSet object
Console.WriteLine("Retrieving rows from the Customers table");Console.WriteLine("Retrieving rows from the Customers table");
mySqlDataAdapter.Fill(myDataSet,"Customers");mySqlDataAdapter.Fill(myDataSet,"Customers");
// step 11: close the database connection using the Close() method// step 11: close the database connection using the Close() method
// of the SqlConnection object created in Step 1// of the SqlConnection object created in Step 1
mySqlConnection.Close();mySqlConnection.Close();
// step 12: get the DataTable object from the DataSet object// step 12: get the DataTable object from the DataSet object
DataTable myDataTable = myDataSet.Tables["Customers"];DataTable myDataTable = myDataSet.Tables["Customers"];
// step 13: display the columns for each row in the DataTable,// step 13: display the columns for each row in the DataTable,
// using a DataRow object to access each row in the DataTable// using a DataRow object to access each row in the DataTable
foreach (DataRow myDataRowmyDataTable Rows)foreach (DataRow myDataRowmyDataTable Rows)
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 186/210
186186
Amjad Mehmood
Lec.IIT
foreach (DataRow myDataRowmyDataTable.Rows)foreach (DataRow myDataRowmyDataTable.Rows)
{Console.WriteLine("CustomerID = "+{Console.WriteLine("CustomerID = "+myDataRow["CustomerID"]);myDataRow["CustomerID"]);
Console.WriteLine("CompanyName = "+Console.WriteLine("CompanyName = "+myDataRow["CompanyName"]);myDataRow["CompanyName"]);
Console.WriteLine("ContactName = "+Console.WriteLine("ContactName = "+myDataRow["ContactName"]);myDataRow["ContactName"]);
Console.WriteLine("Address = "+Console.WriteLine("Address = "+myDataRow["Address"]);myDataRow["Address"]);
}}
}}
}}
Introduction to DataFormIntroduction to DataForm
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 187/210
187187
Amjad Mehmood
Lec.IIT
MYSQLCONNECTION.CSMYSQLCONNECTION.CS
/* MySqlConnection.cs illustrates how to use a SqlConnection object to connect to a SQL Server /* MySqlConnection.cs illustrates how to use a SqlConnection object to connect to a SQL Server database */database */
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 188/210
188188
Amjad Mehmood
Lec.IIT
using System;using System;
using System.Data;using System.Data;
using System.Data.SqlClient;using System.Data.SqlClient;
class MySqlConnectionclass MySqlConnection
{ {
public static void Main() public static void Main()
{ {
// formulate a string containing the details of the // database// formulate a string containing the details of the // database
connection string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa";connection string connectionString = "server=localhost;database=Northwind;uid=sa;pwd=sa";
// create a SqlConnection object to connect to the// create a SqlConnection object to connect to the
// database, passing the connection string to the constructor // database, passing the connection string to the constructor
SqlConnection mySqlConnection = new SqlConnection(connectionString);SqlConnection mySqlConnection = new SqlConnection(connectionString);
// open the database connection using the// open the database connection using the
// O pen() method of the SqlConnection object// O pen() method of the SqlConnection object
mySqlConnection.O pen();mySqlConnection.O pen();
// display the properties of the SqlConnection object// display the properties of the SqlConnection object
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 189/210
189189
Amjad Mehmood
Lec.IIT
// display the properties of the SqlConnection object// display the properties of the SqlConnection objectConsole.WriteLine("mySqlConnection.ConnectionString = "+ mySqlConnection.ConnectionString);Console.WriteLine("mySqlConnection.ConnectionString = "+ mySqlConnection.ConnectionString);
Console.WriteLine("mySqlConnection.ConnectionTimeout = "+Console.WriteLine("mySqlConnection.ConnectionTimeout = "+mySqlConnection.ConnectionTimeout);mySqlConnection.ConnectionTimeout);
Console.WriteLine("mySqlConnection.Database = "+ mySqlConnection.Database);Console.WriteLine("mySqlConnection.Database = "+ mySqlConnection.Database);
Console.WriteLine("mySqlConnection.DataSource = "+ mySqlConnection.DataSource);Console.WriteLine("mySqlConnection.DataSource = "+ mySqlConnection.DataSource);
Console.WriteLine("mySqlConnection.PacketSize = "+ mySqlConnection.PacketSize);Console.WriteLine("mySqlConnection.PacketSize = "+ mySqlConnection.PacketSize);
Console.WriteLine("mySqlConnection.ServerVersion = "+ mySqlConnection.ServerVersion);Console.WriteLine("mySqlConnection.ServerVersion = "+ mySqlConnection.ServerVersion);
Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State);Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State);
Console.WriteLine("mySqlConnection.WorkstationId = "+ mySqlConnection.WorkstationId);Console.WriteLine("mySqlConnection.WorkstationId = "+ mySqlConnection.WorkstationId);
// close the database connection using the Close() method // of the SqlConnection object// close the database connection using the Close() method // of the SqlConnection objectmySqlConnection.Close();mySqlConnection.Close();
}}
} }
The output from this program is as followsThe output from this program is as follows
mySqlConnection.ConnectionString =mySqlConnection.ConnectionString =server=localhost;database=Northwind;uid=sa;server=localhost;database=Northwind;uid=sa;
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 190/210
190190
Amjad Mehmood
Lec.IIT
mySqlConnection.ConnectionTimeout = 15mySqlConnection.ConnectionTimeout = 15
mySqlConnection.Database = NorthwindmySqlConnection.Database = Northwind
mySqlConnection.DataSource = localhostmySqlConnection.DataSource = localhost
mySqlConnection.PacketSize = 8192mySqlConnection.PacketSize = 8192
mySqlConnection.ServerVersion = 08.00.0194mySqlConnection.ServerVersion = 08.00.0194
mySqlConnection.State = O penmySqlConnection.State = O pen
mySqlConnection.WorkstationId = JMPRICEmySqlConnection.WorkstationId = JMPRICE--DT1DT1
CONNECTIONPOOLING.CSCONNECTIONPOOLING.CS
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 191/210
191191
Amjad Mehmood
Lec.IIT
/* ConnectionPooling.cs illustrates connection pooling */ using System;/* ConnectionPooling.cs illustrates connection pooling */ using System;
using System.Data;using System.Data;
using System.Data.SqlClient;using System.Data.SqlClient;
class ConnectionPoolingclass ConnectionPooling
{{
public static void Main() public static void Main()
{ {
// create a SqlConnection object to connect to the database,// 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(// 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" );"server=localhost;database=Northwind;uid=sa;pwd=sa;" + "max pool size=10;min pool size=5" );
// open the SqlConnection object 10 times// open the SqlConnection object 10 times
for (int count = 1; count <= 10; count++)for (int count = 1; count <= 10; count++)
{{
Console.WriteLine("count = "+ count);Console.WriteLine("count = "+ count);
// create a DateTime object and set it to the// create a DateTime object and set it to the
// current date and time// current date and time
DateTime start = DateTime.Now;DateTime start = DateTime.Now;
CONNECTIONPOOLING.CSCONNECTIONPOOLING.CS // open the database connection using the// open the database connection using the
// O pen() method of the SqlConnection object// O pen() method of the SqlConnection object
mySqlConnection.Open();mySqlConnection.Open();
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 192/210
192192
Amjad Mehmood
Lec.IIT
mySqlConnection.O pen();mySqlConnection.O pen();
// subtract the current date and time from the start,// subtract the current date and time from the start, // storing the difference in a TimeSpan// storing the difference in a TimeSpan
TimeSpan timeTaken = DateTime.NowTimeSpan timeTaken = DateTime.Now -- start;start;
// display the number of milliseconds taken to open// display the number of milliseconds taken to open
// the connection// the connection
Console.WriteLine("Milliseconds = "+ timeTaken.Milliseconds);Console.WriteLine("Milliseconds = "+ timeTaken.Milliseconds);
// display the connection state// display the connection state
Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State);Console.WriteLine("mySqlConnection.State = "+ mySqlConnection.State);
// close the database connection using the Close() method// close the database connection using the Close() method
// of the SqlConnection object// of the SqlConnection object
mySqlConnection.Close();mySqlConnection.Close();
}}
count = 1 Milliseconds = 101count = 1 Milliseconds = 101
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 2count = 2
Milliseconds = 0Milliseconds = 0
The output from this program is as follows
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 193/210
193193
Amjad Mehmood
Lec.IIT
Milliseconds 0Milliseconds 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 3count = 3
Milliseconds = 0Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 4count = 4
Milliseconds = 0Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 5count = 5
Milliseconds = 0Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 6count = 6
Milliseconds = 0Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 7count = 7
Milliseconds = 0Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 8 Milliseconds = 0count = 8 Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 9count = 9
Milliseconds = 0Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
count = 10count = 10
Milliseconds = 0Milliseconds = 0
mySqlConnection.State = O penmySqlConnection.State = O pen
Use the GetOrdinal() method of the DataReader objectUse the GetOrdinal() method of the DataReader object
using System;using System;
using System.Data;using System.Data;
using System.Data.SqlClient;using System.Data.SqlClient;
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 194/210
194194
Amjad Mehmood
Lec.IIT
g y q ;g y q ;
class UsingColumnOrdinalsclass UsingColumnOrdinals {{
public static void Main() public static void Main()
{{
SqlConnection mySqlConnection = new SqlConnection(SqlConnection mySqlConnection = new SqlConnection("server=localhost;database=Northwind;uid=sa;pwd=sa" );"server=localhost;database=Northwind;uid=sa;pwd=sa" );
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice, " +mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice, " +"UnitsInStock, Discontinued " + "FR OM Products " + "ORDER BY ProductID";"UnitsInStock, Discontinued " + "FR OM Products " + "ORDER BY ProductID";
mySqlConnection.O pen();mySqlConnection.O pen();
SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader();SqlDataReader productsSqlDataReader = mySqlCommand.ExecuteReader();
// use the GetOrdinal() method of the DataReader object// use the GetOrdinal() method of the DataReader object
// to obtain the numeric positions of the columns// to obtain the numeric positions of the columns
int productIDColPos =int productIDColPos =
productsSqlDataReader.GetOrdinal("ProductID");productsSqlDataReader.GetOrdinal("ProductID");
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 195/210
195195
Amjad Mehmood
Lec.IIT
p oductsSq ata eade .GetO d a ( oduct );p oductsSq ata eade .GetO d a ( oduct );
int productNameColPos =int productNameColPos = productsSqlDataReader.GetOrdinal("ProductName"); productsSqlDataReader.GetOrdinal("ProductName");
int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice");int unitPriceColPos = productsSqlDataReader.GetOrdinal("UnitPrice");
int unitsInStockColPos =int unitsInStockColPos = productsSqlDataReader.GetOrdinal("UnitsInStock"); productsSqlDataReader.GetOrdinal("UnitsInStock");
int discontinuedColPos =int discontinuedColPos =
productsSqlDataReader.GetOrdinal("Discontinued"); productsSqlDataReader.GetOrdinal("Discontinued");
Reading Rows from aReading Rows from a SqlDataReader SqlDataReader ObjectObject
You read the rows from a DataReader object using the Read() method. This method returns theYou read the rows from a DataReader object using the Read() method. This method returns theBoolean true value when there is another row to read, otherwise it returns false.Boolean true value when there is another row to read, otherwise it returns false.
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 196/210
196196
Amjad Mehmood
Lec.IIT
Let's take a look at two code snippets that illustrate these two ways of reading column values. TheLet's take a look at two code snippets that illustrate these two ways of reading column values. Thefirst code snippet uses the column names to read the column values:first code snippet uses the column names to read the column values:
while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader ["ProductID"]);while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader ["ProductID"]);Console.WriteLine(productsSqlDataReader ["ProductName"]);Console.WriteLine(productsSqlDataReader ["ProductName"]);Console.WriteLine(productsSqlDataReader ["UnitPrice"]);Console.WriteLine(productsSqlDataReader ["UnitPrice"]);Console.WriteLine(productsSqlDataReader ["Discontinued"]); } Console.WriteLine(productsSqlDataReader ["Discontinued"]); }
The second code snippet uses the numeric column positions to read the column values:The second code snippet uses the numeric column positions to read the column values:
while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader [0]);while (productsSqlDataReader.Read()) { Console.WriteLine(productsSqlDataReader [0]);Console.WriteLine(productsSqlDataReader [1]); Console.WriteLine(productsSqlDataReader [2]);Console.WriteLine(productsSqlDataReader [1]); Console.WriteLine(productsSqlDataReader [2]);Console.WriteLine(productsSqlDataReader [3]); } Console.WriteLine(productsSqlDataReader [3]); }
while (productsSqlDataReader.Read())while (productsSqlDataReader.Read()) { {
Console.WriteLine("ProductID = " + productsSqlDataReader [ productIDColPos]);Console.WriteLine("ProductID = " + productsSqlDataReader [ productIDColPos]);
Console.WriteLine("ProductName = " + productsSqlDataReader [ productNameColPos]);Console.WriteLine("ProductName = " + productsSqlDataReader [ productNameColPos]);
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 197/210
197197
Amjad Mehmood
Lec.IIT
Console.WriteLine("UnitPrice = " + productsSqlDataReader [unitPriceColPos]);Console.WriteLine("UnitPrice = " + productsSqlDataReader [unitPriceColPos]);
Console.WriteLine("UnitsInStock = " + productsSqlDataReader [unitsInStockColPos]);Console.WriteLine("UnitsInStock = " + productsSqlDataReader [unitsInStockColPos]);
Console.WriteLine("Discontinued = " + productsSqlDataReader [discontinuedColPos]);Console.WriteLine("Discontinued = " + productsSqlDataReader [discontinuedColPos]);
}}
productsSqlDataReader.Close(); productsSqlDataReader.Close();
mySqlConnection.Close();mySqlConnection.Close();
}}
} }
while (productsSqlDataReader.Read())while (productsSqlDataReader.Read())
{{
int productID = productsSqlDataReader.GetInt32(productIDColPos);int productID = productsSqlDataReader.GetInt32(productIDColPos);Console.WriteLine("productID = " + productID);Console.WriteLine("productID = " + productID);
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 198/210
198198
Amjad Mehmood
Lec.IIT
string productName = productsSqlDataReader.GetString(productNameColPos);string productName = productsSqlDataReader.GetString(productNameColPos);Console.WriteLine("productName = " + productName);Console.WriteLine("productName = " + productName);
decimal unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);decimal unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);Console.WriteLine("unitPrice = " + unitPrice);Console.WriteLine("unitPrice = " + unitPrice);
short unitsInStock = productsSqlDataReader.GetInt16(unitsInStockColPos);short unitsInStock = productsSqlDataReader.GetInt16(unitsInStockColPos);Console.WriteLine("unitsInStock = " + unitsInStock);Console.WriteLine("unitsInStock = " + unitsInStock);
bool discontinued = productsSqlDataReader.GetBoolean(discontinuedColPos); bool discontinued = productsSqlDataReader.GetBoolean(discontinuedColPos);Console.WriteLine("discontinued = " + discontinued);Console.WriteLine("discontinued = " + discontinued);
} }
Boxing and UnBoxingBoxing and UnBoxing
while (productsSqlDataReader.Read())while (productsSqlDataReader.Read())
{{
object productID = productsSqlDataReader [ productIDColPos];object productID = productsSqlDataReader [ productIDColPos];
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 199/210
199199
Amjad Mehmood
Lec.IIT
object productName = productsSqlDataReader [ productNameColPos];object productName = productsSqlDataReader [ productNameColPos];
object unitPrice = productsSqlDataReader [unitPriceColPos];object unitPrice = productsSqlDataReader [unitPriceColPos];
object unitsInStock = productsSqlDataReader [unitsInStockColPos];object unitsInStock = productsSqlDataReader [unitsInStockColPos];
object discontinued = productsSqlDataReader [discontinuedColPos];object discontinued = productsSqlDataReader [discontinuedColPos];
Console.WriteLine("productID = " + productID); Console.WriteLine("productName = "Console.WriteLine("productID = " + productID); Console.WriteLine("productName = "+ productName); Console.WriteLine("unitPrice = " + unitPrice);+ productName); Console.WriteLine("unitPrice = " + unitPrice);Console.WriteLine("unitsInStock = " + unitsInStock); Console.WriteLine("discontinuedConsole.WriteLine("unitsInStock = " + unitsInStock); Console.WriteLine("discontinued= " + discontinued);= " + discontinued);
} }
If U want to use it furtherIf U want to use it further
decimal newUnitPrice = (decimal) unitPrice * 1.2m;decimal newUnitPrice = (decimal) unitPrice * 1.2m;
Reading Null ValuesReading Null Values
you'll get the following exception:you'll get the following exception:
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 200/210
200200
Amjad Mehmood
Lec.IIT
you ll get the following exception:you ll get the following exception:
System.Data.SqlTypes.SqlNullValueExceptionSystem.Data.SqlTypes.SqlNullValueException
You can check if a column contains a null value using the IsDBNull()You can check if a column contains a null value using the IsDBNull()method of a DataReader object.method of a DataReader object.
This method returns a Boolean true or false value that indicatesThis method returns a Boolean true or false value that indicateswhether the column value is null.whether the column value is null.
You can then use that Boolean result to decide what to do. For You can then use that Boolean result to decide what to do. For example:example:
if (productsSqlDataReader.IsDBNull(unitPriceColPos))if (productsSqlDataReader.IsDBNull(unitPriceColPos))
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 201/210
201201
Amjad Mehmood
Lec.IIT
{{ Console.WriteLine("UnitPrice column contains a null value");Console.WriteLine("UnitPrice column contains a null value");
}}
elseelse
{{
unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);unitPrice = productsSqlDataReader.GetDecimal(unitPriceColPos);
} }
/*/*
ExecuteMultipleSelects.cs illustrates how to executeExecuteMultipleSelects.cs illustrates how to execute
multiple SELECT statements using a SqlCommand objectmultiple SELECT statements using a SqlCommand object
and read the results using a SqlDataReader objectand read the results using a SqlDataReader object
*/*/
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 202/210
202202
Amjad Mehmood
Lec.IIT
using System;using System;
using System.Data;using System.Data;
using System.Data.SqlClient;using System.Data.SqlClient;
class ExecuteSelectclass ExecuteSelect {{
public static void Main() public static void Main()
{{
SqlConnection mySqlConnection =new SqlConnection(SqlConnection mySqlConnection =new SqlConnection(
"server=localhost;database=Northwind;uid=sa;pwd=sa");"server=localhost;database=Northwind;uid=sa;pwd=sa");
SqlCommand mySqlCommand =SqlCommand mySqlCommand =
mySqlConnection.CreateCommand();mySqlConnection.CreateCommand();
// set the CommandText property of the SqlCommand object to// set the CommandText property of the SqlCommand object to
// the mutliple SELECT statements// the mutliple SELECT statements
mySqlCommand.CommandText =mySqlCommand.CommandText =
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 203/210
203203
Amjad Mehmood
Lec.IIT
mySqlCommand.CommandText mySqlCommand.CommandText
"SELECT TOP 5 ProductID, ProductName " +"SELECT TOP 5 ProductID, ProductName " +
"FR OM Products " +"FR OM Products " +
"ORDER BY ProductID;" +"ORDER BY ProductID;" +
"SELECT TOP 3 CustomerID, CompanyName"SELECT TOP 3 CustomerID, CompanyName" +" +
"FR OM Customers " +"FR OM Customers " + "ORDER BY CustomerID;" +"ORDER BY CustomerID;" +
"SELECT TOP 6 OrderID, CustomerID " +"SELECT TOP 6 OrderID, CustomerID " + "FR OM Orders " +"FR OM Orders " +
"ORDER BY OrderID;";"ORDER BY OrderID;";
mySqlConnection.O pen();mySqlConnection.O pen();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader();
// read the result sets from the SqlDataReader object using// read the result sets from the SqlDataReader object using
// the Read() and NextResult() methods// the Read() and NextResult() methods
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 204/210
204204
Amjad Mehmood
Lec.IIT
// the Read() and NextResult() methods// the Read() and NextResult() methods
dodo
{{
while (mySqlDataReader.Read())while (mySqlDataReader.Read())
{{
Console.WriteLine("mySqlDataReader [0] = " +Console.WriteLine("mySqlDataReader [0] = " +
mySqlDataReader [0]);mySqlDataReader [0]);
Console.WriteLine("mySqlDataReader [1] = " +Console.WriteLine("mySqlDataReader [1] = " +
mySqlDataReader [1]);mySqlDataReader [1]);
}}
Console.WriteLine(""); // visually split the resultsConsole.WriteLine(""); // visually split the results
} while (mySqlDataReader.NextResult());} while (mySqlDataReader.NextResult());
mySqlDataReader.Close();mySqlDataReader.Close();
mySqlConnection.Close();mySqlConnection.Close();
}}
}}
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 205/210
// create a SqlDataAdapter object and set its SelectCommand// create a SqlDataAdapter object and set its SelectCommand
// property to the SqlCommand object// property to the SqlCommand object
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand =SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand =mySqlCommand;mySqlCommand;
// create a DataSet object// create a DataSet object
DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 206/210
206206
Amjad Mehmood
Lec.IIT
DataSet myDataSet new DataSet();DataSet myDataSet new DataSet();
// open the database connection mySqlConnection.O pen(); // use the Fill() method of the SqlDataAdapter // open the database connection mySqlConnection.O pen(); // use the Fill() method of the SqlDataAdapter object toobject to
// retrieve the rows from the table, storing the rows locally // in a DataTable of the DataSet object// retrieve the rows from the table, storing the rows locally // in a DataTable of the DataSet objectConsole.WriteLine("Retrieving rows from the Products table");Console.WriteLine("Retrieving rows from the Products table");
int number OfRows = mySqlDataAdapter.Fill(myDataSet, "Products");int number OfRows = mySqlDataAdapter.Fill(myDataSet, "Products");
Console.WriteLine("number OfRows = " + number OfRows);Console.WriteLine("number OfRows = " + number OfRows);
// close the database connection// close the database connection
mySqlConnection.Close();mySqlConnection.Close();
// get the DataTable object from the DataSet object// get the DataTable object from the DataSet object
DataTable myDataTable = myDataSet.Tables["Products"];DataTable myDataTable = myDataSet.Tables["Products"];
// display the column values for each row in the DataTable,// display the column values for each row in the DataTable,
// using a DataRow object to access each row in the DataTable// using a DataRow object to access each row in the DataTable
foreach (DataRow myDataRow in myDataTable.Rows)foreach (DataRow myDataRow in myDataTable.Rows)
{{ Console.WriteLine("ProductID = " + myDataRow["ProductID"]); Console.WriteLine("ProductName = " +Console.WriteLine("ProductID = " + myDataRow["ProductID"]); Console.WriteLine("ProductName = " +
myDataRow["ProductName"]); Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);myDataRow["ProductName"]); Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
}}
}}
} }
/*/*
PopulateDataSetUsingRange.cs illustrates how to populate a DataSetPopulateDataSetUsingRange.cs illustrates how to populate a DataSet
object with a range of rows from a SELECT statementobject with a range of rows from a SELECT statement */*/
using System;using System;
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 207/210
207207
Amjad Mehmood
Lec.IIT
using System.Data;using System.Data;
using System.Data.SqlClient;using System.Data.SqlClient;
class PopulateDataSetUsingRangeclass PopulateDataSetUsingRange
{{
public static void Main() public static void Main()
{{
SqlConnection mySqlConnection =SqlConnection mySqlConnection =
new SqlConnection(new SqlConnection(
"server=kust;database=Northwind;uid=sa;pwd=sa""server=kust;database=Northwind;uid=sa;pwd=sa"
););
// create a SqlCommand object and set its CommandText property// create a SqlCommand object and set its CommandText property
// to a SELECT statement that retrieves the top 5 rows from// to a SELECT statement that retrieves the top 5 rows from
// the Products table// the Products table
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText =mySqlCommand.CommandText = "SELECT TOP 5 ProductID, ProductName, UnitPrice " +"SELECT TOP 5 ProductID, ProductName, UnitPrice " +
"FR OM Products " +"FR OM Products " +
"ORDER BY ProductID";"ORDER BY ProductID";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();
mySqlConnection.O pen();mySqlConnection.O pen();
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 208/210
208208
Amjad Mehmood
Lec.IIT
// use the Fill() method of the SqlDataAdapter object to// use the Fill() method of the SqlDataAdapter object to // retrieve the rows from the table, storing a range of rows// retrieve the rows from the table, storing a range of rows
// in a DataTable of the DataSet object// in a DataTable of the DataSet object
Console.WriteLine("Retrieving rows from the Products table");Console.WriteLine("Retrieving rows from the Products table");
int number OfRows = mySqlDataAdapter.Fill(myDataSet, 1, 3, "Products");int number OfRows = mySqlDataAdapter.Fill(myDataSet, 1, 3, "Products");
Console.WriteLine("number OfRows = " + number OfRows); mySqlConnection.Close();Console.WriteLine("number OfRows = " + number OfRows); mySqlConnection.Close(); DataTable myDataTable = myDataSet.Tables["Products"];DataTable myDataTable = myDataSet.Tables["Products"];
foreach (DataRow myDataRow in myDataTable.Rows)foreach (DataRow myDataRow in myDataTable.Rows)
{{
Console.WriteLine("ProductID = " + myDataRow["ProductID"]);Console.WriteLine("ProductID = " + myDataRow["ProductID"]);Console.WriteLine("ProductName = " + myDataRow["ProductName"]);Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);Console.WriteLine("UnitPrice = " + myDataRow["UnitPrice"]);
}}
}}
} }
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 209/210
mySqlCommand.Parameters.Add(mySqlCommand.Parameters.Add( "@CustomerID", SqlDbType.NVarChar, 5).Value = "ALFK I";"@CustomerID", SqlDbType.NVarChar, 5).Value = "ALFK I";
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter();
mySqlDataAdapter.SelectCommand = mySqlCommand;mySqlDataAdapter.SelectCommand = mySqlCommand;
DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();
8/7/2019 LECTUR#01 visualProgramming31-10-2006
http://slidepdf.com/reader/full/lectur01-visualprogramming31-10-2006 210/210
DataSet myDataSet = new DataSet();DataSet myDataSet = new DataSet();
mySqlConnection.O pen();mySqlConnection.O pen();
Console.WriteLine("Retrieving rows from the CustOrderHist() Procedure");Console.WriteLine("Retrieving rows from the CustOrderHist() Procedure");
int number OfRows = mySqlDataAdapter.Fill(myDataSet, "CustOrderHist");int number OfRows = mySqlDataAdapter.Fill(myDataSet, "CustOrderHist");
Console.WriteLine("number OfRows = " + number OfRows);Console.WriteLine("number OfRows = " + number OfRows);
mySqlConnection.Close();mySqlConnection.Close();
DataTable myDataTable = myDataSet.Tables["CustOrderHist"];DataTable myDataTable = myDataSet.Tables["CustOrderHist"];
foreach (DataRow myDataRow in myDataTable.Rows)foreach (DataRow myDataRow in myDataTable.Rows)
{{
Console.WriteLine("ProductName = " + myDataRow["ProductName"]);Console.WriteLine("ProductName = " + myDataRow["ProductName"]);
Console.WriteLine("Total = " + myDataRow["Total"]);Console.WriteLine("Total = " + myDataRow["Total"]);