Vous êtes sur la page 1sur 28

Clear() fn remove all the iteams frm combobox

Eg. Comboboxname.Iteams.Clear();

Use new formname().Show(); to jump on new form frm previous form.

Use formname.hide(); to hide the form.


Use dispose() method to end the form.

HANDLING THE CONTROLS OF ONE FORM FRM OTHER FORM


THIS IS TO ENABLE THE BUTTON IN FORM 1 FRM FORM 2

IN FORM 1
Form2 f = new Form2();
this.AddOwnedForm(f); //FORM 1 BECOMES OWNER OF FORM 2
f.Show();//FORM 2 DISPLAYS
this.Hide();//FORM 1 HIDES

IN FORM 2
this.Owner.Controls["button1"].Enabled = true;//CHANGING THE PROPERTY
//OF BUTTON IN FORM1 FROM
//FORM2

Form f = this.Owner;//F CONTAINS OWNER OF FORM2 ….IE. FORM1


f.Show();

wizardcup2009.com

1-30march registration
12 phases
 Project Title & Description
 Module Breakup
 Data Dictionary
30 July  last date for submission
9 aug  presentation for 20 teams
15 aug  prize distribution for 10 teams
First 3  Cash prize, Cup, Certificates
Next 7  Gift, Cup, Ceritification
Invitation to join Wizard  HR Round + Presentation
Mentors+HOD+ Institutes  gifts/certificate

What is .NET?
What is Framework?
What is .NET Framework?
What is Mono?

Technical Programmes
• Pursing .NET 2008 with Framework 2.0 and 3.5 using C# and VB from
Impeccable Educational Trainers Private Limited (An ISO 9001:2000 Certified
Company), Ghaziabad

Technical Knowledge
• .NET Technologies : Visual C#, Visual Basic, ASP.NET 2.0 & 3.5, ADO.NET,
Remoting, I18N, AJAX, Localization, GDI+
• Frameworks : .NET 2.0 & 3.5, Mono
• GUI Tools : Visual Studio.NET 2005 & 2008
• RDBMS : MS Access, SQL Express 2005, SQL Server 2005, Oracle
• Reporting Tools : Crystal Report 11

.NET is a technology from Microsoft. It is based on .NET Framework that provides a set
of APIs called assemblies or dynamic link libraries (DLL) for software development.
These assemblies provide a big set of namespaces and their classes, interfaces,
structures etc. for almost activities of development.

.NET Frameworks works with Windows OS only. To run the .NET applications on other
platforms Novell provides a new framework called Mono that allows to .NET
applications written with C# on any platform.

A framework is a set of rules and tools for .NET development. It is provided a free
distributed and must to run any .NET based application. Different .NET framework
versions are
• 1.0
• 1.1
• 2.0
• 3.0
• 3.5

Components of .NET Framework


• Common Base Library or Assemblies that provide common classes for all .NET
based languages
• Choice multiple languages
o Visual Basic, C#, J# (Microsoft)
o Effil.NET, Ruby.NET etc. (third party)
• Common Type System (CTS)
o C# (int – 4 byte) VB (Integer-4 byte)  System.Int32
• Compilers
• All compilers produce the common format of output as MSIL (Microsoft
Intermediate Language)
• .NET compiled code is interoperable
• Common Languages Specifications (CLS)
o Provides a set of rules to create interoperable code
o A program to be interoperable must be CLS-Compliant
• Common Language Runtime (CLR)
o Software used to run the .NET application

Source file (.cs/.vb/.js etc.)  compiler  .exe/.dll (MSIL)  CLR (class loaders 
code verifier  just-in-time compiler  binary)  Execution

Framework is installed in Windows directory under Micrsoft.NET folder


Features of .NET

1. All kind of applications can be developed using only one language


2. Only one software called CLR is enough to run any kind of .NET based
applications
3. Removal of “DLL Hell”. No need to register the DLLs into Windows Registry
4. All .NET bases languages are Object Oriented
5. Neat and client installation and de-installation
6. A very good GUI for Rapid Application Development with Visual Studio.NET

Requirements

1. OS : Windows 2K+
2. Web Server : IIS 5.0+
3. .NET Framework 2.0+
4. Visual Studio.NET 2005+
a. Express (Free)
b. Standard Edition
c. Professional Edition
d. Team Suite

Terminologies in .NET

Assembly  Smallest unit for deployment in the form of .DLL/.EXE created based on
.NET Framework. It contains a set of Namespaces

Namespace  is a collection of classes, structures, enumerators, interfaces etc.

Class  A template or set of specifications to define similar kind of objects. It contains


different elements
• Fields
• Methods
• Properties
• Indexers
• Delegates

Example
MSCoreLib.dll  Assembly
System namespace
Console class
static void Write()
static void WriteLine()
static String ReadLine()

Conventions used in C#.NET


• All keyword always in lower case
• All class names, field names, method names etc. start with caps (Pascal Case)
• Start the interface names with I

Using C# as Programming Language


- A language of .NET based on C++ and Java
- Case sensitive
- Files must be saved as .cs
- Every executable program must have an entry point called Main()
o public static void Main()
o public static void Main(string []args)
o public static int Main()
o public static int Main(string []args)

Compiling the C# program

CSC <programename>

Example
CSC First.cs  First.exe

Note: Use ILDASM (Intermediate Language De-assembler) to view the IL code

ILDASM <filename>

Example
ILDASM First.exe
11.01.2009

Importing the namespace

- Use using keyword to import the namespace

using System;

Console.WriteLine(“Hello”);

Creating Aliases for class or namespace


- Use the using keyword again

using <aliasname>=<classname with path>;

Example
using c=System.Console;
c.WriteLine(“Hello”);

Creating DOS (Console) Applications using Visual Studio.NET


- Select File New  Project  Visual C#  Console Application
- Define the location and project name
- Use Ctrl+F5 to run the application rather than F5

Mode of operations
- Debug Mode
- Release Mode

Data Types in C#
1. Value Type (Structures)
2. Reference Type (Classes)
3. User Defined Data Types (UDT)
- Class, Structure, Enumerator etc.

Values Types
- Integrals
i. byte – 1 byte
ii. short – 2 byte
iii. int – 4 byte
iv. long – 8 byte
v. sbyte -1 byte
vi. ushort
vii. uint
viii. ulong
- Floats
i. float – 4 bytes (6/7 dp)
ii. double – 8 bytes (15/16 dp)
iii. decimal – 16 bytes (28 dp)
- Booleans
i. bool – 1 byte
- Characters
i. char – 2 byte
Reference Types
string
object

Note: C# allows using keywords as identifiers if preceded with @

string @double;

Literals

- The values used directly without input are called as literals or literal values
- Integrals
i. Default is int
ii. Use l or L for long and u or U for unsigned as suffix
1. int n=6;
2. long k=7L;
- Floats
i. Default is double
ii. Use f or F for floats and m or M for decimals
1. double a=5.6;
2. float b=6.7f;
3. decimal p=5.9M;
- Boolean
i. Only true or false can byte used
ii. Default is false
iii. bool married=true;
- Characters
i. Same is C
- String literals
i. Use double quotes to enclose
ii. Each string is treated as object
iii. Use @ if escape sequence is used
1. string file=@”c:\kavita\abc”;
iv. Use @ to create pre-formatted strings as well

Output Styles

Java Style
Cstyle
int a = 4, b = 6;
System.Console.WriteLine("Sum of " + a + " and " + b + " is " + (a + b));
System.Console.WriteLine("Sum of {0} and {1} is {2}", a, b, a + b);
24.01.2009
Working with arrays
- An array a is a variable to hold multiple values of similar type
- Types of Arrays
i. Rectangular Arrays
ii. Jagged Array

Rectangular Array
- An array that has equal number of columns in each row
- Arrays are treated as object
- Each array provides Length property
- Use GetLength() method to know about specific dimension
- Types of Rectangular Array
i. Single Dimensional Array
1. int []num=new int[5];
ii. Double Dimensional
1. int [,]num=new int[3,4];
iii. Multi-Dimensional
1. int [,,]num=new int[3,4,5];

Jagged Array
- An within array is called as jagged array

int [][]num=new int[5][];


num[0]=new int[5];
num[1]=new int[6];
num[2]=new int[7];

num[0][2]=55;

Introduction of foreach loop

- Used to work on a loop with size and index

foreach(datatype variable in arrayname or collection)


{
}

Reading Data from Keyboard


- Use ReadLine() method of Console class
i. string ReadLine()
- To convert data from string to other value types use Parse() method of
corresponding

int age=int.Parse(c.ReadLine());

Example
Get name and age of a person and check for validity of voter

Using CommandLine Input


- When passing data from DOS Prompt while running a program, it is called
as command line input
Voter Rajesh 44

public static void Main(string []args)


args[0]  Rajesh
args[1]  44

Dealing a program having multiple entry points

For DOS Compilations


- Use /main switch to define the class name to be used as entry point

CSC /main:First MultiMain.cs

For Visual Studio.NET


- Define the current class from
i. Project Project Properties  Startup Object

Defining the Output FileName


- We can define the output filename at the time of compilation
- Use /out switch to define the name of the file

CSC /out:filename.exe programname.cs

25.01.2008

Object Oriented Programming System (OOPs)

- A methodology for better project management using a set of rules


- It is based on the concept of class and objects and four main pillars of
OOPs
i. Encapsulation
ii. Abstraction
iii. Polymorphism
iv. Inheritance

Class?
- A class is a set of specification or blueprint or template about an entity
- Defines the attributes and behavior to be applied on a kind of entity
- Use class keyword to define a class

class <classname>
{
//members
}

Types of members in a class

1. Static or Class Members – Use static keyword with such members


2. Non-Static or Instance Members

Categories of Members
1. field
a. To hold the value
i. Variable
ii. constant
1. const int num=56;
iii. readonly fields
1. Assigned the value like a constant or at the time of object
creation through constructor. Cannot be change thereafter
2. Use readonly keyword
2. Methods
a. General methods
b. Abstract Methods
i. A method having the signature but no body contents
ii. Can be declared inside a class or interface
iii. If declared inside a class use abstract keyword but no keyword is
required for interfaces
iv. If a class contains any abstract method, it must be declared as
abstract
c. Sealed Methods
i. The method that can never be overridden
ii. Use sealed keyword
3. Properties
4. Indexers
5. Delegates

Passing arguments to the methods


1. Pass by value
2. Pass by reference (ref keyword)
3. Pass by output (out keyword)
4. Pass by params (params keyword)
5. Pass by address (using pointers)

31.01.2009

Using Pointers in C#

- When using pointers in C# the code is called as un-managed code. This


code is placed in separate area of memory called as un-managed area.
- Use unsafe keyword to define the unsafe section of the program and
instruct the compiler that the program contains the unmanaged code
- Use /unsafe switch for compilations
Example
//using pointers
class PointerTest
{
unsafe static void Swap(int *a, int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
public static void Main()
{
int x=5,y=6;
unsafe
{
Swap(&x,&y);
}
System.Console.WriteLine("x is {0} and y is {1}",x,y);
}

csc /unsafe PointerTest.cs

Properties

- A special procedures that behaves like a field used to work with some
value
- Property get created using get and set blocks

<returntype> <propertyname>
{
set
{
variable=value;
}
get
{
return variable;
}
}

- Properties can be of three types


i. Read/Write
ii. Read Only
iii. Write Only
07.02.2009

Indexers

- Special property a name


- It is an anonymous property
- It is used to access an element of an object using an index with the object
where the object is not an array

Example 1
class Indexer1
{
public static void Main()
{
string s="Rakesh";
System.Console.WriteLine("Second character is {0}",s[1]);
}
}

Delegates

- A delegates are the classes used to invoke the methods indirectly


- We need to define the delegates with delegate keyword as per the method
requirements

Example
using c=System.Console;
class DlgTest
{
delegate void MyDlg(double x, double y);

public static void Add(double a, double b)


{
c.WriteLine("Sum is {0}",a+b);
}
public static void Product(double x, double y)
{
c.WriteLine("Product is : {0}", x*y);
}

public static void Main()


{
double n1,n2;
c.WriteLine("Enter two numbers ");
n1=double.Parse(c.ReadLine());
n2=double.Parse(c.ReadLine());

MyDlg md;
int choice;
c.WriteLine("1: Add");
c.WriteLine("2: Product");
c.WriteLine("3: Both");
choice=int.Parse(c.ReadLine());
if(choice==1)
md=new MyDlg(Add);
else if (choice==2)
md=new MyDlg(Product);
else
{
md=new MyDlg(Add)+new MyDlg(Product);
}

md(n1,n2);
}
}

Object Oriented Programming System

Encapsulation
- It defines that none of the members can be declared outside the class and
should not be accessible out side the class without permission
- All members are private by default

class <classname>
{
//members
}

Abstraction
- Defines the accessibility level of the members and the assembly
components (class, interface, structure etc.)
- C# provides five level of accessibility
i. private
1. Within the class
ii. internal
1. Within the assembly
iii. protected
1. Used for inheritance only in same or different assembly
iv. public
1. Anywhere access
v. protected internal
1. Can be access within the assembly and can be inherited in
other assembly

Example
- Create a new project as Console Application
- Add a new project in same solution from Project  Add  New
Project…
- To see both the projects open Solution Explorer from View menu
- Create a class in first project and give reference in second project and
check the accessibility levels

Polymorphism

- Polymorphism is a concept by which an item can perform more than one


task
- It is implemented using overloading
- C# allows two kind of overloading
i. Method Overloading
ii. Operator Overloading
Method Overloading
- Multiple methods with same name with but different number of arguments
or the type of arguments

void area(double r)
void area(int len, int width)

Operator Overloading
- When an operator performs more than one operations, is called as operator
overloading
- An operator can be overloaded using operator keyword
- It is made of anonymous method

08
Inheritance

- Provides re-usability of code


- Classes are defined in three layers
i. Current Class
ii. Base Class
iii. Parent Classes
- Use this keyword for current class object and base keyword for object of
base class
- Use : operator to inherit a class or interface into another class

Method Hiding
- When a method in parent class used with same signature in child class
with different body contents is called as method hiding
- Use new keyword to explicitly define the hiding

Example
new public int greatest() //method hiding
{
return base.greatest()>c?base.greatest():c;
}

Method Overriding
- When a method in parent class, rewritten in child class with same
signature and different body contents
- To allow the overriding the method must be abstract or virtual
- While overriding a method use override keyword if the method is virtual
in parent class
- Overridden method can be access though the reference of parent class or
interface. It gives the concept of Dynamic Polymorphism or Dynamic
Method Dispatch (DMD)
Example
class A
{
virtual public double Volume(double r)
{
return 3.14*r*r;
}
}
class B : A
{
override public double Volume(double r)
{
return System.Math.PI*r*r;
}
}

class ERP
{
public void Calc(A x)
{
System.Console.WriteLine(x.Volume(5));
}
}

class Test
{
public static void Main()
{
ERP x=new ERP();
x.Calc(new A());
x.Calc(new B());
}
}

Interface
- A user defined data type similar to class which contains all abstract
methods
- All methods are public and abstract by default
- Use I prefix with interface names for identification

Sample Case
Create classes and interfaces for students (current,alumni) and faculty (permanent and
visiting) to manage their personal and professional information. Also create the
constructors and methods to input data and some processing on data like fee deposit, pay
salary, print salary sheet etc.

14.02.2009

Exception Handling
- A system to trap the runtime error from the place the error has occurred to
the place the method get called
- Each exception is a class inherited from Exception class of System
namespace
- Every exception kind of class returns a message for the kind of error using
i. string Message property
ii. string ToString() method
- C# defines four keywords for exception handling
i. try
ii. catch
iii. throw
iv. finally
- try-catch is block of statements to do some activity and trap the exception

try
{
//statements
}catch(classname ref)
{
//messaging
}

- finally is again a block provided with try in the last to execute some code
irrespective of exception

Creating Custom Exceptions


- Create your class for exception messaging and inherit it from Exception
class
- Override ToString() method and Message property

Example
class LowBalanceException : Exception
{
public override string Message
{
get
{
return "Sorry! Low Balance in your account. Check it";
}
}
public override string ToString()
{
return "LowBalanceException: Sorry! Low Balance Found.
Check it";
}
}

Using the Exception


class Customer
{
string name;
int balance;
public Customer(string name, int opamount)
{
this.name = name;
balance = opamount;
}
public void Deposit(int amount)
{
balance += amount;
}
public void Withdraw(int amount)
{
if (amount > balance)
throw new LowBalanceException();

balance -= amount;
}
public int Balance
{
get
{
return balance;
}
}
}

Catching the Exception


class HDFCBank
{
static void Main(string[] args)
{
Customer c = new Customer("Ravi Verma", 5000);
c.Deposit(3000);
Console.WriteLine("Current Balance is : {0}", c.Balance);
try
{
c.Withdraw(40000);
}
catch (LowBalanceException ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Current Balance is : {0}", c.Balance);

}
}

Assignment

Create a class having a number and a method called Factorial(). Create another class as
exception class named as NoNumberException.
If no data is provided for Factorial then it must throw an exception called as
NoNumberException

String Handling
- .NET provides two classes for string handling
i. System.String (string)
ii. System.Text.StringBuilder
- String class is immutable (fixed size) where any + operation wastes the
one memory for Garbage Collection
- StringBuilder class is mutable where we can concatenate the string at
same place

StringBuilder sb=new StringBuilder();


sb.Append(“Amit”);
sb.Append(“Kumar”);
string s=sb.ToString();

String Methods
o string ToUpper()
o string ToLower()
o bool StartsWith(string s)
o bool EndsWith(string s)
o Trim()
o Length
o Format() – to format a string with place holders
15.02.2009

Visual C#
- Programming for Windows in GUI Mode
- Create a new project as Windows Application
- Every windows Application must have at least one Window Form
- A window form is a special class inherited from Form class of
System.Windows.Forms namespace
- A form works as container for windows applications
- It can be used to place different component to develop a windows
application
- Every component and container provided some fixed set of
i. Properties
ii. Methods
iii. Events
- Properties deal with value. Can be of two types
i. Design Time Properties
1. Provides in Properties Window (F4)
ii. Runtime Windows
1. Provided using coding in Code Window
2. Use a control and its event to define the code in code
window
a. Controlname.propertyname=value;
- An event is the moment generated using keyboard, mouse or system
activity
i. Click
ii. DoubleClick
iii. MouseOver
iv. MouseOut
Etc.

Common properties on All controls


1. Name
2. BackColor
3. ForeColor
4. Visible
5. Enabled
6. Font
etc.

Naming the controls


- Use Hungarian notation given by Charles Simony of Hungary
- It states that every control must have
i. A unique name
ii. It should proceed three character prefix to define the type of
control
1. TextBox  txt
2. CommandButton  cmd
3. ComboBox  cbo
Adding a new form
- Windows  Add Windows Form…

Setting a form as startup form


- Select Program.cs file from Windows  Solution Explorer
- Specify the class to start in Application.Run()
Example
Application.Run(new Form2());

Calling the same method of multiple controls


- Select one control and its event to invoke a method
- Type some method name to be created

20.02.2009

Form control
- Works like a container for Windows Applications
- Must have at least one window form
i. Text
ii. StartPosition
iii. MinimumBox
iv. MaximumBox
v. WindowState
vi. Icon
vii. BackgroundImage
viii. BackgroundImageLayout
ix. FormBorderLayout

Label control
- To provide fixed text
i. Text
ii. Image
iii. TextAlign
iv. ImageAlign
v. AutoSize
vi. TabIndex
- Use & to make the hot key

TextBox control
- To create single line or multiline text and password field
i. Text
ii. PasswordChar
iii. MaxLength
iv. Multiline
v. ScrollBars
vi. WordWrap
vii. Doc
viii. Cut()
ix. Copy()
x. Paste()
xi. Focus()
xii. Append()
-
Button class
- to create the push buttons
i. Text
ii. Image
iii. TextAlign
iv. ImageAlign

PictureBox control
- To show an image
i. Image
ii. SizeMode
iii. BorderStyle
- To load an image dynamically use Image class with FromFile() method

Note: Use … (ellipses) to indicate that some dialog will appear on a button or Menu Item
when clicked

Working with Dialogs

- Dialogs can be normal message or query dialogs or some kind of input


dialogs
- MessageBox.Show() method gives normal and query dialogs
- Dialog section of toolbox provides standard controls for dialogs
i. OpenFileDialog
ii. SaveFileDialog
iii. FontDialog
iv. ColorDialog
v. FolderBrowerDialogs

MessageBox.Show() method for General Mesages


- MessageBox.Show(“message”);
- MessageBox.Show(“message”,”caption”);
- MessageBox.Show(“message”,”caption”,MessageBoxButtons b,
MessageBoxIcon ic);

MessageBox.Show() for Response Input

DialogResult MessageBox.Show(“message”,”caption”,MessageBoxButtons b,
MessageBoxIcon ic);

Working with Enumerators


- A enumerator is a set of named values
- Use enum keyword to define the enumerators
- Default value starts with 0 and incremented by 1
- By default is of int type but can given the type

Using Built-in Dialogs


- Each dialog control provides
i. ShowDialog() method

OpenFileDialog control
- Allows to select a file
i. FileName
ii. Filter
Example
openFileDialog1.Filter = "All Files|*.*|Image Files|*.jpg;*.gif;*.png";
openFileDialog1.ShowDialog();
this.Text = openFileDialog1.FileName;
pictureBox1.Image = Image.FromFile(openFileDialog1.FileName);

ColorDialog control
- To get a color
i. Color
ii. FullOpen

Example
colorDialog1.FullOpen = true;
colorDialog1.ShowDialog();
textBox3.ForeColor = colorDialog1.Color;

FontDialog control
- to get a font with name,size and style
i. Font
ii. Color
iii. ShowColor=true/false

22.02.2009

Checkbox control
- To select none or all
i. Text
ii. Image
iii. TextAlign
iv. ImageAlign
v. Checked

Example
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
button1.Enabled = true;
else
button1.Enabled = false;
}

RadioButton control
- To select only one out of all
i. Text
ii. Image
iii. TextAlign
iv. ImageAlign
v. Checked
- Use GroupBox or Panel control to make the groups

ComboBox control
- To select only one item from list of items
- It provides Items collection
- Use it to Add and remove the items
i. SelectedItem
ii. SelectedIndex
iii. DropDownStyle//event handler
Example
private void Form4_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("-Select-");
for (int i = 100; i <= 200; i++)
comboBox1.Items.Add(i);
comboBox1.SelectedIndex = 0;
}

private void button2_Click(object sender, EventArgs e)


{
if(comboBox1.SelectedIndex!=0)
MessageBox.Show(comboBox1.SelectedItem.ToString());
}

ListBox class
- Allows to select one or more items
- It also provided Items collection
i. SelectedItem
ii. SelectedIndex
iii. SelectionMode
iv. bool GetSelected(int index)

Example
private void Form4_Load(object sender, EventArgs e)
{

for (int n = 900; n <= 1000; n += 10)


listBox1.Items.Add(n);
}

private void button3_Click(object sender, EventArgs e)


{
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (listBox1.GetSelected(i))
listBox2.Items.Add(listBox1.Items[i]);
}
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if (listBox1.GetSelected(i))
listBox1.Items.RemoveAt(i);
}
}

DateTimePicker control
- Allows to select date, time or both
i. Format
ii. CustomFormat
iii. ShowUpDown
iv. ShowCheckBox
v. Checked
vi. Value
- Working with Collections
- A collection is a set of classes provided inside
System.Collections namespace that can manage dynamic set of
data
i. List
ii. ArrayList
iii. LinkedList
- Each collection type class provides
i. Add(object x)
ii. Remove(object x)
iii. RemoveAt(int index)
iv. Count

Note: While passing the values to the collections, they get converted
to objects, called as boxing. While reading back the values from object
cast them to values types, called as unboxing.
- Value to object conversion is called as boxing
object x=56;
- Reference to value conversion though casting is calling as
unboxing
int num=(int) x;

Example
ArrayList ar = new ArrayList();
ar.Add(56);//boxing
ar.Add(33);
ar.Add(77);

int sum = 0;
for (int i = 0; i < ar.Count; i++)
sum = sum + (int)ar[i]; //unboxing
Console.WriteLine("Sum is " + sum);

Generics

- Special kind of collections provided under System.Collections.Generic


namespace
- They allows to define the type of elements inside a class while creating
object of the class
- They are best used to avoid boxing and unboxing
Example
class GenericTest
{
public static void Main()
{
List<int> ar = new List<int>();
ar.Add(34);
ar.Add(35);
ar.Add(90);
int sum = 0;
for (int i = 0; i < ar.Count; i++)
sum = sum + ar[i];
Console.WriteLine(sum);
}
}
23.02.2009

Creating Menus
- Menus can be of two types
i. Dropdown Menu
ii. Context Menu
- Two controls are used
i. MenuStrip
ii. ContextMenuStrip
- We can define the hot key with &
- Shortcut key, Image and ToolTip

RichTextBox control
- Provides additional properties on text box
i. SelectionFont
ii. SelectionColor
iii. LoadFile
iv. SaveFile

Creating StatusBar control


- Use StatusStrip control to create the statusbar
- It provides Items collection
- We can define the size of each section with AutoSize as False

Timer Control
- To execute some activity after every given interval of time
- Provided under Components section
i. Interval – time in milliseconds
ii. Enabled

ToolBar control
- To create the toolbars
- Use ToolStrip control

Progressbar control
- Minimum
- Maximum
- Value

Creating MDI (Multiple Document Interfaces) Applications


- Such applications have a main form or parent and other child forms
- To make a form as parent form set its IsMdiContainer property as true
- To make a form as child form set its MdiParent property
- To arrange the child forms inside the container use LayoutMdi() method
with MdiLayout enumerator
- To get the current form in main form use
i. ActiveMdiChild property
- To get reference of a control from that child form use Controls collection
28.02.2009

ADO.NET (ActiveX Data Object for .NET)

- A technology under .NET class library and provides classes for database
operations
- Namespaces used
i. System.Data – common classes for all databases
ii. System.Data.Odbc – Using DSN for any database
iii. System.Data.OleDb – Using Provider for specific database
iv. System.Data.Oracle – Only for Oracle
v. System.Data.SqlClient – Only for MS Sql Server
- These namespaces are provided in two assemblies
i. System.Data.dll
ii. System.Data.OracleClient.dll

Categories of classes used


1. xxxConnection
a. To setup the connection
2. xxxCommand
a. To execute the SQL statements
3. xxxDataReader
a. To hold reference of records returned by SELECT
statement
4. xxxDataAdapter
a. To get data from database and store in some client
side container DataTable or DataSet

Using MS Access with ODBC


- Create a database and tables
- Create a Data Source Name (DSN) from control panel as system dsn

Example
batch02access
Creating a Connection
- Create an object of Connection type class
i. OdbcConnection cn=new OdbcConnection();
- Provide the ConnectionString property with following information
i. DSN=<dsnname>
ii. User Id or uid=<login name>
iii. Password or pwd=<password>
iv. Example
1. cn.ConnectionString=”dsn=batch02access”;
- Open the connection
i. cn.Open();

Creating the SQL Statement


- string sql=”INSERT INTO ….”;

Create the command type object and provide the connection and commandtext
OdbcCommand cmd=new OdbcCommand();
cmd.Connection=cn;
cmd.CommandText=sql;

Execute the methods of command type class depending on type of SQL statement
- void ExecuteNonQuery()
i. For all command except SELECT
- object ExecuteScaler()
- OdbcDataReader ExecuteReader()

Close the connection


cn.Close();

Using OLEDB Technology

- Create the connection string with Provider from


i. Data  Add New Data Source…
- To create the dynamic path for file based databases use
i. Application.StartupPath property to get the folder name of EXE
file
Using Oracle as Database

- ConnectionString fields
i. Data Source=<servername>
ii. User Id or uid=<login>
iii. Password or pwd=<password>

Using SQL Server as Database


- Create the database e.g. batch02
- Create the Login and Password and the database with the current user as
db_owner for Mapping Tab
- ConnectionString fields
i. Data Source=<servername>
ii. User Id or uid=<login>
iii. Password or pwd=<password>
iv. Database=<databasename>
01.03.2009

Placing the connection related information in Application Configuration File (app.config)


- Add a file from
i. Project  Add New Item…  Application Configuration File
- It is an XML file having some customized tags

Example
<configuration>
<appSettings>
<add key="cs_sql" value="Data
Source=.;uid=b02;pwd=pass;database=batch02"/>
</appSettings>
</configuration>

Accessing the information from app.config file


- Import the namespace
i. using System.Configuration;
- Fetch it using ConfigurationSettings class
i. cn.ConnectionString =
ConfigurationSettings.AppSettings["cs_sql"];

Creating formatted SQL strings with Format() method of String


class
string sql = string.Format("INSERT INTO employee
VALUES({0},'{1}','{2}')", txtEmpId.Text, txtName.Text, txtEmail.Text);

Using Parameters in SQL statements


- Do not provide real data while create the SQL statements but create the
parameters
i. For Access use ?
ii. For SQL Server use @paramname
iii. For Oracle use :paramname
- Use Parameters collection of Command type objects to pass the
parameters

Example 1 – SQL Server


string sql = "INSERT INTO employee VALUES(@eid,@name,@email)";
sqlCommand cmd = new SqlCommand(sql,cn);
cmd.Parameters.AddWithValue("@eid", txtEmpId.Text);
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@email", txtEmail.Text);
cmd.ExecuteNonQuery();

Example 2 – MS Access
string sql = "INSERT INTO employee VALUES(?,?,?)";
OleDbCommand cmd = new OleDbCommand(sql,cn);
cmd.Parameters.AddWithValue("empid", txtEmpId.Text);
cmd.Parameters.AddWithValue("name", txtName.Text);
cmd.Parameters.AddWithValue("email", txtEmail.Text);
cmd.ExecuteNonQuery();
Saving Images to Database
- To image to database use datatype
i. Sql Server  Image
ii. MS Access  OLE Object
iii. Oracle  BLOB
- First we must an image to be saved
- To save to on disc it must be byte type array
- Use MemoryStream class of System.IO namespace for interface

Example
string sql = "INSERT INTO imagetest VALUES(@name,@photo)";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.Parameters.AddWithValue("@name", txtName.Text);

MemoryStream ms = new MemoryStream();


pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] b = ms.GetBuffer();

SqlParameter p = new SqlParameter("@photo",


SqlDbType.Image);
p.Value = b;

cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();

Creating Stored Procedures


- Select the database
- Select Programmability
- Select Stored Procedure
- Create the procedure and Execute it (F5)

CREATE PROCEDURE SaveData


@name varchar(50),
@photo image
AS
BEGIN
INSERT INTO imagetest VALUES(@name,@photo);
END
GO

Use the procedure from the program


SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SaveData";
cmd.Parameters.AddWithValue("@name", txtName.Text);

MemoryStream ms = new MemoryStream();


pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] b = ms.GetBuffer();

SqlParameter p = new SqlParameter("@photo",


SqlDbType.Image);
p.Value = b;

cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();
Working with connection as One way entry, one way exit
- Open the connection on Load and close the connection on FormClosing

Reading Data from Database


- Select commands can return
i. Records
ii. Single value
- .NET provides two kind of data reading methods
i. Connected Mode
ii. Disconnected Mode
- In connected mode we can read only one record at a time. Once the
connection is closed data cannot be read. It is forward only.
- In disconnected model data can be stored on client side in some container
called DataTable or DataSet. Data is available even after closing the
connection on client side.
- Connected Mode
i. Use xxxDataReader and xxxCommand
- Disconnected Mode
i. Use xxxDataAdapter, DataSet or DataTable

Using xxxDataReader classes


- Provides
i. bool HasRows property which return true if records found
ii. bool Read() method to move the pointer to next record till end of
record reached

Vous aimerez peut-être aussi