[go: up one dir, main page]

0% found this document useful (0 votes)
112 views200 pages

Reading Content From The File: Application 61: File Writing Demo

The document discusses multi-threading in .NET applications. It defines multi-threading as an application that maintains multiple threads running concurrently. It describes how .NET uses the System.Threading namespace to implement multi-threading by creating Thread objects that execute code independently and simultaneously. The document also outlines the different states a thread can be in during its lifecycle, including ready, running, sleeping, suspended, and dead. It provides examples of methods that can change a thread's state, such as Start(), Sleep(), Suspend(), and Resume().

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views200 pages

Reading Content From The File: Application 61: File Writing Demo

The document discusses multi-threading in .NET applications. It defines multi-threading as an application that maintains multiple threads running concurrently. It describes how .NET uses the System.Threading namespace to implement multi-threading by creating Thread objects that execute code independently and simultaneously. The document also outlines the different states a thread can be in during its lifecycle, including ready, running, sleeping, suspended, and dead. It provides examples of methods that can change a thread's state, such as Start(), Sleep(), Suspend(), and Resume().

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 200

Reading content from the file

 Import the API


using System.IO;
 Create the stream reader object
StreamReader sr = new StreamReader(―file name‖);
 Reade the content
sr.ReadToEnd();
 Close the Reader
sr.Close();

Application 61: File Writing Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileWriteDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);

if (!fobj.Exists)
{
string content;
Console.WriteLine("\nEnter content to write:");
content = Console.ReadLine();

StreamWriter sw = new StreamWriter(filepath);


sw.Write(content);
sw.Close();

Console.WriteLine("\nWritten successfully!");
}
else
Console.WriteLine("File already exists.");

.NET 4.0 and Visual Studio 2010 Page 194 of 548


Console.Read();
}
}
}

Output:

Application 62: File Reading Demo

using System;
using System.IO;

namespace FileReadDemo
{
class Program
{
static void Main(string[] args)
{
string filepath;
Console.WriteLine("Enter the file path:");
filepath = Console.ReadLine();
FileInfo fobj = new FileInfo(filepath);

if (fobj.Exists)
{
StreamReader sr = new StreamReader(filepath);
string content = sr.ReadToEnd();
Console.WriteLine(content);

sr.Close();
}
else
Console.WriteLine("File not found.");

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 195 of 548


Output:

.NET 4.0 and Visual Studio 2010 Page 196 of 548


Multi Threading
 ―Multi Threading‖ is one of the rich features of .NET applications.
 Using this feature, the user is able to create multi-threaded applications.
 This concept is introduced in VC++. This is also supported by Java.
 Definition of Multi Threading: The ability of an application that maintains multiple
threads at run time.
 Definition of Thread: The thread is a sub process (part of the process). That means it
has some code to execute.
 Advantage of Multi-Threading: Using ―multi threading‖, you can break a complex
task in a single application into multiple threads that execute independently and
simultaneously.
 In other words, ―multi threading‖ is the sub form of ―multi tasking‖.
 Before starting with the implementatin of Multi Threading, you should recollect the
concept of ―Multi-Tasking‖.

Multi Tasking:
 Def: Ability of the OS, that is able to perform more than one task, at-a-time
(simultaneously) is called as ―Multi-Tasking‖.
 As a part of this, OS allocates the CPU clock (CPU capacity) for each task.
Note: Just like multi-tasking, OS allocates the CPU clock for each thread.

Threading Architecture:

.NET Application

OS
Thread 1
CLR
Thread 2

Thread 3
Processor

.NET 4.0 and Visual Studio 2010 Page 197 of 548


Implementation of Multi Threading:
.NET Framework offers a namespace called “System.Threading” for implementation of
multi threading.
Library: System.Threading.Thread
This class object represents a thread.

 Import the API:


using System.Threading;
 Create the Thread Object:
Thread th = new Thread(method_name);
 Start the Thread:
th.Start();

Application 63: Simple Demo on Multi Threading

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SimpleThreadingDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 300; i++)
Console.Write("i=" + i + " ");
}
private void SecondMethod()
{
for (int j = 1; j <= 300; j++)
Console.Write("j=" + j + " ");
}
public void Display()
{
Thread th1 = new Thread(FirstMethod);
Thread th2 = new Thread(SecondMethod);

th1.Start();
th2.Start();

.NET 4.0 and Visual Studio 2010 Page 198 of 548


}
}
class Program
{
static void Main(string[] args)
{
ThreadingDemo td = new ThreadingDemo();
td.Display();
Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 199 of 548


Thread States

The thread state specifies the current status of the thread. Sometimes, the thread
automatically switches from one state to another state automatically; at some other times, you
can switch its state by using the methods offered by ―Thread‖ class.

The following diagram called ―Thread Life Cycle‖ describes the different states of a
thread.

Thread Life Cycle

Ready

Start()

Running

Automatic Automatic / Sleep()

Sleeping

Suspend()

Resume()
Suspended
Automatic / Abort()
Dead

1. Ready: This is the initial state. The thread object is created.


2. Running: The thread is currently being executed.
3. Sleeping: The thread is temporarily paused. .NET framework offers automatic switching
between ―Running‖ and ―Sleeping‖ states, when other threads are executed.

.NET 4.0 and Visual Studio 2010 Page 200 of 548


4. Suspended: The thread is temporarily suspended (paused). It will be continued, when
you call ―Resume()‖ method.
5. Dead: The thread was closed; it can‘t be restarted or continued.

“Thread”classmethods:

o thobj.Start()
This method starts-up the thread execution.

o Thread.Sleep(mille_sec)
This method puts the thread under ―Sleeping‖ state, up to a certain no. of mille
seconds. When the given no. of mille seconds are completed, automatically the
thread execution will be continued.

o thobj.Suspend()
This is similar to ―Sleep()‖ method, but here, no time limit will be given. That
means whenever the ―Suspend()‖ method is called, the thread will be put under
―Suspended‖ state, until the ―Resume()‖ method is called.

o thobj.Resume()
This is to continue the thread execution that is under ―Suspended‖ state. This
method won‘t work if the thread is not under ―Suspended‖ state.

o thobj.Abort()
This is close the thread execution completely, at any time. Once, if the ―Abort()‖
method is called, the thread can‘t be started or resumed. This is the end of every
thread life cycle.

Application 64: Demo on Thread States

.NET 4.0 and Visual Studio 2010 Page 201 of 548


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadLifeCycleDemo
{
class ThreadingDemo
{
private void FirstMethod()
{
for (int i = 1; i <= 50; i++)
{
Console.Write("i=" + i + " ");
Thread.Sleep(1000);
}
}
private void SecondMethod()
{
for (int j = 1; j <= 50; j++)
{
Console.Write("j=" + j + " ");
Thread.Sleep(1000);
if (j == 20)
th1.Suspend();
else if (j == 30)
th1.Resume();
}
}

Thread th1, th2;

public void Display()


{
th1 = new Thread(FirstMethod);
th2 = new Thread(SecondMethod);
th1.Start();
th2.Start();
}
}
class Program
{
static void Main(string[] args)
{
ThreadingDemo td = new ThreadingDemo();
td.Display();
Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 202 of 548


Output:

Anonymous Methods
 This is used to create a method, without any name.
 Syntax:
delegate()
{
//some code
}

Application 65: Demo on Anonymous Methods

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AnonymousMethodsDemo
{
class ThreadingDemo
{
public void Display(string name)
{
Thread th1 = new Thread(delegate()
{
while (true)
{
Console.WriteLine("Welcome to " + name);
Thread.Sleep(500);
}
});
th1.Start();
}
}

.NET 4.0 and Visual Studio 2010 Page 203 of 548


class Program
{
static void Main(string[] args)
{
string name;
Console.WriteLine("Enter your name:");
name = Console.ReadLine();

ThreadingDemo td = new ThreadingDemo();


td.Display(name);

Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 204 of 548


Speech Translation
 This is to translate the text as speech.
 This makes us to listen a voice from the speakers that reads some specified text.
 Library: System.Speech.Synthesis.SpeechSynthesizer
 This class used to speak the required text through the speakers.

Implementation:
 Create the object of ―SpeechSynthesizer‖ class:
SpeechSynthesizer ss = new SpeechSynthesizer();
 Set the volume (1 to 100):
ss.Volume = n;
 Set the speed of speaking (-10 to +10):
ss.Rate = n;
 Change the voice gender and age:
ss.SelectVoiceByHints(VoiceGender.xxxx, VoiceAge.xxxx);
 Speak the text:
ss.SpeakAsync(―message‖);

Application 66: Demo on Speech Translation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Speech.Synthesis;

namespace SpeechTranslationDemo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter text to speak:");
string TextToSpeak = Console.ReadLine();

SpeechSynthesizer ss = new SpeechSynthesizer();

ss.Volume = 100; //1 to 100

.NET 4.0 and Visual Studio 2010 Page 205 of 548


ss.Rate = -3; // -10 to +10

ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Child);

ss.SpeakAsync(TextToSpeak);

Console.Read();
}
}
}

Output:

Memory Management
 Every application requires some amount of memory to run.
 That memory will be allocated in the primary memory (RAM).
 For every variable, individual memory will be allocated.
 The RAM contains two memory locations.
o Stack RAM
o Heap
 Now, we need to understand, where the
application memory is getting allocated in the Stack
RAM.
 The storage area in the RAM depends on the
―data type‖ that you are using for declaring the
Heap
variable in the program.
 The data types are two types in C#
o Value Types
o Reference Types

.NET 4.0 and Visual Studio 2010 Page 206 of 548


1) Value Types:
 Def: Whenever a data type is designed based on a structure, it can be called as
―Value Type‖.
 All the standard data types built based on structures.
 You can see the list of data types and respective structures here:

Data Type Structure Name


sbyte System.SByte
byte System.Byte
short System.Int16
ushort System.UInt16
int System.Int32
uint System.UInt32
long System.Int64
ulong System.UInt64
float System.Single
double System.Double
decimal System.Decimal
bool System.Boolean
char System.Char

 So finally, the following are value types in C#:


1) Structures
2) Enumerations
3) sbyte, byte, short, ushort, int, uint, long, ulong, float, double, decimal, bool,
char, decimal, DateTime

 Note 1: The value types can‘t be inherited.


 Note 2: All the value types (structures and enumerations), are derived from a
common base class called ―System.ValueType‖.

2) Reference Types:
 Def: Whenever a data type is designed based on a class, it can be called as
―Reference Type‖.
 The following are the reference types in C#:
1) Classes
2) Interfaces
3) String, Object
 Reference types support inheritance.

.NET 4.0 and Visual Studio 2010 Page 207 of 548


 The ―Value Type‖ variables will be allocated in the ―Stack‖.
 The ―Reference Type‖ variables (objects) will be allocated in the ―Heap‖.

The “System.Object” class:


 This class acts as super class for all other classes (pre-defined / user-defined
classes).
 So, it can be called as ―Ultimate base class‖.

Object

ValueType

Structures Enumerations Classes

 The ―Object‖ class offers the following methods.


Method Description
Equals(value) Checks the equality of the value of the object with the given
argument value. If both are equal, then returns ―true‖, otherwise
returns ―false‖.
Ex:
MyObj.Equals(AnotherObject);
In this example, ―MyObj‖ will be compared with ―AnotherObject‖.
GetType() Gets the name of the class, for which, it is declared.
Ex:
MyObj.GetType();
ToString() Converts the value of the object and returns it.
Ex:
MyObj.ToString();
In this example, the value of ―MyObj‖ will be converted as string
type, and that string value will be returned.

.NET 4.0 and Visual Studio 2010 Page 208 of 548


Application 67: Demo on System.Object class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ObjectClassMethods
{
class Program
{
static void Main(string[] args)
{
int x = 100;
int y = 100;

Console.WriteLine("x is " + x);


Console.WriteLine("y is " + y);

Console.WriteLine();

if (x.Equals(y))
Console.WriteLine("x is equal to y");
else
Console.WriteLine("x is not equal to y");

Console.WriteLine("\nx is the type of " + x.GetType());

string s = x.ToString();
Console.WriteLine("\nThe integer value after converting into string is: " + s);

Console.Read();
}
}
}

Output:

.NET 4.0 and Visual Studio 2010 Page 209 of 548


Garbage Collector:
 This is one of the components of CLR (Common Language Runtime).
 This component is dedicated for de-allocating the un-used memory of the
application, automatically.
 This uses ―Mark and Compact‖ algorithm for clearing the un-used memory.
 Mark: Markup the un-used objects and push those objects towards up.
 Compact: Clear the marked objects memory.

Object 1

Object 2

Object 3

Object 4

The Memory Heap

Note: The above functionality is in-built in ―Garbage collector‖ component. Anyhow, there is a
provision for the programmer to command the garbage collector to perform ―garbage collection‖
at run time, programmatically. Then use the following method from ―System.GC‖ class.
Syn: System.GC.Collect();

.NET 4.0 and Visual Studio 2010 Page 210 of 548


LINQ
 LINQ (pronounced link) stands for ―Language Integrated Query‖.
 This concept is introduced in .NET Framework 3.5.
 This is a ―query writing technology‖.
 This is most useful while working large amount of data in the live projects.

Introduction:

 In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
 But you can‘t write a query on the non-database data, which in the form of objects in the
application. There, you can write the queries using the new concept called ―LINQ‖.
 You can write queries on arrays, objects, databases and XML using LINQ.
 Note: Before writing the LINQ queries, you should import the ―System.Linq‖
namespace..

The following example shows a small demo on LINQ:

Application 68: LINQ to Arrays

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoArrayDemo
{
class Program
{
static void Main(string[] args)
{
//data source
int[] numbers = { 2, 12, 10, 5, 15, 4, 62 };

//ling query
IEnumerable<int> result = from n in numbers where n <= 10 select n;

.NET 4.0 and Visual Studio 2010 Page 211 of 548


//output
foreach (var x in result)
Console.WriteLine(x);

Console.Read();
}
}
}

Output:

In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can execute the queries on
data sets (after learning ADO.NET) also.

LINQ Syntax:

from… in… let … where … orderby … select… group by …

 The above syntax consists of 7 clauses.


 from clause
 in clause
 let clause
 where clause
 orderby clause
 select clause
 group by clause

 Mandatory clauses:
 from clause
 in clause
 select clause

Def of Clause: A part of the query.

.NET 4.0 and Visual Studio 2010 Page 212 of 548


Understanding Clauses:

1. from clause: This is used to specify the iteration variable name. This acts as alias name
for the data source.
2. in clause: This is used to specify the main data source for the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required.
6. select clause: This is used to specify the object, which is required in the query results.
7. group by (optional): This is similar to ―group by‖ clause in SQL. This retrieves grouped
data, based on a column.

Note: The result of a LINQ query should be assigned into a IEnumerable<data type> type
variable. IEnumerable is an interface.

Library: System.Collections.Generic.IEnumerable

Application 69: LINQ to Objects

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;

.NET 4.0 and Visual Studio 2010 Page 213 of 548


//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};

//linq query with where clause


IEnumerable<Student> result1 = from s in stu where s.Course == "MCA" select s;
Console.WriteLine("MCA Students:");
foreach (Student r in result1)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);

//linq query with compound where clause


IEnumerable<Student> result2 = from s in stu where s.Name.EndsWith("a") &&
s.Marks>=400 && s.Marks<=600 select s;
Console.WriteLine("\nStudents whose name ends with 'a', and marks is >=400 and
<=600:");
foreach (Student r in result2)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);

.NET 4.0 and Visual Studio 2010 Page 214 of 548


//linq query with let and where clauses
IEnumerable<Student> result3 = from s in stu let avg = s.Marks / 10 where avg < 35
select s;
Console.WriteLine("\nFailed Students:");
foreach (Student r in result3)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause


IEnumerable<Student> result4 = from s in stu orderby s.Marks select s;
Console.WriteLine("\nStudents (sort on marks):");
foreach (Student r in result4)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause (descending)


IEnumerable<Student> result5 = from s in stu orderby s.Marks descending select s;
Console.WriteLine("\nStudents (sort on marks - descending):");
foreach (Student r in result5)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with group clause


IEnumerable<IGrouping<string,Student>> result6 = from s in stu group s by s.Course;
Console.WriteLine("\nStudents with grouping:");
foreach (IGrouping<string, Student> StuGrp in result6)
{
Console.WriteLine(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Console.WriteLine(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);
}

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 215 of 548


Output:

LINQ with Lambda Expressions


 LINQ queries can be written in two syntaxes:
1) General Query Syntax
2) Lambda Expression Syntax
 The previously written applications are written with ―General Query Syntax‖.
 Syntax for Lambda Expression:
DataSource.Clause(DataAliasName => Expression)
 Ex:
stu.Where(s => s.Marks < 300)

goes to

.NET 4.0 and Visual Studio 2010 Page 216 of 548


Application 70: LINQ with Lambda Expressions

Student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQtoObjectsDemo
{
class Student
{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
}

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQwithLambaExpressions
{
class Program
{
static void Main(string[] args)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)};

.NET 4.0 and Visual Studio 2010 Page 217 of 548


//linq query with where clause
IEnumerable<Student> result1 = stu.Where(s => s.Course == "MCA");
Console.WriteLine("MCA Students:");
foreach (Student r in result1)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with compound where clause


IEnumerable<Student> result2 = stu.Where(s => s.Name.EndsWith("a") && s.Marks
>= 400 && s.Marks <= 600);
Console.WriteLine("\nStudents whose name ends with 'a', and marks is >=400 and
<=600:");
foreach (Student r in result2)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause


IEnumerable<Student> result4 = stu.OrderBy(s => s.Marks);
Console.WriteLine("\nStudents (sort on marks):");
foreach (Student r in result4)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with orderby clause (descending)


IEnumerable<Student> result5 = stu.OrderByDescending(s => s.Marks);
Console.WriteLine("\nStudents (sort on marks - descending):");
foreach (Student r in result5)
Console.WriteLine(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks);

//linq query with group clause


IEnumerable<IGrouping<string, Student>> result6 = stu.GroupBy(s => s.Course);
Console.WriteLine("\nStudents with grouping:");
foreach (IGrouping<string, Student> StuGrp in result6)
{
Console.WriteLine(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Console.WriteLine(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks);
}

Console.Read();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 218 of 548


Output:

.NET 4.0 and Visual Studio 2010 Page 219 of 548


Exception Handling
 This is one of the major features of OOP languages like C++, VC++, VB.NET, C#.NET,
Java etc.
 Def: "The process of handling the run time exceptions" is called as "Exception
handling".
Note: Exception = Run time error

Types of Errors:
1) Compile Time Errors: The errors occurred after compiling the program, are called as
―compile time errors‖.
2) Run Time Errors: The errors occurred during the execution of the program, are called
as ―run time errors‖.

Overview of Exception Handling:


 The exception may occur at run time, based on the mistake of the user / programmer /
system problem also.
 When exception is raised, automatically it leads to "abnormal application termination".
 The cause of the exception may be anything; the project developer should take care
about the exceptions.
 As a part of this exception handling, the programmer has to display "particular error
message" to the user.
 Purpose of Exception Handling: To avoid "abnormal application termination", even
though exception occurs.

Types of Application Termination:

 Normal Application Termination: Whenever the program execution controls executes


all the statements in the program and reaches to end of the code, the application will be
terminated automatically. It can be called as ―Normal Application Termination‖.

 Abnormal Application Termination: Whenever an exception occurred at run time,


the application will be terminated automatically. It can be called as ―Abnormal Application
Termination‖.

.NET 4.0 and Visual Studio 2010 Page 220 of 548


If the application was terminated abnormally, if will be most inconvenience for the user. So being
a programmer, you are responsible to avoid that kind of abnormal application termination, even
though exception is occurred at run time.

A small demo on exceptions:

Application 71: Simple Demo on Exceptions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo1
{
class Program
{
static void Main(string[] args)
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
Console.Read();
}
}
}

In the above code, the highlighted line contains an error, because it is trying to access an
array element which is in out of range of the array. So, it leads to abnormal application
termination at run time.

.NET 4.0 and Visual Studio 2010 Page 221 of 548


Then screen looks like this:

To avoid this, we have to implement exception handling for this code.

Syntax of Exception Handling:

try
{
---------------------;
---------------------;
---------------------;
---------------------;
}
catch (Exception ex)
{
--------------------;
--------------------;
}
finally
{
--------------------;
--------------------;
}

.NET 4.0 and Visual Studio 2010 Page 222 of 548


In the above syntax, we can observe to blocks.
1) try block
2) catch block
3) finally block

1) try block:
 The try block contains the actual code, which
is to be executed. try
{
 After every try block, there should catch
---------------------;
block without fail. ---------------------;
 The system tries to execute the code in the ---------------------;
---------------------;
try block. }
 During the execution, if any exception
occurs, then the execution control automatically goes to catch block.
 At the same time, the ―try‖ block throws the exception to the catch block in the
form of an object. That object is called as ―exception object‖.

2) catch block:
 This is also known as ―error handler‖.
 This is followed by the try block.
 The catch block will be executed if any
exception is occurred during the execution catch (Exception ex)
of try block. {
--------------------;
 The catch block contains necessary code --------------------;
which displays an error message to the }
user.
 This receives the exception, thrown by the try block, in the form of an object. In
the following syntax, ―ex‖ is the ―Exception object‖. The ―Exception‖ is the class
for the exception object.
 Library: System.Exception

.NET 4.0 and Visual Studio 2010 Page 223 of 548


3) finally block:
finally
 This block will be executed automatically and
{
compulsorily, after executing ―try block‖ / ―catch --------------------;
block‖. --------------------;
}
 That means even though exception is raised or
not raised, the ―finally‖ block will be executed without fail.
 This is optional block. You can write the exception handling syntax only with
―try‖ and ―catch‖ blocks, without ―finally‖ block.

Application 72: Demo Exception Handling

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo2
{
class Program
{
static void Main(string[] args)
{
try
{
string[] Cities = { "Vijayawada", "New Delhi", "Banglore", "Hyderabad" };
Console.WriteLine(Cities[3]);
Console.WriteLine(Cities[4]);
}
catch (Exception ex)
{
Console.WriteLine("Error occurred.");
}
finally
{
Console.WriteLine("This is 'finally' block.");
Console.Read();
}
}
}
}

.NET 4.0 and Visual Studio 2010 Page 224 of 548


Output:

Types of Catch Block Messages:

Already we have discussed that the catch block generates an error message, when an exception
occurs. That error message can be of two types.
1. User Defined Message
2. System Defined Message

1. User Defined Message: Your own message can be written.


Ex: ―Error Occurred.‖
―Operation is not successful‖.
etc.
2. System Defined Message: The system provides the description of the error, so that
you can print that on the output directly. To access the system defined message, you can
use the exception object as follows:
Syn: ex.Message
Example:

catch (Exception ex)


{
Console.WriteLine(ex.Message);
}

.NET 4.0 and Visual Studio 2010 Page 225 of 548


Exceptional Classes

 Already you know that C# recognizes the exception as an object.


 To declare the exception object, we have used a class called ―System.Exception‖, in
the previous examples.
 The ―Exception‖ class recognizes any type of exceptions. In order to catch the particular
type of error, C# provides other exceptional classes. Some of them are given here.

Sl. No Exceptional Class Description


Occurs when a large value is

1 System.OverflowException assigned to a variable, which is not


fit in that variable.
Occurs when the casting is failed
System.FormatException /
2 from one data type of another data
System.InvalidCastException
type.
Occurs when any number is divided
3 System.DivideByZeroException
by 0.
Occurs when an index is accessed in
4 System.IndexOutOfRangeException
out of range.
Occurs when there is no sufficient

5 System.InsufficientMemoryException memory in RAM for the execution of


the application.
Occurs when a non-existing file is
6 System.IO.FileNotFoundException
accessed.
Occurs when a non-existing directory
7 System.IO.DirectoryNotFoundException
is accessed.
Occurs when any error occurred
8 System.IO.FileLoadException
during the opening of any file.
Occurs when any error occurred
9 System.IO.IOException
during file read or writing.
Occurs when any error occurred
10 System.Threading.ThreadInterruptedException
during the execution of the thread.

.NET 4.0 and Visual Studio 2010 Page 226 of 548


Occurs when any error occurred
11 System.Threading.ThreadStartException
while starting the thread.
Occurs when any error occurred

12 System.InvalidOperationException while opening the database


connection.
Occurs when any error occurred

13 System.Data.OleDb.OleDbException while performing query or non-query


transactions on OleDb databases.
Occurs when any error occurred

14 System.Data.SqlClient.SqlException while performing query or non-query


transactions on SqlServer database.
Occurs when you try to run the

15 System.EntryPointNotFoundException application, without defining any


entry point (main() method).
Occurs when the system has an

16 System.InvalidTimeZoneException invalid time zone setting the date &


time settings.

Note: Based on the situation, the above specified exception classes could be used.

Application 73: Demo on Exceptional Classes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo3
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;

Console.WriteLine("Enter first value:");


n1 = Convert.ToInt32(Console.ReadLine());

.NET 4.0 and Visual Studio 2010 Page 227 of 548


Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());

n3 = n1 / n2;

Console.WriteLine("Result is: " + n3);


}
catch (DivideByZeroException ex)
{
Console.WriteLine("Can't divide the number with zero.");
}
Console.Read();
}
}
}

Output:

Note: If you want to handle more than one type of exception for the same try block, then you
need to write multiple catch blocks.

Application 74: Demo on Multiple Catch Blocks

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionDemo4
{
class Program
{
static void Main(string[] args)
{
try
{
int n1, n2, n3;

Console.WriteLine("Enter first value:");


n1 = Convert.ToInt32(Console.ReadLine());

.NET 4.0 and Visual Studio 2010 Page 228 of 548


Console.WriteLine("Enter second value:");
n2 = Convert.ToInt32(Console.ReadLine());

n3 = n1 / n2;
Console.WriteLine("Result is: " + n3);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("This is divide by zero exception.");
}
catch (OverflowException ex)
{
Console.WriteLine("This is overflow excpetion.");
}
catch (FormatException ex)
{
Console.WriteLine("This is invalid cast exception.");
}
Console.Read();
}
}
}

Output:

The“EventLog”

 ―EventLog‖ is a service, offered by Microsoft Windows.


 It is used to store the exceptions / warnings / any messages permanently, even though
the application is closed.
 Let us imagine you have done a live project and issue it to the client.
 At run time there may be so many exceptions. But after few days, you went to the client
location, and want to know what kind of run time errors were coming in your application.
 Then no information is available with you.
 So, in this case, you require some thing, that stores the exceptions information
automatically, for further information, which helps you while you want to debug your
application and develop a next version.
 That kind of service is ―EventLog‖.
 To open ―EventLog‖ and view the current events:
Start – Control Panel – Administrative Tools – Event Viewer.

.NET 4.0 and Visual Studio 2010 Page 229 of 548


Writing a new entry programmatically:
System.Diagnostics.EventLog.WriteEntry("project name", ―message‖, EventLogEntryType.Error);

Application 75: Demo on Event Log

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace EventLogDemo
{
class Program
{
static void Main(string[] args)
{
try
{
string filename = "c:\\sample.txt";
StreamReader sr = new StreamReader(filename);

string content = sr.ReadToEnd();


Console.WriteLine("The file content is:\n");
Console.WriteLine(content);
}
catch (Exception ex)
{
string EventMsg = ex.Message + "\n\n" + ex.StackTrace;
EventLog.WriteEntry("My Sample Project 1.0", EventMsg,
EventLogEntryType.Error);
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Press any key to exit..");
Console.Read();
}
}
}
}

.NET 4.0 and Visual Studio 2010 Page 230 of 548


Output:

Debugging
 Bug: An error.
 Debugging: Removing the bugs.

.NET offers more features for debugging. To start with the .NET application debugging, you
should create the break points.

Break Points

i) Definition: A break point is a point in the program, where the application execution
control pauses until you press ―F10‖ key. In the code, that line is highlighted with red
color.

ii) Creating a break point: Just click on the left side margin of the required line.

.NET 4.0 and Visual Studio 2010 Page 231 of 548


iii) Running the Application with Break Points: Just press ―F5‖ key. The
application will be executed normally. But whenever the execution control reaches to
the break point line, automatically the execution will be paused and the break point
line will be highlighted with yellow color. To continue with the execution to the next
statement, press “F10” key.

iv) Observing the values of variables or objects: While you are executing the
application with break points, to know the current value of any variable or object,
just place the mouse pointer over it.

Application 76: Demo on Break Points

.NET 4.0 and Visual Studio 2010 Page 232 of 548


Immediate window

 The ―Immediate‖ window resides at bottom side of Visual Studio IDE. It will automatically
appear at run time. If not, press ―Ctrl + Alt + I‖.
 This window is used to know the current values of the required variables, objects or data
members, which is not possible to find the value by just placing the mouse pointer over
it.

.NET 4.0 and Visual Studio 2010 Page 233 of 548


Application 77: Demo on Immediate window

Locals window

 It automatically displays all the current local variables along with their values.
 To open this window, while running the application, get into the Visual Studio and press
―Ctrl+D‖ and the ―L‖.

.NET 4.0 and Visual Studio 2010 Page 234 of 548


Assemblies

 Def: An assembly is the container of compiled code of .NET applications.


 It contains the code in MSIL (Microsoft Intermediate Language) language.
 At run time, it will be compiled by CLR‘s JIT compiler into machine language.
 The assembly file (with .exe or .dll extension) will be generated in the ‖project folder‖ \
―bin‖ folder, after compilation.

Types of Assemblies (based on extension):

1. Executable Assemblies / Process Assemblies / Private Assemblies (with .EXE


extension)
 This is generated with
A. Console Applications
B. Smart Device Applications
C. Windows Applications
 These files are ready for execution. You can execute those by simply double clicking.
 Limitation: The code in this assembly is not accessible from other projects.

2. Library Assemblies / Re-usable Assemblies / Shared Assemblies (with .DLL


extension)
 This is generated with
. Class Library
B. Windows Forms Control Library
 These are non-executable files.
 Advantage: The code is this assembly is accessible from other projects.

Overviewof“ClassLibrary”Project

 A ―class library‖ project is meant for the development of ―Shared Assemblies‖.


 The shared assemblies are re-usable in other applications also.

.NET 4.0 and Visual Studio 2010 Page 235 of 548


 That means the class library‘s code is re-usable in other applications, whenever required.
 Class library project contains only user-defined classes.
 Whenever the class library project is compiled, a library assembly file (with .DLL
extension) will be generated in the ―bin\Debug‖ folder.
 The class library project can‘t be executed directly unlike console applications, windows
applications etc.

Global Assembly Cache (GAC): All the shared assemblies should be saved in the GAC. GAC
offers the following advantages.
 Unique identification of the shared assemblies.
 Avoids the DLL hell (replacement of an assembly related to one application, by another
application).
 Faster accessibility.

.NET 4.0 and Visual Studio 2010 Page 236 of 548


To view the currently installed assemblies in the GAC, open the following folder.
C:\windows\assembly
The above folder is able to contain multiple dll files with same name, with different
versions.

Strong Name Keys (SNK): The ―strong name key‖ is a file, which acts as a unique
identifier, for the shared assemblies, stored in the GAC. In other words, GAC recognizes the
assembly with this strong name only.

Implementation Steps of Shared Assemblies

1. Create a Class Library Project.


 Create a new ―Class Library‖ project.
 Write the required code in the project.

2. Create a strong name key.


 Right click on the project in the ―Solution Explorer‖ and choose ―Properties‖.
 In the project properties, select the check box ―Sign the assembly‖.
 In the ―Choose a strong name key file‖ drop down, select ―<New>‖ option.
 In the ―Create strong name key‖ dialog box, enter the name of the strong name key
file.
 If password security is not required, uncheck the ―Protect my key file with a
password‖ checkbox.
 Click on OK.

3. Customize the “Assembly Information” (AssemblyInfo.cs).


 This is optional step.
 To change the additional details of the assembly like displayed name, version,
company, copy right, description etc., open “AssemblyInfo.cs” file from the
―Properties‖ folder in the Solution Explorer.

.NET 4.0 and Visual Studio 2010 Page 237 of 548


4. Generate the DLL File.
 Build the class library project.
 Then the ―.dll‖ file will be generated in the ―bin\debug‖ folder of your class library
project.

5. Write the assembly into GAC (Global Assembly Cache).


 Open the following folder.
C:\Windows\Assembly
 Drag and drop the ―.DLL file‖ from ―bin\Debug‖ folder into the
―c:\windows\assembly‖ folder.
 After dragging, the name of your shared assembly will appear in the existing list.
 Now, the shared assembly is ready. The rest of your work involved with the usage of
the shared assembly.

6. Invoke the Shared Assembly.


 Create the executable project (Console application / windows application).
 Click on ―Project‖ – ―Add Reference‖.
 Click on ―Browse‖ tab.
 Open the class library project‘s ―bin\Debug‖ folder.
 Select the ―dll file‖ and click on OK.
 Then the reference of the selected shared assembly will be added to the current
project.
 Then you can construct objects for the required class in the class library and perform
required activities on that.

Demo on Shared Assemblies

Application 78: Demo on Shared Assemblies

In this example,
Class Library Project: SharedAssemblyLibrary
Console Application Project: SharedAssemblyDemo

.NET 4.0 and Visual Studio 2010 Page 238 of 548


1. Create a Class Library Project.
 Open Visual Studio 2008.
 Click on ―File‖ – ―New‖ – ―Project‖.
 Select the language as ―Visual C#‖ and project template as ―Class Library‖.
 Enter the name as ―SharedAssemblyLibrary‖.
 Click on OK. It creates a new class library project. Initially it contains a new class
called ―class1‖.
 In the solution explorer, rename the ―class1.cs‖ as “MyLibraryClass.cs”.
 Then type the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharedAssemblyLibrary
{
public class MyLibraryClass
{
public bool IsValidLogin(string Username, string Password)
{
if (Username == "system" && Password == "manager")
return true;
else
return false;
}
}
}

2. Create a strong name key.


 Right click on the
project in the
―Solution Explorer‖
and choose
―Properties‖.
 In the project
properties, select
the check box ―Sign
the assembly‖.

Page 240 of 553


 In the ―Choose a strong name key file‖ drop down, select ―<New>‖ option.
 In the ―Create strong name key‖ dialog box, enter the name of the strong name key
file as “MyKeyFile”.
 Uncheck the ―Protect my key file with a password‖ checkbox.
 Click on OK.

3. Customize the “Assembly Information” (AssemblyInfo.cs).


 Change the assembly version as “1.5.0.0”.

4. Generate the DLL File.


 Build the class library project by clicking on ―Build‖ menu – ―Build Solution‖.

5. Write the assembly into GAC (Global Assembly Cache).


 Open the following folder.
C:\Windows\Assembly
 Drag and drop the “SharedAssemblyLibrary.DLL‖ file from ―bin\Debug‖ folder
into the ―c:\windows\assembly‖ folder.

6. Invoke the Shared Assembly.


 Create a new Console Application. Name: SharedAssemblyDemo
 Click on ―Project‖ – ―Add Reference‖.
 Click on ―Browse‖ tab.
 From the class library project‘s
―bin\Debug‖ folder, select the
“SharedAssemblyLibrary.dll‖
file and click on OK. Then the
.dll file reference will be added.

Page 241 of 553


 Enter the code as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedAssemblyLibrary;

namespace SharedAssemblyDemo
{
class Program
{
static void Main(string[] args)
{
MyLibraryClass mlc = new MyLibraryClass();

string Username, Password;


Console.Write("Enter Username: ");
Username = Console.ReadLine();
Console.Write("Enter Password: ");
Password = Console.ReadLine();

bool result = mlc.IsValidLogin(Username, Password);


if (result == true)
Console.WriteLine("\nLogin successful!");
else
Console.WriteLine("\nInvalid Username / Password!");

Console.Read();
}
}
}

Output:

Page 242 of 553


Windows Forms Applications
 C# supports two kinds of User Interfaces.
o C.U.I (Character User Interface)
 This user interface supports a blank screen, with some characters
only.
 It is not attractive for the user. That‘s why it is not suitable for the
live projects.

o G.U.I (Graphical User Interface)


 It supports graphical components like windows, icons, mouse
pointer, toolbars, status bars, buttons etc.
 It is attractive for the user. That‘s why it is suitable for the live
projects.

Page 243 of 553


 Almost all the software‘s you are using today like Notepad, WordPad,
Paint, MS Word, My computer and My documents etc., are the GUI
applications.

Windows Forms Application:

 It can also be called as ―Windows Application‖.


 It‘s a collection of windows forms.

A Windows Application

Login Form Registration Form

Data Entry Form Report Form

Page 244 of 553


Form:

 The graphical container, which


can contain the graphical
controls like labels, textboxes,
buttons, list boxes etc., is called
as ―Form‖. It acts as container
for the controls.
 It is also called as a ―window‖.
 It has the visual appearance
with a title bar, icon, control box
(with minimize button, maximize button and close button).

Creating a “Windows Forms Application” project:


 Open Microsoft Visual Studio 2010.
 Click on ―File‖ – ―New‖ – ―Project‖.
 Select the language as ―Visual C#‖.
 Select the project type as ―Windows Forms Application‖.
 Enter the name and location of the project.
 Click on ―OK‖.

Page 245 of 553


 Then it will create a windows forms application, along with a form, named ―Form1‖.
 Then the screen looks like this:

Page 246 of 553


Development of a Form

 It includes with two stages:


o Designing
o Coding

1) Designing the Form:

 Drag and Drop the controls from the ―ToolBox‖.

Application 79: A Sample Windows Application Project (with Login Form)

Page 247 of 553


 Select the control and set the properties as your wish.
 For example, set the following properties as per given below:
o Form1
 Text: Login
o Label1
 Text: User Name
o Label2
 Text: Password
o TextBox1
 (No properties are required in this example)
o TextBox2
 PasswordChar: *
o Button1
 Text: OK
o Button2
 Text: Cancel

Page 248 of 553


 Then the screen looks like this:

 The above process is called as ―Form designing‖.

2) Coding the Form:

 Double click on the controls and write the code in the ―Code window‖.
 For example, double click on ―OK‖ button and write the following code:

private void button1_Click(object sender, EventArgs e)


{
if (textBox1.Text == "system" && textBox2.Text == "manager")
MessageBox.Show("Login is successful.");
else
MessageBox.Show("Invalid Login.");
}

 And then, double click on ―Cancel‖ button and write the following code:

Page 249 of 553


private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}

 The above process is called as ―Form coding‖.

 Every Form is a Class:

 C#.NET recognizes every form as a ―class‖.


 In VB 6.0, every form is known as an object for the ―Form‖ class. But in C#, every form
is a class; so that at run time, you can create any no. of objects as your wish. For
example, if you want to display ―Login‖ form twice at run time, you can simply create
two objects and can show it.

 The Automatic Generated Code:

 While you design the controls, the Visual Studio generates some automatic code in the
“Form1.Designer.cs” file.
 To open this file, Open Solution Explorer, Expand ―Form1‖, then double click on
―Form1.Designer.cs‖.
 For example, you can see the automatic generated code for the previous ―Login‖
example:

Form1.Designer.cs:

namespace WindowsFormsApplication1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed;
otherwise, false.</param>

.NET 4.0 and Visual Studio 2010 Page 250250 of


548
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code


/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(186, 44);
this.textBox1.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(232, 27);
this.textBox1.TabIndex = 0;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(186, 102);
this.textBox2.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.textBox2.Name = "textBox2";
this.textBox2.PasswordChar = '*';
this.textBox2.Size = new System.Drawing.Size(232, 27);
this.textBox2.TabIndex = 1;
//
// button1
//
this.button1.Location = new System.Drawing.Point(186, 167);
this.button1.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(107, 37);
this.button1.TabIndex = 2;
this.button1.Text = "OK";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);

.NET 4.0 and Visual Studio 2010 Page 251 of 548


//
// button2
//
this.button2.Location = new System.Drawing.Point(314, 167);
this.button2.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(107, 37);

this.button2.TabIndex = 3; this.button2.Text
= "Cancel";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);

//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(64, 48);
this.label1.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(104, 19);
this.label1.TabIndex = 4;
this.label1.Text = "User Name:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(64, 107);
this.label2.Margin = new System.Windows.Forms.Padding(5, 0, 5, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(93, 19);
this.label2.TabIndex = 5;
this.label2.Text = "Password:";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 19F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 244);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Font = new System.Drawing.Font("Tahoma", 12F,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.Margin = new System.Windows.Forms.Padding(5, 4, 5, 4);
this.Name = "Form1";
this.Text = "Login";
this.ResumeLayout(false);
this.PerformLayout();

.NET 4.0 and Visual Studio 2010 Page 252 of 548


}

#endregion

private System.Windows.Forms.TextBox textBox1;


private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
}
}

 Don‘t worry about the above automatic generated code; it will be generated automatically,
while you design the form in the Design window.
 The entire code is generated in a method called ―InitializeComponent()‖.
 Finally, coming to a conclusion; every form contains two files:
o Form1.Designer.cs
Contains the code for designing (Automatically generated code by Visual Studio).
o Form1.cs
Contains the actual functionality code (Written by the Programmer).

Class Definition Syntax of a Windows Form:

Form1.cs

importing section;
namespace ProjectName
{
public partial class FormName : Form
{
public FormName()
{
InitializeComponent();
}
}
}

.NET 4.0 and Visual Studio 2010 Page 253 of 548


Rules for the Form class definition:

 In the importing section, you can import the necessary namespaces that you want.
 The namespace name should be same as project name.
 A user-defined class with the form name is to be defined.
 It should be the sub class of "System.Windows.Forms.Form" class; as it offers some
visual design, properties, methods and events for the user-defined form class.
 It will be defined as a public class (this is optional). Whenever it is a public class, in
future, it can be accessed from other projects also.
 It should be defined as "partial" class, as its definition is written in the following two files.
o Form1.cs
o Form1.Designer.cs
 It should contain a constructor, with a statement called ―InitializeComponent();‖,
which calls the designer code that is generated in ―Form1.Designer.cs‖ file.

 “Program.cs” file in Windows Forms Applications:

 Generally, when you ―Start‖ the windows application project, automatically the ―Form1‖
will be appeared on the screen.
 Then don‘t think like directly Form1 will be opened.
 In fact, when you click on ―Start‖ option, the Main() method will be invoked first.
 Like Console Applications, Main() method is located in ―Program.cs‖ file.

.NET 4.0 and Visual Studio 2010 Page 254 of 548


 For reference you open ―Solution Explorer‖ – ―Program.cs‖ file.
 In the Main() method, you can see two important statements.
 Application.EnableVisualStyles();
This statement enables the better styles (for sleek appearance) for the
entire application, based on the current working theme offered by the
O/S.

 Application.Run(new Form1());
This statement creates a new Form1 class object and that object will be
shown on the screen.

.NET 4.0 and Visual Studio 2010 Page 255 of 548


Controls Handling Windows Applications
Common Properties for all the controls:

 The following properties commonly available for all the controls:

Common Properties
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Specifies the mouse pointer style, when the mouse is over on the control at
Cursor
run time.
Size Specifies the Width and Height of the control.
Location Specifies the X and Y co-ordinations of the control‘s position on the form.
TextAlign Specifies the position of the text in the control.
Specifies the image that is to be displayed in the control along with the
Image
text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.

Common Events for all the controls:

 The following events commonly available for all the controls:

Common Events
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
Executes when any key is pressed on the keyboard, while the focus is on
KeyPress
the control.
Enter Executes when the focus is entered into the control.
Leave Executes when the focus got out of the control.

Event: An event is a run time action that can be performed by the user.
Let us practice the above properties and events on the button control.

.NET 4.0 and Visual Studio 2010 Page 256 of 548


Application 80: Demo on Buttons

 Take a new Windows Forms Application project.


 Design the form as follows:

 To design the form as above set the following properties.

Design
button1:
Text: What’s the time now?
button2:
Text: Show Me a Random Number
ForeColor: Green
button3:
Text: Exit
BackColor: Purple
ForeColor: Yellow
Image: c:\close.jpg
ImageAlign: MiddleLeft
FlatStyle: Popup
Font: Lucida Sans, Bold, 11

.NET 4.0 and Visual Studio 2010 Page 257 of 548


 Double click on ―Button1‖ and Write the following code:

private void button1_Click(object sender, EventArgs e)


{
DateTime dt = DateTime.Now;
MessageBox.Show(dt.ToString());
}

 Double click on ―Button2‖ and Write the following code:

private void button2_Click(object sender, EventArgs e)


{
Random r = new Random(); int
n = r.Next(1, 500);
MessageBox.Show(n.ToString());
}

 Double click on ―Button3‖ and Write the following code:

private void button3_Click(object sender, EventArgs e)


{
MessageBox.Show("Bye....");
Application.Exit();
}

 Then finally run the application.

Changing Property Values at run time


 You can change the property values at run time (programmatically).
 For example, you have designed a button with blue background. Later, after the user
clicks it, you want to display that button with green background.
 Then you require to change the ―BackColor‖ property value at run time.
 Syntax:
controlname.property = value;
 Ex:
button1.Text = ―Button is clicked‖;

.NET 4.0 and Visual Studio 2010 Page 258 of 548


 But sometimes, when you are trying to change some property values, you may face
some problems.
For example, the following statements are not valid statements:
button1.BackColor = ―green‖;
button1.Cursor = ―hand‖;
button1.TextAlign = ―TopLeft‖;
 So, while you are changing the property values, you remember and follow the following
syntaxes:

Assign Property Values at Run Time


Property Statement to assign the value at run time

Name Not possible to change at run time.

Text controlname.Text = ―xxxxx‖;

Enabled controlname.Enabled = true / false;

Visible controlname.Visible = true / false;

Location controlname.Location = new System.Drawing.Point(x, y);

Size controlname.Size = new System.Drawing.Size(width, height);


controlname.Font = new System.Drawing.Font(―font name‖,
Font
fontsize);

BackColor controlname.BackColor = System.Drawing.Color.xxxxx;

ForeColor controlname.ForeColor = System.Drawing.Color.xxxxx;

Cursor controlname.Cursor = System.Windows.Forms.Cursors.xxxxx;


controlname.Image = System.Drawing.Image.FromFile(―image file
Image
path‖);
controlname.TextAlign =
TextAlign
System.Drawing.ContentAlignment.MiddleRight;
controlname.TextAlign =
ImageAlign
System.Drawing.ContentAlignment.MiddleRight;

TabIndex controlname.TabIndex = n;

ContextMenuStrip controlname.ContextMenuStrip = xxxxx;

.NET 4.0 and Visual Studio 2010 Page 259 of 548


IMP Notes to remember:
In the above syntaxes, we are using few pre-defined classes, pre-defined structures and pre-
defined enumerations also.
1) System.Drawing.Point
2) System.Drawing.Size
Classes 3) System.Drawing.Font
4) System.Drawing.Image
5) System.Windows.Forms.Cursors
Structures 1) System.Drawing.Color
Enumerations 1) System.Drawing.ContentAlignment

Application 81: Demo on Changing Property Values at Run Time

.NET 4.0 and Visual Studio 2010 Page 260 of 548


private void button2_Click(object sender, EventArgs e)
{
button1.Text = "My Test Button";
}

private void button3_Click(object sender, EventArgs e)


{
button1.Enabled = false;
}

private void button4_Click(object sender, EventArgs e)


{
button1.Enabled = true;
}

private void button5_Click(object sender, EventArgs e)


{
button1.Visible = false;
}

private void button6_Click(object sender, EventArgs e)


{
button1.Visible = true;
}

private void button7_Click(object sender, EventArgs e)


{
button1.Location = new Point(150, 400);
}

private void button8_Click(object sender, EventArgs e)


{
button1.Size = new Size(250, 100);
}

private void button9_Click(object sender, EventArgs e)


{
button1.Font = new Font("Showcard Gothic", 17);
}

private void button10_Click(object sender, EventArgs e)


{
button1.BackColor = Color.LightCoral;
}

private void button11_Click(object sender, EventArgs e)


{
button1.ForeColor = Color.Green;
}

private void button12_Click(object sender, EventArgs e)


{

.NET 4.0 and Visual Studio 2010 Page 261 of 548


button1.Image = Image.FromFile("c:\\flagindia.gif");
button1.ImageAlign = ContentAlignment.MiddleLeft;
button1.TextAlign = ContentAlignment.MiddleRight;
button1.Size = new Size(200, 60);
}

Event Handling
 Def: The event handling includes with executing some code, whenever the user
performs an action.
 The necessary code is to be written in a special method. That method is called as ―Event
Handler‖.

Event Handler:

 An event handler is a method, which will be called automatically, whenever the user
performs certain event at run time.
 The event handler should be defined in the form class.
Syntax:

private void controlname_eventname(object sender, EventArgs e)


{
//some code
}

 In the above syntax, there are two arguments:


o sender: Represents the control, based on which the event is raised. For
example, in the ―button1_click‖ event handler, the ―sender‖ argument
represents ―button1‖ control.
o e: Contains some additional information about the event. For example, in the
―MouseClick‖ event, the position of the mouse will be represented, where it
is clicked.
 Event through you know the syntax of event handler properly, don‘t try to type it
manually in the code. The event handler method should be generated through the proper
way.

.NET 4.0 and Visual Studio 2010 Page 262 of 548


 In the previous examples, you have generated the event handlers by double clicking on
the controls.
 But already you know that, for all the controls, there are multiple events. But when you
double click the control, it will generate the event handler for only one event. That
particular event can be called as ―Default event‖.
 For example, the default event for the button is ―Click‖ event.
 If you want to implement the event handlers for other controls, you require to follow the
steps given below.

Implementation of Event Handler:

 First, in the design window, select the form or control, for which you want to create the
event handler.
 Open ―Properties‖ window, and click on ―Events‖
option.
 Select the required event, for which you want to create
the event handler.
 Press Enter.
 Then the event handler will be created in the code
window.

.NET 4.0 and Visual Studio 2010 Page 263 of 548


Application 82: Demo on Event Handling

Design
button1:
Text: Click Me
BackColor: DarkRed
ForeColor: Yellow

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show("You have clicked the button");
}

private void button1_MouseEnter(object sender, EventArgs e)


{
button1.BackColor = Color.Yellow;
button1.ForeColor = Color.DarkRed;
}

private void button1_MouseLeave(object sender, EventArgs e)


{
button1.BackColor = Color.DarkRed;
button1.ForeColor = Color.Yellow;
}

.NET 4.0 and Visual Studio 2010 Page 264 of 548


Working with Multiple Forms
Adding a new Form to the Project:
 In the ―Solution Explorer‖, right click on the project and choose ―Add‖ - Windows Form‖.
 In the dialog box, enter the name of the new form.
 Then the new form will be created.

Deleting a Form from the Project:


 In the ―Solution Explorer‖, right click on the required form, which you want to delete and
click on ―Delete‖ option.
 Click on OK for confirmation.

Changing Startup Form:


 Even, if you add multiple forms to the project, when the project is started, the ―Form1‖
will be opened by default. This is called as ―Startup orm‖.
 To change the startup form, change the following statement with the required class
name in the ―Program‖ class‘s Main() method.
Syn: Application.Run(new <form name>());
Ex: Application.Run(new Form2());

Invoke Forms at Run Time (Programmatically):


 To open any form at run time programmatically, you require to create an object for the
form class.
FormName obj = new FormName();
obj.Show();

Application 83: Multiple Forms Handling

.NET 4.0 and Visual Studio 2010 Page 265 of 548


Form1.cs

private void Form1_DoubleClick(object sender, EventArgs e)


{
Form2 f = new Form2();
f.Show();
}

Controls in Windows Applications

I. Common Controls
1) Button
2) Label
3) TextBox
4) PictureBox
5) LinkLabel
6) CheckBox
7) RadioButton
8) ListBox
9) ComboBox
10) DomainUpDown
11) NumericUpDown
12) DateTimePicker
13) MonthCalendar

.NET 4.0 and Visual Studio 2010 Page 266 of 548


II. Container Controls
14) Panel
15) GroupBox
16) TabControl
17) FlowLayoutPanel
18) SplitContainer
19) TableLayoutPanel
III. Background Process Controls
20) Timer
21) ProgressBar
IV. Menu & ToolBar Controls
22) MenuStrip
23) ContextMenuStrip
24) ToolStrip
25) StatusStrip
V. Dialog Box Controls
26) ColorDialog
27) FontDialog
28) FolderBrowserDialog
29) OpenFileDialog
30) SaveFileDialog
31) PrintDialog
VI. Data Controls
32) DataGridView
33) BindingSource
34) DataSet
35) Chart
VII. Component Controls
36) Tooltip
37) NotifyIcon
38) EventLog
39) ImageList
40) ErrorProvider

.NET 4.0 and Visual Studio 2010 Page 267 of 548


VIII. Reporting Controls
41) CrystalReportViewer
42) ReportViewer
IX. Other User Friendly Controls
43) LineShape
44) OvalShape
45) RectangleShape
46) PrintForm
X. Other User Friendly Controls
47) RichTextBox
48) TrackBar
49) TreeView
50) WebBrowser

.NET 4.0 and Visual Studio 2010 Page 268 of 548


The “System.Windows.Forms.Form” Class

The ―System.Windows.Forms.Form‖ class offers few properties, methods and events for each
user-defined form class.

Properties of “System.Windows.Forms.Form” Class


Property Description
Name Specifies the name of the form class.
Text Specifies the title bar text of the form.
ShowIcon Specifies whether the form icon is to be displayed or not.
ShowInTaskBar Specifies whether the task bar icon is to be displayed or not.
MinimizeBox Specifies whether the minimize button is to be displayed or not.
MaximizeBox Specifies whether the maximize button is to be displayed or not.
HelpButton Displays / hides the ? button in the form title bar.
Specifies whether the control box is to be displayed or not. Here
ControlBox
the control box means minimize, maximize and close buttons.
Enabled Activates / Deactivates the functionality of the entire form.
AutoScroll Enables / Disables automatic activation of scrollbars in the form.
TopMost Activates / de-activates the nature of ―Always on top‖
IsMDIContainer When it is true, the form acts as Parent form.
BackColor Specifies the background color of the form.
ForeColor Specifies default foreground color for all the controls of this form.
Font Specifies default font for all the controls of this form.
Specifies the background image of the form. It requires an image
BackgroundImage
file of any image format.
Specifies mode of the background image. (None / Tile / Center /
BackgroundImageLayout
Stretch / Zoom)
Specifies the icon of the form, displayed at left most side of the
Icon
form title bar. It requires icon file with ―.ico‖ file.
Specifies the status of the form window. (Normal / Minimized /
WindowState
Maximized)
Cursor Specifies the mouse cursor style. (Arrow, Hand etc.)
None / FixedSingle / Fixed3D / FixedDialog / Sizable /
FormBorderStyle
FixedToolWindow / SizableToolWindow
Size (Width and Heght) Specifies the size of the form (pixels format).
Location (X and Y) Specifies the position of the form (pixels format).
Opacity Specifies form graphics depth percentage. (1% to 100%)

Syntax to access the Properties at run time: this.Property = value;

.NET 4.0 and Visual Studio 2010 Page 269 of 548


While you are changing the property values, you remember and follow the following syntaxes:

Assign Form Property Values at Run Time


Property Statement to assign the value at run time
Name Not possible to change at run time.

Text this.Text = ―xxxxxxxxxx‖;

ShowIcon this.ShowIcon = true / false;

ShowInTaskbar this.ShowInTaskbar = true / false;

MinimizeBox this.MinimizeBox = true / false;

MaximizeBox this.MaximizeBox = true / false;

HelpButton this.HelpButton = true / false;

ControlBox this.ControlBox = true / false;

Enabled this.Enabled = true / false;

AutoScroll this.AutoScroll = true / false;

TopMost this.TopMost = true / false;

IsMdiContainer this.IsMdiContainer = true / false;

BackColor this.BackColor = System.Drawing.Color.xxxxxxx;

ForeColor this.ForeColor = System.Drawing.Color.xxxxxxx;

Font this.Font = new System.Drawing.Font(―font name‖, size);


this.BackgroundImage = System.Drawing.Image.FromFile(―image file
BackgroundImage
path‖);

BackgroundImageLayout this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.xxxxx

Icon this.Icon = new System.Drawing.Icon(―icon file path‖);

this.WindowState = System.Windows.Forms.FormWindowState.Normal;
(or)
WindowState this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
(or)
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
Cursor this.Cursor = System.Windows.Forms.Cursors.xxxxx;

FormBorderStyle this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.xxxxx;

Size this.Size = new System.Drawing.Size(width, height);

Location this.Location = new System.Drawing.Point(x, y);

Opacity this.Opacity = n;

.NET 4.0 and Visual Studio 2010 Page 270 of 548


IMP Notes to remember:
In the above syntaxes, we are using few pre-defined classes, pre-defined structures and pre-
defined enumerations also.
1) System.Drawing.Point
2) System.Drawing.Size
3) System.Drawing.Font
Classes
4) System.Drawing.Image
5) System.Drawing.Icon
6) System.Windows.Forms.Cursors

Structures 7) System.Drawing.Color
8) System.Drawing.ContentAlignment
9) System.Windows.Forms.ImageLayout
Enumerations
10) System.Windows.Forms.FormWindowState
11) System.Windows.Forms.FormBorderStyle

Methods of “System.Windows.Forms.Form” Class


Method Description
Hide() Makes the form invisible at run time.
Show() Makes the form visible at run time.
Close() Closes the form.
Syntax to access the Methods in the code: this.Method();

Events of “System.Windows.Forms.Form” Class


Event Description
Executes whenever the form is loaded in the memory at run time, before the
Load
form is displayed on the screen.
Shown Executes after the form is displayed on the screen.
FormClosing Executes when the form is about to be closed.
FormClosed Executes after the form is closed.
Click Executes when the user clicks on the form at run time.
DoubleClick Executes when the user double-clicks on the form at run time.
MouseMove Executes when the mouse pointer is moves across the form.
MouseEnter Executes when the mouse pointer is focused on to the form.
MouseLeave Executes when the mouse pointer is out of the form.
Move Executes when the form is moved at run time, using keyboard or mouse.
Resize Executes when the form is resized at run time.
KeyPress Executes when any key is pressed on the keyboard, while running on the form.
Enter Executes when the focus is got into the form.
Leave Executes when the focus is out of the form.

.NET 4.0 and Visual Studio 2010 Page 271 of 548


Application 84: Demo on Form Events

private void Form1_Load(object sender, EventArgs e)


{
this.Text = "This is load event.";
}

private void Form1_Move(object sender, EventArgs e)


{
this.Text = "This is move event.";
}

private void Form1_Click(object sender, EventArgs e)


{
this.Text = "This is click event.";
}

private void Form1_DoubleClick(object sender, EventArgs e)


{
this.Text = "This is double click event.";
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)


{
MessageBox.Show("Bye. Thank you.");
}

private void Form1_Resize(object sender, EventArgs e)


{
this.Text = "This is resize event.";
}

private void Form1_KeyPress(object sender, KeyPressEventArgs e)


{
this.Text = "This is key press event.";
}

.NET 4.0 and Visual Studio 2010 Page 272 of 548


Application 85: A Simple Demo on Form Properties

Design
Form1:
Text: Click the form

private void Form1_Click(object sender, EventArgs e)


{
this.Text = "Thanks for clicking";
this.BackColor = Color.Green;
this.WindowState = FormWindowState.Maximized;
}

Application 86: Demo on Form Properties

Design
button1:
Text: Red
Name: btnRed
button2:
Text: Green
Name: btnGreen
button3:
Text: Blue
Name: btnBlue

.NET 4.0 and Visual Studio 2010 Page 273 of 548


private void btnRed_Click(object sender, EventArgs e)
{
this.BackColor = Color.Red;
}

private void btnGreen_Click(object sender, EventArgs e)


{
this.BackColor = Color.Green;
}

private void btnBlue_Click(object sender, EventArgs e)


{
this.BackColor = Color.Blue;
}

Application 87: Demo on Form Properties

Design
button1:
Text: Normal
Name: btnNormal
button2:
Text: Minimize
Name: btnMinimize
button3:
Text: Maximize
Name: btnMaximize
button3:
Text: Exit
Name: btnExit

private void btnNormal_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Normal;
}

private void btnMinimize_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Minimized;
}

private void btnMaximize_Click(object sender, EventArgs e)


{

.NET 4.0 and Visual Studio 2010 Page 274 of 548


this.WindowState = FormWindowState.Maximized;
}

private void btnExit_Click(object sender, EventArgs e)


{
this.Close();
}

Application 88: Demo on Form Properties

Design
button1:
Text: Show Background Image
Name: btnShowBackgroundImage
button2:
Text: Clear Background Image
Name: btnClearBackgroundImage

private void btnShowBackgroundImage_Click(object sender, EventArgs e)


{
this.BackgroundImage = Image.FromFile("c:\\globe.jpg");
this.BackgroundImageLayout = ImageLayout.Zoom;
}

private void btnClearBackgroundImage_Click(object sender, EventArgs e)


{
this.BackgroundImage = null;
}

.NET 4.0 and Visual Studio 2010 Page 275 of 548


1) Button

It is known as action based control. Executes an operation, when it is clicked.


API: System.Windows.Forms.Button
Naming Convension: btnxxxxxx

Properties of Button
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Location Specifies the X and Y co-ordinations of the control‘s position on the form.
TextAlign Specifies the position of the text in the control.
Specifies the image that is to be displayed in the control along with the
Image
text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
FlatStyle Specifies style of the button. (Flat / Popup / Standard / System)

Events of Button
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
Executes when any key is pressed on the keyboard, while the focus is on
KeyPress
the control.
Enter Executes when the focus is get into the control.
Leave Executes when the focus is out of the control.

.NET 4.0 and Visual Studio 2010 Page 276 of 548


2) Label

Mainly used for presentation purpose, to display a message or description to the


user.

API: System.Windows.Forms.Label
Naming Convension: lblxxxxxx

Properties of Label
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Specifies the X and Y co-ordinations of the control‘s position on the
Location
form.
TextAlign Specifies the position of the text in the control.
Specifies the image that is to be displayed in the control along with
Image
the text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
Enables / disables automatic sizing of the control, based on the
AutoSize
text.

Events of Label
Event Description
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the control.
Executes when any key is pressed on the keyboard, while the focus
KeyPress
is on the control.
Enter Executes when the focus is entered into the control.
Leave Executes when the focus is out of the control.

.NET 4.0 and Visual Studio 2010 Page 277 of 548


3) TextBox
Used to take any user input in the application.
API: System.Windows.Forms.TextBox
Naming Convension: txtxxxxxx

Properties of TextBox
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
BackColor Specifies the background color of the control.
ForeColor Specifies the foreground color of the control.
Font Specifies the font style of the control‘s text.
Enabled Enables / Disables the control.
Visible Displays / Hides the control.
Cursor Specifies the mouse pointer style, when it is over on the control.
Size Specifies the Width and Height of the control.
Specifies the X and Y co-ordinations of the control‘s position on the
Location
form.
Specifies the position of the text in the control (Left / Center /
TextAlign
Right)
Specifies the image that is to be displayed in the control along with
Image
the text.
ImageAlign Specifies the position of the image in the control
TabIndex Specifies the index of the control in the tab order.
ContextMenuStrip Contains the reference of the respective context menu control.
Enables / disables read-only nature of the textbox. In the read only
ReadOnly
textbox, the user can not enter any text.
Enables / disables multiple lines in the text box. By default, the text
MultiLine
box will be single-line textbox.
This is used in multi line textboxes, which automatically moves the
WordWrap
cursor to the next line, when the current line exceeds.
Scrollbars Enables / disables scroll bars in the textbox.
PasswordChar Used to specify the password display character. Ex: *
Specifies the maximum no. of characters that can be entered in the
MaxLength
textbox.

Events of TextBox
Event Description
TextChanged Executes when any character is typed / removed in the textbox.
Click Executes when the user clicks the control run time.
DoubleClick Executes when the user double-clicks the control at run time.
MouseMove Executes when the mouse pointer is moves across the control.
MouseEnter Executes when the mouse pointer is focused on to the control.
MouseLeave Executes when the mouse pointer is out of the button.
Executes when any key is pressed on the keyboard, while the focus
KeyPress
is on the control.

.NET 4.0 and Visual Studio 2010 Page 278 of 548


Enter Executes when the focus is entered into the control.
Leave Executes when the focus is out of the control.

Methods of TextBox
Method Description
Clear() Clears all the contents of the textbox and makes it empty.
Focus() Moves the focus to the control.

Application 89: Demo on TextBox Design


label1:
Text: Enter your Name:
Name: lblName
textBox1:
Name: txtName
label2:
Text: Message
Name: lblMessage
Visible: False
button1:
Text: OK
Name: btnOK
ForeColor: Red

private void btnOK_Click(object sender, EventArgs e)


{
string name = txtName.Text;
string message = "Welcome to " + name;
lblMessage.Text = message;
lblMessage.Visible = true;
}

.NET 4.0 and Visual Studio 2010 Page 279 of 548


Application 90: Demo on TextBox

Design
label1:
Text: Enter First Value:
Name: lblFirstValue (Continued…)
button3:
textBox1: Name: btnMultiply
Name: txtFirstValue Text: *
label2: button4:
Text: Enter Second Value: Name: btnDivide
Name: lblSecondValue Text: /
button1: label3:
Name: btnAdd Name: lblResult
Text: + Text: Result:
button2: textBox3:
Name: btnSubtract Name: txtResult
Text: - ReadOnly: True

.NET 4.0 and Visual Studio 2010 Page 280


private void btnAdd_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a + b;
txtResult.Text = Convert.ToString(c);
}

private void btnSubtract_Click(object sender, EventArgs e)


{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a - b;
txtResult.Text = Convert.ToString(c);
}

private void btnMultiply_Click(object sender, EventArgs e)


{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a * b;
txtResult.Text = Convert.ToString(c);
}

private void btnDivide_Click(object sender, EventArgs e)


{
int a = Convert.ToInt32(txtFirstValue.Text);
int b = Convert.ToInt32(txtSecondValue.Text);
int c = a / b;
txtResult.Text = Convert.ToString(c);
}

Application 91: Demo on TextBox

Design
label1:
Text: Enter your text here:
Name: lblSourceText
textBox1:
Name: txtSourceText
label2:
Text: Copied Text:
Name: lblDestinationText
button1:
Name: txtDestinationText
ReadOnly: True

.NET 4.0 and Visual Studio 2010 Page 281


private void txtSourceText_TextChanged(object sender, EventArgs e)
{
txtDestinationText.Text = txtSourceText.Text;
}

Application 92: Demo on TextBox


Design
label1:
Text: Generate Numbers
Name: lblGenerateNumbers
label2:
Text: From:
Name: lblFrom
textBox1:
Name: txtFrom

label3:
Text: To:
Name: lblTo
textBox2:
Name: txtTo

button1:
Name: btnGo
Text: GO
textBox3:
Name: txtNumbers
ReadOnly: True
MultiLine: True
ScollBars: Vertical

private void btnGO_Click(object sender, EventArgs e)


{
int n1 = Convert.ToInt32(txtFrom.Text);
int n2 = Convert.ToInt32(txtTo.Text);
txtNumbers.Clear();
for (int i = n1; i <= n2; i++)
{
txtNumbers.Text = txtNumbers.Text + i + ", ";
}
txtFrom.Focus();
}

.NET 4.0 and Visual Studio 2010 Page 282


4) CheckBox

Used to take the choice from the user. The check box can be checked or
un-checked by the user.

API: System.Windows.Forms.CheckBox
Naming Convension: chkxxxxxx

Properties of CheckBox
Property Description
Name Specifies the name of the control.
Represents the current status of the check box, whether it is
Checked
checked or un-checked.
Text Specifies the displayable text of the control.
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip

Events of CheckBox
Event Description
CheckedChanged Executes when the user checks / un-checks the checkbox.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of CheckBox
Method Description
Focus() Moves the focus to the control.

Application 93: Demo on CheckBox

.NET 4.0 and Visual Studio 2010 Page 283


private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
label1.Text = "The check box is checked.";
else
label1.Text = "The check box is un-checked.";
}

5) RadioButton

Used to take the choice from the user. We have to implement two or
more radio buttons. At run time, any one of the radio buttons can be
selected.

API: System.Windows.Forms.RadioButton
Naming Convension: rbxxxxxx

Properties of RadioButton
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
Represents the current status of the check box, whether it is
Checked
checked or un-checked.
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip

Events of RadioButton
Event Description
CheckedChanged Executes when the user checks / un-checks the radio button.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of RadioButton
Method Description
Focus() Moves the focus to the control.

.NET 4.0 and Visual Studio 2010 Page 284


Application 94: Demo on RadioButton

Design
label1:
Text: Select Background Color:
Name: lblBackgroundColor
radioButton1: Text:
Beige Name:
rbBeige
radioButton2:
Text: Light Green
Name: rbLightGreen

radioButton3:
Text: Light Yellow
Name: rbLightYellow
radioButton4: Text:
Bisque Name:
rbBisque

private void rbBeige_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.Beige;
}

private void rbLightGreen_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.LightGreen;
}

private void rbLightYellow_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.LightYellow;
}

private void rbBisque_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.Bisque;
}

.NET 4.0 and Visual Studio 2010 Page 285


6) LinkLabel
Used to create hyperlinks.

API: System.Windows.Forms.LinkLabel
Naming Convension: lnkxxxxxx

Properties of LinkLabel
Property Description
Name Specifies the name of the control.
Text Specifies the displayable text of the control.
LinkColor Specifies the default link color
VisitedLinkColor Specifies the visited link color
ActiveLinkColor Specifies the active link color
BackColor, ForeColor, Font, Enabled, Visible, Cursor, Size, Location, TextAlign, Image, ImageAlign,
TabIndex, ContextMenuStrip

Events of LinkLabel
Event Description
LinkClicked Executes when the user clicks on the link.
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of LinkLabel
Method Description
Focus() Moves the focus to the control.

Application 95: Demo on LinkLabel

Design
linkLabel1:
Text: My Link Label:
Name: linkLabel1

.NET 4.0 and Visual Studio 2010 Page 286


private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
MessageBox.Show("The link label is clicked.");
}

7) PictureBox
Used to display an image on the form, at desired place.

API: System.Windows.Forms.PictureBox
Naming Convension: picxxxxxx

Properties of PictureBox
Property Description
Name Specifies the name of the control.
Image Specifies the image, which is to be displayed in the control.
Specifies mode of the image sizing in the control.
SizeMode
(Normal, Stretch, Auto Size, Center, Zoom)
BackColor, Enabled, Visible, Cursor, Size, Location, ContextMenuStrip

Events of PictureBox
Event Description
Click Executes when the user clicks on the picture box.
DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Application 96: Demo on PictureBox

Design button2:
label1: Text: Clear Image
Text: Enter image path: Name: btnClearImage
Name: lblEnterImagePath
label2: radioButton3:
textBox1: Text: Size Mode: Text: Auto Size
Name: txtImagePath ForeColor: Red Name: rbAutoSize
button1: radioButton1: radioButton4:
Text: Show Text: Normal Text: Center
Name: btnShow Name: rbNormal Name: rbCenter
pictureBox1: radioButton2: radioButton5:
BorderStyle: Fixed3D Text: Stretch Text: Zoom
Name: picBoxImage Name: rbStretch Name: rbZoom

.NET 4.0 and Visual Studio 2010 Page 287


using System.IO;

private void btnShow_Click(object sender, EventArgs e)


{
string imagepath = txtImagePath.Text;
FileInfo fobj = new FileInfo(imagepath);
if (fobj.Exists)
{
picBoxImage.Image = Image.FromFile(imagepath);
}
else
{
MessageBox.Show("Image file not found.");
}
}

private void btnClearImage_Click(object sender, EventArgs e)


{
picBoxImage.Image = null;
}

private void rbNormal_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.Normal;
}

.NET 4.0 and Visual Studio 2010 Page 288


private void rbStretch_CheckedChanged(object sender, EventArgs e)
{
picBoxImage.SizeMode = PictureBoxSizeMode.StretchImage;
}

private void rbAutoSize_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.AutoSize;
}

private void rbCenter_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.CenterImage;
}

private void rbZoom_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
}

.NET 4.0 and Visual Studio 2010 Page 289


8) Panel

This acts as container, which can contain other type


of controls like labels, textboxes, buttons,
checkboxes etc.

API: System.Windows.Forms.Panel
Naming Convension: pnlxxxxxx

Properties of Panel
Property Description
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip, BorderStyle

Events of Panel
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Application 97: Demo on Panel

Note: When you want to create multiple groups of radio buttons, then use the panel or group
box control to group-up those radio buttons.

.NET 4.0 and Visual Studio 2010 Page 290of 548


9) GroupBox

This is also acts as container, similar to panel, but it


contains text also.

API: System.Windows.Forms.GroupBox
Naming Convension: grpxxxxxx

Properties of GroupBox
Property Description
Name, Text, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip

Events of GroupBox
Event Description
Enter, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Leave

Application 98: Demo on GroupBox

.NET 4.0 and Visual Studio 2010 Page 291of 548


Design
textBox1:
Name: txtMyTextBox radioButton3:
Text: Yellow
groupBox1: Name: rbYellow
Name: grpBackgroundColor
Text: TextBox Background Color: radioButton4:
Text: Blue
groupBox2: Name: rbBlue
Name: grpForegroundColor
Text: TextBox Foreground Color: radioButton5:
Text: Green
radioButton1:
Text: White Name: rbGreen
Name: rbWhite
radioButton6:
radioButton2: Text: Text: Orange
Red Name: Name: rbOrange
rbRed

private void rbWhite_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.BackColor = Color.White;
}

private void rbRed_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.BackColor = Color.Red;
}

private void rbYellow_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.BackColor = Color.Yellow;
}

private void rbBlue_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.ForeColor = Color.Blue;
}

private void rbGreen_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.ForeColor = Color.Green;
}

private void rbOrange_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.ForeColor = Color.Orange;
}

.NET 4.0 and Visual Studio 2010 Page 292of 548


10) ListBox

This contains multiple options (items). Among those items, the user can
select any one option. In some list boxes, multiple items also can be
selected. Those list boxes are called as ―Mutiple item selection list
boxes‖.

API: System.Windows.Forms.ListBox
Naming Convension: lstxxxxxx

Properties of ListBox
Property Description
Items Contains the list of items, that can be displayed in the list box.
Specifies mode of the item selection.
None – No item can be selected.One - Single item can only be selected
SelectionMode MultiSimple – Multiple items can be selected, directly by clicking on the items.
MultiExtended – Multiple items can be selected, with Shift+Click or Ctrl+Click.

Sorted Enables / disables automatic sorting of items


Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of ListBox
Event Description
SelectedIndexChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Leave

Run Time Properties of ListBox


Property Description
ListboxName.SelectedItem Represents the currently selected item in the list box.
ListboxName.SelectedIndex Represents the index of the currently selected item in the list box.
ListboxName.Items.Count Represents the total no. of items in the list box.
ListboxName.Items[index] Gets the specified item, based on the given index.
Represents the total no. of items, currently being selected. (For
ListboxName.SelectedItems.Count
multiple selection list boxes)
Gets the particular item in the currently selected items. (For
ListboxName.SelectedItems[index]
multiple selection list boxes)

Methods of ListBox
Property Description
ListboxName.Items.Add(―xxxxx‖) Adds a new item at the end of the list box items.
ListboxName.Items.Insert(index,
Inserts a new item at the specified position.
―xxxx‖)
ListboxName.Items.RemoveAt(index) Removes an item, based on its index.
ListboxName.Items.Clear() Removes all the items in the list box.
Searches the given string the items collection, and returns the
ListboxName.Items.IndexOf(―xxxx‖)
index, if it is found; otherwise, it returns -1.

.NET 4.0 and Visual Studio 2010 Page 293of 548


Application 99: Demo on Single item Selection ListBox

Design
label1:
Name: lblSelectCourse
Text: Select your Course:
label3:
listBox1: Name: lblSelectedCourse
Name: lstCourses Text: Selected Course Here
Items: .NET 4.0
Java label4:
Share Point Name: lblSelectedCourseIndexPrompt
Oracle DBA Text: Selected Course Index:
Sql Server label5:
QTP Name: lblSelectedCourseIndex
MS BI Text: Selected Course Index Here
label2:
Name: lblSelectedCoursePrompt
Text: Selected Course:

private void lstCourses_SelectedIndexChanged(object sender, EventArgs e)


{
lblSelectedCourse.Text = Convert.ToString(lstCourses.SelectedItem);
lblSelectedCourseIndex.Text = Convert.ToString(lstCourses.SelectedIndex);
}

.NET 4.0 and Visual Studio 2010 Page 294of 548


Application 100: Demo on Single item Selection ListBox

Design
groupBox1:
Name: grpCities
Text: Cities:
listBox1: button1:
Name: lstCities Name: btnAdd
Items: Hyderabad Text: Add
Pune
New Delhi button2:
Banglore Name: btnRemoveCity
Dehradun Items: Remove Selected City

groupBox2: button3:
Name: grpOptions Name: btnClearAll
Text: Options: Text: Clear All

label1: button4:
Name: lblNewCity Name: btnShowCount
Text: New City Name: Text: Show Count

textBox1:
Name: txtNewCity

.NET 4.0 and Visual Studio 2010 Page 295of 548


private void btnAdd_Click(object sender, EventArgs e)
{
if (txtNewCity.Text != "")
{
lstCities.Items.Add(txtNewCity.Text);
txtNewCity.Clear();
}
else
MessageBox.Show("Enter new city name.");
txtNewCity.Focus();
}

private void btnRemoveCity_Click(object sender, EventArgs e)


{
if (lstCities.SelectedIndex >= 0)
lstCities.Items.RemoveAt(lstCities.SelectedIndex);
else
MessageBox.Show("Select any city.");
}

private void btnClearAll_Click(object sender, EventArgs e)


{
lstCities.Items.Clear();
MessageBox.Show("All cities cleared.");
}

private void btnShowCount_Click(object sender, EventArgs e)


{
int count = lstCities.Items.Count;
MessageBox.Show(count + " cities found.");
}
Design
Applicati Name: lblAvailableBooks
on 101: Text: Available Books:
Demo on
Multiple
item
Selection
ListBox

label1:

.NET 4.0 and Visual Studio 2010 Page 296of 548


label2:
Name: lblSelectedBooks
listBox1:
Text: Selected Books:
Name: lstAvailableBooks
Sorted: True listBox2:
SelectionMode: MultiSimple Name: lstSelectedBooks
Items: ASP.NET for Professionals Sorted: True
C# 4.0 for Beginners
HTML 4.0 button1:
Java Complete Reference Name: btnSend
JavaScript Bible
Let Us C
Let Us C++

.NET 4.0 and Visual Studio 2010 Page 297of 548


private void btnSend_Click(object sender, EventArgs e)
{
int i;
lstSelectedBooks.Items.Clear();
for (i = 0; i < lstAvailableBooks.SelectedItems.Count; i++)
lstSelectedBooks.Items.Add(lstAvailableBooks.SelectedItems[i]);
}

11) ComboBox

This also contains multiple options (items), similar to list box.


But, unlike list box, in the combo box, the user can‘t select
multiple items. One more advantage of combo box is, it offers
some text entry similar to text box. Finally the combo box is a combination of list box and text
box.

API: System.Windows.Forms.ComboBox
Naming Convension: cmbxxxxxx

Properties of ComboBox
Property Description
Items Contains the list of items that can be displayed in the list box.
Simple: It looks like a text box, but the items can be accessed by pressing up / down
arrow keys.
DropDownStyle DropDown: It is the default value. The user can type new text (or) can select the
items from the list.
DropDownList: The user can type new text. Only selection is possible.
Sorted Enables / disables automatic sorting of items
Name, Text, TextAlign, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of ComboBox
Event Description
SelectedIndexChanged, TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave,
KeyPress, Leave

Run Time Properties of ComboBox


Property Description
cmbObj.SelectedItem Represents the currently selected item in the combo box.
Represents the index of the currently selected item in the combo
cmbObj.SelectedIndex
box.
cmbObj.Items.Count Represents the total no. of items in the combo box.
cmbObj.Items[index] Gets the specified item, based on the given index.
cmbObj.Text Gets the text, entered in the combo box.

.NET 4.0 and Visual Studio 2010 Page 298of 548


Methods of ComboBox
Method Description
cmbObj.Items.Add(―xxxxx‖) Adds a new item at the end of the combo box items.
cmbObj.Items.Insert(index, ―xxxx‖) Inserts a new item at the specified position.
cmbObj.Items.RemoveAt(index) Removes an item, based on its index.
cmbObj.Items.Clear() Removes all the items in the combo box.
Searches the given string the items collection, and returns the
cmbObj.Items.IndexOf(―xxxx‖)
index, if it is found; otherwise, it returns -1.
cmbObj.Clear() Clears the text entered in the combo box.

Application 102: Demo on ComboBox

Design
label1:
Name: lblSeleCourse
Text: Select Course:
comboBox1:
Name: cmbCourse
DropDownStyle: DropDownList
Items: .NET
Java
C
C++
Oracle
label2:
Name: lblFee
Text: Fee:
textBox1:
Name: txtFee
ReadOnly: True

.NET 4.0 and Visual Studio 2010 Page 299of 548


private void cmbCourse_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbCourse.SelectedIndex == 0)
txtFee.Text = "Rs. 4,900/-";
else if (cmbCourse.SelectedIndex == 1)
txtFee.Text = "Rs. 6,200/-";
else if (cmbCourse.SelectedIndex == 2)
txtFee.Text = "Rs. 1,000/-";
else if (cmbCourse.SelectedIndex == 3)
txtFee.Text = "Rs. 1,200/-";
else if (cmbCourse.SelectedIndex == 4)
txtFee.Text = "Rs. 1,500/-";
}

12) NumericUpDown

This offers to enter a numerical value, within a given range. The user can enter a
value, out of the range.

API: System.Windows.Forms.NumericUpDown
Naming Convension: numxxxxxx

Properties of NumericUpDown
Property Description
Value Gets or sets the current value in the NumericUpDown control.
DecimalPlaces Specifies the no. of decimal places in the value
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
TextAlign Left / Center / Right
UpDownAlign Left / Right
Name, ReadOnly, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip, BorderStyle

Events of NumericUpDown
Event Description
ValueChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

.NET 4.0 and Visual Studio 2010 Page 300of 548


13) DomainUpDown

It is similar to combo box, but it looks like NumericUpDown.

API: System.Windows.Forms.DomainUpDown
Naming Convension: domxxxxxx

Properties of DomainUpDown
Property
Items, Sorted, Name, Text, TextAlign, BackColor, ForeColor, Font, Enabled, Visible, Size, Location,
ContextMenuStrip

Events of DomainUpDown
Event
SelectedItemChanged, TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave,
KeyPress, Leave

Run Time Properties of DomainUpDown


Property
domObj.SelectedItem, domObj.SelectedIndex, domObj.Items.Count, domObj.Items[index], domObj.Text

Methods of DomainUpDown
Method
domObj.Items.Add(―xxxxx‖) Adds a new item at the end of the domainupdown items.
domObj.Items.Insert(index, ―xxxx‖) Inserts a new item at the specified position.
domObj.Items.RemoveAt(index) Removes an item, based on its index.
domObj.Items.Clear() Removes all the items in the domainupdown.
Searches the given string the items collection, and returns the
domObj.Items.IndexOf(―xxxx‖)
index, if it is found; otherwise, it returns -1.
domObj.Clear() Clears the text entered in the domainupdown.

Application 103: Demo on NumericUpDown and DomainUpDown

.NET 4.0 and Visual Studio 2010 Page 301of 548


Design
textBox1:
Name: txtMyText
label1:
Name: lblFont label2:
Name: lblSize
Text: Font:
Text: Size:
domainUpDown1:
Name: domFont label3:
Name: numSize
Text: Tahoma
Value: 10
Items: Times New Roman
Tahoma Minimum: 1
Maximum: 100
Arial
Arial Black
Century Gothic
Trebuchet MS
Palatino Linotype

private void ChangeFont()


{
string font = Convert.ToString(domFont.SelectedItem);
int size = Convert.ToInt32(numSize.Value);
txtMyText.Font = new Font(font, size);
}

private void domFont_SelectedItemChanged(object sender, EventArgs e)


{
ChangeFont();
}

.NET 4.0 and Visual Studio 2010 Page 302of 548


private void numSize_ValueChanged(object sender, EventArgs e)
{
ChangeFont();
}

14) DateTimePicker

This control enables the user, to select a date


or time value at run time. When the drop down
button is clicked, it displays a calendar for date selection. When you change the ―Format‖
property, it offers to select the time also.

API: System.Windows.Forms.DateTimePicker
Naming Convension: dtPickerxxxxxx

Properties of DateTimePicker
Property Description
Value Gets or sets the current value in the control.
Format Specifies the format of the date selection. (Short / Long / Time / Custom)
Used to specify the customer date formats. (with words and symbols like dd,
CustomFormat
mm, yyyy, -, / etc.)
ShowUpDown Enables / Disables the ―up/down‖ buttons in the control.
MinDate Specifies the minimum date, which can be selected at run time.
MaxDate Specifies the maximum date, which can be selected at run time.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of DateTimePicker
Event
ValueChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Application 104: Demo on DateTimePicker

.NET 4.0 and Visual Studio 2010 Page 303of 548


Design
label1:
Name: lblSelectDOB
Text: Select Date of Birth:
dateTimePicker1:
Name: dtPickerDOB
Format: Short
label2:
Name: lblAgePrompt
Text: Age:
label3:
Name: lblAge
Text: Age here

private void Form1_Load(object sender, EventArgs e)


{
dtPickerDOB.Value = DateTime.Now.AddYears(-20);
}

private void dtPickerDOB_ValueChanged(object sender, EventArgs e)


{
DateTime dob = dtPickerDOB.Value;
DateTime now = DateTime.Now;
if (now > dob)
{
TimeSpan ts = now - dob; int
Age = ts.Days / 365;
lblAge.Text = Age + " years.";
}
else
lblAge.Text = "Invalid DOB.";
}

15) MonthCalendar

Similar to DateTimePicker. It offers for a date selection. But this


control, displays the calendar directly. In the calendar, the user can
select any date.

API: System.Windows.Forms.MonthCalendar
Naming Convension: monCalxxxxxx

.NET 4.0 and Visual Studio 2010 Page 304of 548


Properties of MonthCalendar
Property Description
ShowToday Displays / hides today‘s date at the bottom of the control.
ShowWeekNumbers Displays / hides the week no‘s at left side.
MinDate Specifies the minimum date, which can be selected at run time.
MaxDate Specifies the maximum date, which can be selected at run time.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, ContextMenuStrip

Events of MonthCalendar
Event Description
DateChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Note: There is not any property, which gets the currently selected date in the calendar; so that,
we have to use ―DateRangeEventArgs‖ class object to access currently selected date value in the
―DateChanged‖ event.

Application 105: Demo on MonthCalendar

.NET 4.0 and Visual Studio 2010 Page 305of 548


Design
label1:
Name: lblSelectAnyDate
Text: Select any Date:
monthCalendar1:
Name: monCalMyDate
label2:
Name: lblSelectedDate
Text: Select Date Here

private void monCalMyDate_DateChanged(object sender, DateRangeEventArgs e)


{
DateTime dt = e.Start;
lblSelectedDate.Text = "You have selected: " + dt.ToShortDateString();
}

.NET 4.0 and Visual Studio 2010 Page 306of 548


16) TrackBar

Similar to numericupdown, but it offers


visualization for the value selection.

API: System.Windows.Forms.TrackBar
Naming Convension: trkxxxxxx

Properties of TrackBar
Property Description
Value Gets or sets the current value in the control.
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
TickFrequency Specifies the difference between each tick.
Orientation Horizontal / Vertical
TickStyle None, TopLeft, BottomRight, Both
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BorderStyle

Events of TrackBar
Event Description
Scroll, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Application 106: Demo on TrackBar

.NET 4.0 and Visual Studio 2010 Page 307of 548


Design
label1:
Name: lblFontSize
Text: Font Size:
trackBar1:
Name: trkFontSize
Minimum: 1
Maximum: 200
TickFrequency: 5
label2:
Name: lblMyText
Text: .NET Framework 4

private void trkFontSize_Scroll(object sender, EventArgs e)


{
int n = trkFontSize.Value;
lblMyText.Font = new Font("Tahoma", n);
}

17) Timer

It is known as ―Invisible Control‖. That means it can‘t be displayed on the form


UI. But it works during the execution time. It performs background processing.
It executes a certain logic, whenever a certain interval time is completed.

API: System.Windows.Forms.Timer
Naming Convension: tmrxxxxxx

Properties of Timer
Property Description
Interval Specifies the interval time of the timer, in the form of mille seconds.
Name, Enabled
Events of Timer
Event
Tick Executes on every completion of interval time.

Application 107: Demo on Timer

.NET 4.0 and Visual Studio 2010 Page 308of 548


Design
label1:
Name: lblTime
Text: Time here
timer1:
Name: tmrTime
Interval: 1000
Enabled: True

private void Form1_Load(object sender, EventArgs e)


{
lblTime.Text = DateTime.Now.ToLongTimeString();
}

private void tmrTime_Tick(object sender, EventArgs e)


{
lblTime.Text = DateTime.Now.ToLongTimeString();
}

Application 108: Demo on Timer

Design
timer1:
Name: tmrBackColor
Interval: 500
Enabled: True

.NET 4.0 and Visual Studio 2010 Page 309of 548


int n = 0;

private void tmrBackColor_Tick(object sender, EventArgs e)


{
n++;
switch (n)
{
case 1: this.BackColor = Color.Black; break;
case 2: this.BackColor = Color.Blue; break;
case 3: this.BackColor = Color.LightCoral; break;
case 4: this.BackColor = Color.LightCyan; break;
case 5: this.BackColor = Color.Green; break;
case 6: this.BackColor = Color.Red; break;
case 7: this.BackColor = Color.Chocolate; break;
case 8: this.BackColor = Color.DarkKhaki; break;
case 9: this.BackColor = Color.Firebrick; break;
case 10: this.BackColor = Color.Gold; break;
default: n = 0; break;
}
}

18) ProgressBar

It shows the progress of a certain process. It‘s value is


limited to the range of 0 to 100. Whenever its value is
reached to 100, that means the process is completed. It can be implemented with the
combination of timer control.

API: System.Windows.Forms.ProgressBar
Naming Convension: prgxxxxxx

Properties of ProgressBar
Property Description
Value Gets or sets the current value in the control.
Minimum Specifies the minimum value in the range.
Maximum Specifies the maximum value in the range.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BackgroundImage,
BackgroundImageLayout

Events of ProgressBar
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

.NET 4.0 and Visual Studio 2010 Page 310 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

Application 109: Demo on Progress Bar

Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName textBox2:
Name: txtContent
button1: ReadOnly: True
Name: btnOpen WordWrap: False
Text: Open Multiline: True
label2: Scrollbars: Both
Name: lblLoading timer1:
Text: Loading… Name: tmrFileOpen
ForeColor: Red Enabled: False
Visible: False Interval: 100
progressBar1:
Name: prgFile
Visible: False

.NET 4.0 and Visual Studio 2010 Page 311 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

using System.IO;

private void OpenFile()


{
string filename = txtFileName.Text;
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filename);
string content = sr.ReadToEnd();
txtContent.Text = content;
sr.Close();
}
else
MessageBox.Show("File not found.");
}

private void btnOpen_Click(object sender, EventArgs e)


{
prgFile.Value = 0;
tmrFileOpen.Enabled = true;
lblLoading.Visible = true;
prgFile.Visible = true;
}

private void tmrFileOpen_Tick(object sender, EventArgs e)


{
prgFile.Value++;
if (prgFile.Value == 100)
{
tmrFileOpen.Enabled = false;
lblLoading.Visible = false;
prgFile.Visible = false;
OpenFile();
}
}

19) MenuStrip

Used to create a menu bar in the form. A menu bar


is a collection of multiple menu items. It is known
as invisible control. The menu items are of two types.
1) Parent Menu Items
2) Child Menu Items

.NET 4.0 and Visual Studio 2010 Page 312 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

API: System.Windows.Forms.MenuStrip
Naming Convension: mnuxxxxxx

Each menu item will be created as a control for


“System.Windows.Forms.ToolStripMenuItem” class. The default naming convention for the
menu item is: ―xxxxxToolStripMenuItem‖.

Properties of MenuStrip
Property Description
Dock Top, Bottom, Left, Right, Fill
TextDirection Horizontal, Vertial90, Vertical270.
Name, BackColor, ForeColor, Font, Enabled, Visible, Size, Location, BackgroundImage,
BackgroundImageLayout, ContextMenuStrip
Events of MenuStrip
Event Description
ItemClicked, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Properties of Menu Item


Property Description
Name, Text, TextAlign, BackColor, ForeColor, Font, Image, ImageAlign, Checked, Enabled, Visible,
ShortcutKeys, ShowShortcutKeys, Size, Location, BackgroundImage, BackgroundImageLayout,
ContextMenuStrip, BorderStyle
Events of Menu Item
Event Description
Click, DoubleClick, MouseMove, MouseEnter, MouseLeave

Application 110: Demo on MenuStrip

.NET 4.0 and Visual Studio 2010 Page 313 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

private void showToolStripMenuItem_Click(object sender, EventArgs e)


{
this.BackgroundImage = Image.FromFile("c:\\globe.jpg");
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)


{
this.BackgroundImage = null;
}

private void normalToolStripMenuItem_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Normal;
}

private void minimizedToolStripMenuItem_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Minimized;
}

private void maximizedToolStripMenuItem_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Maximized;
}

.NET 4.0 and Visual Studio 2010 Page 314 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

private void form2ToolStripMenuItem_Click(object sender, EventArgs e)


{
Form2 f = new Form2();
f.Show();
}

private void form3ToolStripMenuItem_Click(object sender, EventArgs e)


{
Form3 f = new Form3();
f.Show();
}

20) ContextMenuStrip
It is also a menu related control, similar to MenuStrip. But the context
menu would be displayed, when the user right
clicks on a control or a form, at run time. This is
also a collection of menu items. The context
menu is also called as ―Shortcut menu‖. The ―ContextMenuStrip‖ is an
invisible control.
API: System.Windows.Forms.ContextMenuStrip
Naming Convension: conMnuxxxxxx

Properties of ContextMenuStrip
Property Description
Name, BackColor, Font, Enabled, Size, Location, BackgroundImage, BackgroundImageLayout,
ContextMenuStrip

Events of ContextMenuStrip
Event Description
ItemClicked, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Application 111: Demo on ContextMenuStrip

Design the following two context menus in Form1.

.NET 4.0 and Visual Studio 2010 Page 315 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

.NET 4.0 and Visual Studio 2010 Page 316 of 548


Design
contextMenuStrip1:
Name: conMnuForm
displayIconToolStripMenuItem:
Checked: True
showInTaskBarToolStripMenuItem:
Checked: True
contextMenuStrip2:
Name: conMnuTextBox
Form1:
ContextMenuStrip: contextMenuStrip
Text: conMnuForm
textBox1:
Name: txtMyText
ContextMenuStrip: conMnuTextBox

private void displayIconToolStripMenuItem_Click(object sender, EventArgs e)


{
if (displayIconToolStripMenuItem.Checked == true)
{
displayIconToolStripMenuItem.Checked = false;
this.ShowIcon = false;
}
else
{
displayIconToolStripMenuItem.Checked = true;
this.ShowIcon = true;
}
}

private void redToolStripMenuItem_Click(object sender, EventArgs e)


{
this.BackColor = Color.Red;
redToolStripMenuItem.Checked = true;
greenToolStripMenuItem.Checked = false;
blueToolStripMenuItem.Checked = false;
}

private void greenToolStripMenuItem_Click(object sender, EventArgs e)


{
this.BackColor = Color.Green;
redToolStripMenuItem.Checked = false;
greenToolStripMenuItem.Checked = true;
blueToolStripMenuItem.Checked = false;
}

.NET 4.0 and Visual Studio 2010 Page 317of 548


private void blueToolStripMenuItem_Click(object sender, EventArgs e)
{
this.BackColor = Color.Blue;
redToolStripMenuItem.Checked = false;
greenToolStripMenuItem.Checked = false;
blueToolStripMenuItem.Checked = true;
}

private void showInTaskBarToolStripMenuItem_Click(object sender, EventArgs e)


{
if (showInTaskBarToolStripMenuItem.Checked == true)
{
showInTaskBarToolStripMenuItem.Checked = false;
this.ShowInTaskbar = false;
}
else
{
showInTaskBarToolStripMenuItem.Checked = true;
this.ShowInTaskbar = true;
}
}

private void upperCaseToolStripMenuItem_Click(object sender, EventArgs e)


{
txtMyText.Text = txtMyText.Text.ToUpper();
}

private void lowerCaseToolStripMenuItem_Click(object sender, EventArgs e)


{
txtMyText.Text = txtMyText.Text.ToLower();
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)


{
txtMyText.Clear();
}

.NET 4.0 and Visual Studio 2010 Page 318of 548


Dialog Controls

 These are meant for creating dialog boxes at run time.


 A dialog box can be defined as a ―Force responsive window‖, which requires the user‘s
attention at run time. That means, without answering the dialog box, the user can‘t work
with the form.
 In order to display different types of dialog boxes, .NET offers several dialog box
controls.
1) ColorDialog
2) FontDialog
3) FolderBrowserDialog
4) OpenFileDialog
5) SaveFileDialog
6) PrintDialog

Note: All the dialog box controls are known as ―invisible controls‖.

21) ColorDialog

Displays a dialog box, for a color selection.

API: System.Windows.Forms.ColorDialog
Naming Convension: colorDlgxxxxxx

 To invoke the dialog box at run time:


colorDialog1.ShowDialog();
 Get the currently selected color in the dialog box:
colorDialog1.Color;

.NET 4.0 and Visual Studio 2010 Page 319of 548


Application 112: Demo on ColorDialog

Design
button1:
Name: btnBackColor
Text: Back Color
colorDialog1:
Name: colorDlgBackColor

private void btnBackColor_Click(object sender, EventArgs e)


{
colorDlgBackColor.ShowDialog();
this.BackColor = colorDlgBackColor.Color;
}

22) FontDialog

Displays a dialog box, for a font selection (with font name, bold, italic, regular, underline, font
size options).

API: System.Windows.Forms.FontDialog
Naming Convension: fontDlgxxxxxx

 To invoke the dialog box at run time:


fontDialog1.ShowDialog();
 Get the currently selected color in the
dialog box:
fontDialog1.Font;

.NET 4.0 and Visual Studio 2010 Page 320of 548


Application 113: Demo on FontDialog

Design
textBox1:
Name: txtMyText
button1:
Name: btnFont
Text: Font
fontDialog1:
Name: fontDialogMyText

private void btnFont_Click(object sender, EventArgs e)


{
fontDialogMyText.ShowDialog();
txtMyText.Font = fontDialogMyText.Font;
}

23) FolderBrowserDialog

Displays a dialog box, for a folder selection.

API: System.Windows.Forms.FolderBrowserDialog
Naming Convension: folderBrowserDlgxxxxxx

 To invoke the dialog box at run time:


folderBrowserDialog1.ShowDialog();
 Get the currently selected folder’s full path
in the dialog box:
folderBrowserDialog1.SelectedPath;

.NET 4.0 and Visual Studio 2010 Page 321of 548


Application 114: Demo on FolderBrowserDialog

Design
button1:
Name: btnBrowseFolder
Text: Browse Folder…
label1:
Name: lblSelectedFolder
Text: Selected Folder:
label2:
Name: lblFiles
Text: Files:
label3:
Name: lblSubFolders
Text: Sub Folders:
listBox1:
Name: lstFiles
listBox2:
Name: lstSubFolders

.NET 4.0 and Visual Studio 2010 Page 322of 548


using System.IO;

private void btnBrowseFolder_Click(object sender, EventArgs e)


{
folderBrowserDialog1.ShowDialog();
string selectedfolder = folderBrowserDialog1.SelectedPath;
lblSelectedFolder.Text = "Selected Folder: " + selectedfolder;
DirectoryInfo d = new DirectoryInfo(selectedfolder);
if (d.Exists)
{
DirectoryInfo[] subdirs = d.GetDirectories();
FileInfo[] files = d.GetFiles();
lstSubFolders.Items.Clear();
lstFiles.Items.Clear();
foreach (DirectoryInfo dobj in subdirs)
lstSubFolders.Items.Add(dobj.Name);
foreach (FileInfo fobj in files)
lstFiles.Items.Add(fobj.Name);
}
else
MessageBox.Show("The seleced folder not found.");
}

24) OpenFileDialog

Displays a dialog box, for a file selection for


opening of a file.

API: System.Windows.Forms.OpenFileDialog
Naming Convension: openFileDlgxxxxxx

 To invoke the dialog box at run time:


openFileDialog1.ShowDialog();
 Get the currently selected file path
and name:
openFileDialog1.FileName;

Application 115: Demo on OpenFileDialog

.NET 4.0 and Visual Studio 2010 Page 323of 548


Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName
button1:
Name: btnBrowse
Text: Browse...
button2:
Name: btnOpen
Text: Open
textBox2:
Name: txtContent
ReadOnly: True
MultiLine: True
WordWrap: False
ScrollBars: Both

.NET 4.0 and Visual Studio 2010 Page 324of 548


using System.IO;

private void btnOpen_Click(object sender, EventArgs e)


{
string filename = txtFileName.Text;
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filename);
string content = sr.ReadToEnd();
txtContent.Text = content;
sr.Close();
}
else
MessageBox.Show("File not found.");
}

private void btnBrowse_Click(object sender, EventArgs e)


{
openFileDialog1.Reset();
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}

25) SaveFileDialog

Displays a dialog box, for a file selection for


saving a file.

API: System.Windows.Forms.SaveFileDialog
Naming Convension: saveFileDlgxxxxxx

 To invoke the dialog box at run


time:
saveFileDialog1.ShowDialog();
 Get the currently selected file path
and name:
saveFileDialog1.FileName;

Application 116: Demo on SaveFileDialog

.NET 4.0 and Visual Studio 2010 Page 325of 548


Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName
button1:
Name: btnBrowse
Text: Browse...
button2:
Name: btnSave
Text: Save
textBox2:
Name: txtContent
MultiLine: True
WordWrap: False
ScrollBars: Both

.NET 4.0 and Visual Studio 2010 Page 326of 548


using System.IO;

private void btnBrowse_Click(object sender, EventArgs e)


{
saveFileDialog1.Reset();
saveFileDialog1.ShowDialog();
txtFileName.Text = saveFileDialog1.FileName;
}

private void btnSave_Click(object sender, EventArgs e)


{
string filename = txtFileName.Text;
if (filename != "")
{
FileInfo fobj = new FileInfo(filename);
if (!fobj.Exists)
{
StreamWriter sw = new StreamWriter(filename);
string content = txtContent.Text;
sw.Write(content);
sw.Close();
MessageBox.Show("Successfully Saved.");
}
else
MessageBox.Show("File already exists!");
}
else
MessageBox.Show("Select any file name first.");
}

26) PrintDialog
Displays a dialog box, for printing preferences selection like no. of copies, name of the printer,
paper range and paper orientation etc.

API: System.Windows.Forms.PrintDialog
Naming Convension: printDlgxxxxxx

 To invoke the dialog box at run time:


printDialog1.ShowDialog();
 Get the selected printer settings:
printDialog1.PrinterSettings;

.NET 4.0 and Visual Studio 2010 Page 327of 548


Application 117: Demo on PrintDialog

Design
label1:
Name: lblFileName
Text: Enter File Name:
textBox1:
Name: txtFileName
button1:
Name: btnBrowse
Text: Browse...
button2:
Name: btnPrint
Text: Print

using System.Drawing.Printing;
using System.IO;

private void btnBrowse_Click(object sender, EventArgs e)


{
openFileDialog1.Reset();
openFileDialog1.ShowDialog();
txtFileName.Text = openFileDialog1.FileName;
}

private void btnPrint_Click(object sender, EventArgs e)


{
string filename = txtFileName.Text;
if (filename != "")
{

.NET 4.0 and Visual Studio 2010 Page 328of 548


FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
printDialog1.Reset();
printDialog1.ShowDialog();
PrintDocument doc = new PrintDocument();
doc.PrinterSettings = printDialog1.PrinterSettings;
doc.DocumentName = filename;
doc.Print();
MessageBox.Show("Printing Started...");
}
else
MessageBox.Show("File not found.");
}
else
MessageBox.Show("Enter file name");
}

27) RichTextBox

 A rich textbox is used for development of text editor applications like word pad, edit plus
etc.
 It offers better features, when compared with the standard textbox.
 It supports built-in file interaction with ―.rtf‖ files. (rtf stands for Rich Text Format).
 One of the highlights of rich textbox is, to support different fonts and colors for part of
the text.

API: System.Windows.Forms.RichTextBox
Naming Convension: rtbxxxxxx

Run Time Properties of RichTextBox


Property Description
Text Gets or sets the text of the entire rich textbox.
SelectedText Gets or sets the currently selected text.
SelectionBackColor Represents the background color for the selected text.
SelectionColor Represents the foreground color for the selected text.
SelectionAlignment Left / Right / Center / Justify
SelectionFont Represents the font settings for the seleted text.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, Scrollbars, BorderStyle

.NET 4.0 and Visual Studio 2010 Page 329of 548


Events of RichTextBox
Event Description
TextChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Methods of RichTextBox
Property Description
Clear() Clears entire text of the control.
Cut() Cuts the selected text.
Copy() Copies the selected text.
Paste() Pastes the text from the clipboard.
SelectAll() Selects the entire text in the control.
LoadFile(―rtf file path‖) Loads the text from the specified ―.rtf‖ file.
SaveFile(―rtf file path‖) Saves the text of the control, into ―.rtf‖ file.
Undo() Undos the previous action.
Redo() Redos the previous action.

Application 118: Demo on RichTextBox

.NET 4.0 and Visual Studio 2010 Page 330of 548


bool IsFileSaved = true;

private void newToolStripMenuItem_Click(object sender, EventArgs e)


{
if (IsFileSaved == false)
{
DialogResult dr = MessageBox.Show("Do you want to save the file", "Text
Editor 1.0", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
if (this.Text == "Untitled")
{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}
else
{
rtbMyText.SaveFile(this.Text);
IsFileSaved = true;
}
rtbMyText.Clear();
this.Text = "Untitled";
IsFileSaved = true;
}
else if (dr == DialogResult.No)
{
rtbMyText.Clear();
this.Text = "Untitled";
IsFileSaved = true;
}
}
else
{
rtbMyText.Clear();
this.Text = "Untitled";
IsFileSaved = true;
}
}

private void openToolStripMenuItem_Click(object sender, EventArgs e)


{
openFileDialog1.Reset();
openFileDialog1.Filter = "Rich Text Files|*.rtf";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{

.NET 4.0 and Visual Studio 2010 Page 331of 548


rtbMyText.LoadFile(openFileDialog1.FileName);
this.Text = openFileDialog1.FileName;
IsFileSaved = true;
}
}

private void saveToolStripMenuItem_Click(object sender, EventArgs e)


{
if (this.Text == "Untitled")
{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}
else
{
rtbMyText.SaveFile(this.Text);
IsFileSaved = true;
}
}

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)


{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}

private void printToolStripMenuItem_Click(object sender, EventArgs e)


{
if (this.Text != "Untitled")
{
printDialog1.Reset();
printDocument1.DocumentName = this.Text;
printDialog1.Document = printDocument1;
if (printDialog1.ShowDialog() == DialogResult.OK)
{
printDocument1.PrinterSettings = printDialog1.PrinterSettings;
printDocument1.Print();
MessageBox.Show("Printing started successfully!");
}

.NET 4.0 and Visual Studio 2010 Page 332of 548


}
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)


{
Application.Exit();
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Undo();
}

private void redoToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Redo();
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Cut();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Paste();
}

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.SelectAll();
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.SelectedText = "";
}

private void fontToolStripMenuItem_Click(object sender, EventArgs e)


{
fontDialog1.ShowDialog();
rtbMyText.SelectionFont = fontDialog1.Font;
}

private void backgroudColorToolStripMenuItem_Click(object sender, EventArgs e)


{

.NET 4.0 and Visual Studio 2010 Page 333of 548


colorDialog1.ShowDialog();
rtbMyText.SelectionBackColor = colorDialog1.Color;
}

private void foregroundColorToolStripMenuItem_Click(object sender, EventArgs e)


{
colorDialog1.ShowDialog();
rtbMyText.SelectionColor = colorDialog1.Color;
}

private void rtbMyText_TextChanged(object sender, EventArgs e)


{
IsFileSaved = false;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)


{
if (IsFileSaved == false)
{
DialogResult dr = MessageBox.Show("Do you want to save the file", "Text
Editor 1.0", MessageBoxButtons.YesNo);
if (dr == DialogResult.Yes)
{
if (this.Text == "Untitled")
{
saveFileDialog1.Reset();
saveFileDialog1.Filter = "Rich Text Files|*.rtf";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbMyText.SaveFile(saveFileDialog1.FileName);
this.Text = saveFileDialog1.FileName;
IsFileSaved = true;
}
}
else
{
rtbMyText.SaveFile(this.Text);
IsFileSaved = true;
}
}
}
}

.NET 4.0 and Visual Studio 2010 Page 334of 548


28) NotifyIcon

Creates an icon at the system‘s notification area (on the windows task bar).

API: System.Windows.Forms.NotifyIcon
Naming Convension: notifyxxxxxx

 Set the “Icon” Property:


 Display balloon tip message:
notifyIcon1.ShowBalloonTip(time out, ―title‖, ―message‖, ToolTipIcon.type);

Application 119: Demo on NotifyIcon

Design
notifyIcon1:
Name: notifyIcon1
Text: My Application
Icon: laptop.ico

private void Form1_Load(object sender, EventArgs e)


{
notifyIcon1.ShowBalloonTip(5000, "My Application", "This is a sample message",
ToolTipIcon.Info);
}

.NET 4.0 and Visual Studio 2010 Page 335of 548


29) TabControl

Displays multiple tab pages. Each tab page contains other


controls. Finally a tab page is a container for the other controls; A
tab control is a container of multiple tab pages.

API: System.Windows.Forms.TabControl
Naming Convension: tbCtrlxxxxxx

Properties of TabControl
Property Description
TabPages Contains the list of tab pages.
Alignment Top, Bottom, Left, Right
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BackgroundImage,
BackgroundImageLayout

Events of TabControl
Event Description
SelectedIndexChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter,
Leave

Application 120: Demo on TabControl

Design the form with the following 3 tabs.

.NET 4.0 and Visual Studio 2010 Page 336of 548


Design
tabPage1:
Text: Enter Numbers

tabPage2:
Text: Choose Action

tabPage3:
Text: Get Result

label1:
Name: lblFirstValue
Text: Enter First Value:

label2:
Name: lblSecondValue
Text: Enter Second Value:

textBox1:
Name: txtFirstValue

textBox2:
Name: txtSecondValue

button1:
Name: btnAdd
Text: +

button2:
Name: btnMultiply
Text: *

label3:
Name: lblResult
Text: Result:

textBox3:
Name: txtResult
ReadOnly: True

private void btnAdd_Click(object sender, EventArgs e)


{
int n1, n2, n3;
n1 = Convert.ToInt32(txtFirstValue.Text);
n2 = Convert.ToInt32(txtSecondValue.Text);
n3 = n1 + n2;
txtResult.Text = Convert.ToString(n3);
}

.NET 4.0 and Visual Studio 2010 Page 337of 548


private void btnMultiply_Click(object sender, EventArgs e)
{
int n1, n2, n3;
n1 = Convert.ToInt32(txtFirstValue.Text);
n2 = Convert.ToInt32(txtSecondValue.Text);
n3 = n1 * n2;
txtResult.Text = Convert.ToString(n3);
}

30) TreeView

Displays the items in a tree format. The items of TreeView control,


are called as ―Nodes‖. The nodes can be expanded or collapsed at
run time.

API: System.Windows.Forms.TreeView
Naming Convension: treexxxxxx

Properties of TreeView
Property Description
Nodes Contains the list of nodes.
ShowLines Displays / hides the lines in the tree view.
ShowPlusMinus Enables / disables the plus and minus symbols.
Name, BackColor, ForeColor, Enabled, Visible, Size, Location, ContextMenuStrip, BorderStyle

Events of TreeView
Event Description
AfterSelect, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Enter, Leave

Run Time Properties of TreeView


Property Description
SelectedNode Represents the currently selected node in the tree view
SelectedNode.Text Gets the text of the currently selected node.
SelectedNode.FullPath Gets the full path of the currently selected node.
Nodes.Count Gets the count of all the nodes in the tree view.

.NET 4.0 and Visual Studio 2010 Page 338of 548


Application 121: Demo on TreeView

Design
treeView1:
Name: treeMyTree
Nodes: (as shown right side)

button1:
Name: btnExpandAll
Text: Expand All

button2:
Name: btnCollapseAll
Text: Collapse All

label1:
Name: lblSelectedNode
Text: Selected Node:

label2:
Name: lblSelectedNodePath
Text: Selected Node Path:

private void treeMyTree_AfterSelect(object sender, TreeViewEventArgs e)


{
lblSelectedNode.Text = treeMyTree.SelectedNode.Text;
lblSelectedNodePath.Text = treeMyTree.SelectedNode.FullPath;
}

.NET 4.0 and Visual Studio 2010 Page 339of 548


private void btnExpandAll_Click(object sender, EventArgs e)
{
treeMyTree.ExpandAll();
}

private void btnCollapseAll_Click(object sender, EventArgs e)


{
treeMyTree.CollapseAll();
}

MDI Applications
The windows applications are of two types.
1) SDI Applications (Single Document Interface)
2) MDI Applications (Multiple Document Interface)

.NET 4.0 and Visual Studio 2010 Page 340of 548


The SDI and MDI applications contain multiple forms. But in SDI applications, each
form will be executed as individual form; whereas in MDI applications, one form acts as Parent
Form, and the remaining forms act as Child Forms.

You can observe the visibility of MDI applications in the picture.

Features of MDI Applications:

1) All the child forms are contained by the parent form, so that the parent form is also
called as ―Container form‖.
2) Among several child forms, only one form acts as ―active child form‖.
3) Generally the parent form contains no UI design, it contains a menu.
4) Any child form can‘t be moved outside of its parent form.
5) In VB 6.0, only one form can be implemented as parent form in a project. But in C#.NET
and VB.NET, you can define multiple parent forms within the same project.
6) In VB 6.0, the parent form can‘t contain any type of controls. But in C#.NET and VB.NET,
you can drag any controls.
7) The child form icon is not displayed in the windows taskbar.
8) If the parent form is moved, all the child forms will be moved.
9) Whenever the parent form is minimized, all the child forms will be minimized.
10) Whenever the parent form is maximized, all the child forms will be restored.
11) Whenever the child form is minimized, an icon will be created at the bottom area of the
parent form.
12) Whenever the child form is maximized, the text of the parent form and child form will be
concatenated.
13) Whenever you close the parent form, all the child forms will be closed automatically.
14) The child form is able to access the reference of its parent form.
15) The parent form is able to access the references of its child forms.

Implementation of MDI Applications in C#:


1) Convert the Form as Parent Form.
 To convert, set that form‘s property ―IsMDIContainer = True‖.

.NET 4.0 and Visual Studio 2010 Page 341of 548


2) Invoke the child form at run time from the parent form.
 Use the following code.
ChildFormClassName obj = new ChildFormClassName();
obj.MdiParent = this;
obj.Show();

Application 122: Demo on MDI Applications

Design
Form1:
IsMdiContainer: True

Form1.cs

private void Form1_Load(object sender, EventArgs e)


{
Form2 f = new Form2();
f.MdiParent = this;
f.Show();
}

.NET 4.0 and Visual Studio 2010 Page 342of 548


Application 123: Demo on MDI Applications (with Menu)

.NET 4.0 and Visual Studio 2010 Page 343of 548


Form1.cs

private void form2ToolStripMenuItem_Click(object sender, EventArgs e)


{
Form2 f = new Form2();
f.MdiParent = this;
f.Show();
}

private void form3ToolStripMenuItem_Click(object sender, EventArgs e)


{
Form3 f = new Form3();
f.MdiParent = this;
f.Show();
}

private void form4ToolStripMenuItem_Click(object sender, EventArgs e)


{
Form4 f = new Form4();
f.MdiParent = this;
f.Show();
}

private void closeToolStripMenuItem_Click(object sender, EventArgs e)


{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.Close();
}
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)


{
this.Close();
}

private void pinkToolStripMenuItem_Click(object sender, EventArgs e)


{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.BackColor = Color.Pink;
}
}

private void cyanToolStripMenuItem_Click(object sender, EventArgs e)


{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.BackColor = Color.Cyan;
}
}

.NET 4.0 and Visual Studio 2010 Page 344of 548


private void orangeToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.ActiveMdiChild != null)
{
this.ActiveMdiChild.BackColor = Color.Orange;
}
}

The “MessageBox” class


 This is to generate the message boxes at run time, which displays a messge to the user.

 Library: System.Windows.Forms.MessageBox

 Syntax:

MessageBox.Show(“message”); MessageBox.Show(“message”,

title”); MessageBox.Show(“message”, “title”,

MessageBoxButtons.xxxxxx);

Possible MessageBoxButton Models:

1) MessageBoxButtons.OK

2) MessageBoxButtons.OKCancel

3) MessageBoxButtons.YesNo

4) MessageBoxButtons.YesNoCancel

5) MessageBoxButtons.RetryCancel

6) MessageBoxButtons.AbortRetryIgnore

Ex: MessageBox.Show(“Do you want to save the file?”, “My App 1.0”,
MessageBoxButtons.YesNo);

.NET 4.0 and Visual Studio 2010 Page 345of 548


Adding Controls Programmatically
 Usually, the controls are designed in the form, at design time.

 Sometimes, you may need to add the controls programmatically at run time.

 To generate the controls at run time, follow the below steps:

 Create the control objectL

 ControlClassname obj = new ControlClassname();

 Assign the required properties (like name, text etc.):

 obj.property = value;

 Add the controls to the container:

 containername.Add(value);

Application 124: Demo on Adding Controls at run Time

Design
button1:
Text: Add Exit Button

.NET 4.0 and Visual Studio 2010 Page 346of 548


private void button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Exit";
btn.Location = new Point(130, 130);
btn.Click += new EventHandler(Exit_Click);
this.Controls.Add(btn);
}

private void Exit_Click(object sender, EventArgs e)


{
Application.Exit();
}

Output:

.NET 4.0 and Visual Studio 2010 Page 347of 548


Application 125: Demo on Adding Controls at run Time

Design
button1:
Name: btnShowNumbers
Text: Show Numbers
textBox1:
ReadOnly: True
TextAlign: Right

.NET 4.0 and Visual Studio 2010 Page 348of 548


private void btnShowNumbers_Click(object sender, EventArgs e)
{
FlowLayoutPanel flp = new FlowLayoutPanel();
flp.Size = new Size(180, 150);
flp.Location = new Point(100, 140);
flp.BackColor = Color.Azure;
this.Controls.Add(flp);

for (int i = 0; i <= 9; i++)


{
Button btn = new Button();
btn.Text = i.ToString();
btn.Size = new Size(50, 30);
btn.BackColor = Color.Cornsilk;
btn.Click += new EventHandler(Number_Click);
flp.Controls.Add(btn);
}
}

private void Number_Click(object sender, EventArgs e)


{
Button btn = (Button)sender;
textBox1.Text += btn.Text;
}

Output:

.NET 4.0 and Visual Studio 2010 Page 349of 548


User Controls
 A user control is nothing but, user defined control.
 That means you can create our own control, and you can use it in any form, wherever
required.
 The user control may contain some user interface with controls like buttons, textboxes
etc.
 So finally, you need to design the user interface only once in the ―User Control‖, and you
can use it any no. of times, in any form.
 Advantage: Avoids repetition of design and code.
 Generally, you can use it for designing the common header for all the forms in the
project (as given in the below example).

User Control (vs) Form


Sl. No User Control Form
1 It‘s a container for other controls It‘s also a container for other controls.
2 It can‘t run individually. It can run individually.
It inherits a pre-defined class called It inherits a pre-defined class called
3
―System.Windows.Forms.UserControl‖. ―System.Windows.Forms.Form‖.
4 It is meant for re-usability. It is meant for direct execution.

Implementation of User Controls

 Create the User Control:


 Click on ―Project‖ menu – ―Add User Control‖.
 Enter the name of the new user control.
 Click on ―Add‖.

 Design and Develop the User Control:


 Design the UI in the user control, by dragging the controls from the toolbox.
 Write the code in ―Code window‖. (User control also supports event handlers
similar to forms).

.NET 4.0 and Visual Studio 2010 Page 350of 548


 Invoke the User Control:
 Open the required form and build the project.
 Then the user control name will be displayed in the toolbox automatically.
 To invoke the user control on a form, just drag it from the toolbox into the form
designer.
 Then the control object will be created in the form.

Application 126: Demo on User Controls

 Create the Windows Application Project.


 Click ―Project‖ menu – ―Add User Control‖.
 Enter the name as ―Title‖.
 Click on ―Add‖.
 Then design the user control as follows:

.NET 4.0 and Visual Studio 2010 Page 351of 548


 Set the properties of ―Timer1‖
 Enabled: True
 Interval: 1000
 Double click on the user control and write the code.

private void Title_Load(object sender, EventArgs e)


{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}

 Double click on the user control and write the code.

private void timer1_Tick(object sender, EventArgs e)


{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}

 Come back to the ―Form1‖ and ―Build‖ the project.


 Then the user control name ―Title‖ will be added to the toolbox, at the top.

.NET 4.0 and Visual Studio 2010 Page 352of 548


 Then drag and drop it from the toolbox into the form. Then it‘s ready.
 In the similar way, you can drag and drop the controls into any no. of forms, within the
same project.
 Note: The current user control is called as ―Local User Control‖. So that it can be used
within the same project only. You can‘t use it in other windows application projects. But
if you want to utilize the same user control in other windows application projects also,
then you have to create this user control in ―Windows Forms Control Library‖.

Windows Forms Control Library


 It‘s a collection of global user controls.
 If a user control is created in a windows application project, it can be used or accessed
within the same project only. If the user control is created in the ―Windows Forms
Control Library‖, that user control is accessible in any other windows application projects.
 The user controls created in the ―windows forms control library‖, are called as ―Global
user controls‖.
 When we compile the ―windows form controls library‖ project, it will generate a ―.dll‖ file
in the ―bin‖ folder of the project.
 Later, that dll file can be linked with any no. of windows application projects, and the
user control can be utilized in those forms.

Implementation Steps of “Windows Forms Control Library”

 Create the “Windows Forms Control Library”:


 In Visual Studio, click on ―File‖ – ―New‖ – ―Project‖.
 In the ―New Project‖ dialog box, select the project template as ―Windows Forms
Control Library‖.
 Enter the name and location of the project.
 Click on OK.
 Then the new control library project will be created along a user control called
―UserControl1‖.

.NET 4.0 and Visual Studio 2010 Page 353of 548


 Note: To add additional user controls within the same project, just click on
―Project‖ menu and choose ―Add User Control‖.

 Design and Develop the User Control:


 Design the UI in the user control, by dragging the controls from the toolbox.
 Write the code in ―Code window‖. (User control also supports event handlers
similar to forms).
 Build the project.
 Then the ―.dll‖ file will be created in the ―bin\Debug‖ folder of the ―windows
forms control library‖ project.

 Invoke the User Control from other Windows Application Project:


 Create a new windows application project.
 Open the toolbox.
 Right click anywhere on the toolbox and select ―Add tab‖.
 Type any name for the tab. Ex: My Controls.
 Right click on ―My Controls‖ and select ―Choose Items‖.
 Select the ―dll‖ file from ―bin\Debug‖ folder of windows forms control library
project..
 Click on OK.
 Then the user control name will be displayed in the toolbox automatically.
 To invoke the user control on a form, just drag it from the toolbox into the form
designer.
 Then the control object will be created in the form.

Application 127: Demo on WindowsFormsControlLibrary

Windows Forms Control Library Project Name: GlobalControlsLibrary


Windows Application Project Name: GlobalControlsTest

.NET 4.0 and Visual Studio 2010 Page 354of 548


I) “Windows Control Library” Project Development:
 Open Visual Studio.
 File – New – Project.
 Select ―Visual C#‖ – ―Windows‖ – ―Windows Forms Control Library‖.
 Enter the name as ―GlobalControlsLibrary‖.
 Select any location. Ex: D:\C#Apps
 Click on OK.
 Then it will create the windows forms control library project and it creates a user control
named ―UserControl1‖.
 Then rename it as ―Title‖ using Solution Explorer.
 Then design the user control as follows:

 Set the properties of ―Timer1‖


 Enabled: True
 Interval: 1000

.NET 4.0 and Visual Studio 2010 Page 355of 548


 Double click on the user control and write the code.

private void Title_Load(object sender, EventArgs e)


{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}

 Double click on the user control and write the code.

private void timer1_Tick(object sender, EventArgs e)


{
label3.Text = DateTime.Now.ToLongDateString();
label4.Text = DateTime.Now.ToLongTimeString();
}

 The build the project. ―Build‖ menu – ―Build Solution‖.


 Then in the ―dll‖ file will be generated in the ―bin\Debug‖ folder of the project.
Ex: D:\C#Apps\GlobalControlsLibrary\GlobalControlsLibrary\bin\Debug\GlobalControlsLibrary.dll

II) Client Application Development:

 Create a new windows application project.


Name: GlobalControlsTest
 Open the toolbox.
 Right click anywhere on the toolbox and select ―Add tab‖.
 Type any name for the tab. Ex: My Controls.
 Right click on ―My Controls‖ and select ―Choose Items‖.
 Select the ―dll‖ file from ―bin\Debug‖ folder of windows forms control library project.
Ex: D:\C#Apps\GlobalControlsLibrary\GlobalControlsLibrary\bin\Debug\GlobalControlsLibrary.dll
 Click on OK.
 Then the user control name will be displayed in the toolbox automatically.
 Then drag and drop it from the toolbox into the form. Then it‘s ready.

.NET 4.0 and Visual Studio 2010 Page 356of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

.NET 4.0 and Visual Studio 2010 Page 357 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

.NET 4.0 and Visual Studio 2010 Page 358 of 548


GDI+ graphics
 GDI stands for Graphic Device Interface.
 This concept is used to create user defined graphical elements in the form like lines,
rectangles, circles, triangles etc.
 This is similar to ―graphics‖ concept in C.

Library: System.Drawings.Graphics
This class object is able to write any graphics on its container. That means every graphic object
requires a container. The container may be either form or panel.

Note: The GDI graphics can be implemented in “Paint()” method.

Implementation:

private void Form1_Paint(object sender, PaintEventArgs e)


{
Graphics g = this.CreateGraphics();
}

In the above code, the ―CreateGraphics()‖ method creates a graphics object, that is able to write
the GDI graphics in the container (form).

Drawing the GDI Graphics

1) Drawing Lines
 g.DrawLine(Pens.xxxx, x1, y1, x2, y2);

.NET 4.0 and Visual Studio 2010 Page 359 of 548


2) Drawing Rectangles
 g.DrawRectangle(Pens.xxxx, x1, y1, width,
height);

3) Drawing Circles / Elipses


 g.DrawEllipse(Pens.xxxx, x1, y1, width, height);

4) Drawing Polygons
 Point[] p = new Point[count];
p[0] = new Point(x,y);
p[1] = new Point(x,y);
p[2] = new Point(x,y);
……………………..
g.DrawPolygon(Pens.xxx, p);

5) Drawing Curves
 Point[] p = new Point[count];
p[0] = new Point(x,y);
p[1] = new Point(x,y);
p[2] = new Point(x,y);
……………………..
g.DrawCurve(Pens.xxx, p);

.NET 4.0 and Visual Studio 2010 Page 360 of 548


Application 128: Demo on GDI (Drawing Lines)

private void Form1_Paint(object sender, PaintEventArgs e)


{
Graphics g = this.CreateGraphics();
g.DrawLine(Pens.RoyalBlue, 100, 100, 300, 100);
g.DrawLine(Pens.Red, 150, 150, 300, 150);
g.DrawLine(Pens.SandyBrown, 200, 200, 300, 200);
g.DrawLine(Pens.SlateGray, 250, 250, 300, 250);
}

Application 129: Demo on GDI (Drawing Lines)

.NET 4.0 and Visual Studio 2010 Page 361 of 548


private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = this.CreateGraphics();
int h = this.Size.Height - 35;
int w = this.Size.Width - 9;
g.DrawLine(Pens.Coral, 0, 0, w, h);
g.DrawLine(Pens.Coral, w, 0, 0, h);
}

Application 130: Demo on GDI (Drawing Lines)

private void Form1_Paint(object sender, PaintEventArgs e)


{
Graphics g = this.CreateGraphics();
int w = this.Size.Width - 9;
int h = this.Size.Height - 35;
for (int i = 0; i <= h; i += 4)
g.DrawLine(Pens.DarkGreen, 0, i, w, i);
for (int i = 0; i <= w; i += 4)
g.DrawLine(Pens.Red, i, 0, i, h);
}

.NET 4.0 and Visual Studio 2010 Page 362 of 548


Application 131: Demo on GDI (Drawing Lines)

private void Form1_MouseMove(object sender, MouseEventArgs e)


{
Graphics g = this.CreateGraphics();
g.DrawLine(Pens.Orange, 0, 0, e.X, e.Y);
}

Application 132: Demo on GDI (Drawing Lines, Rectangles, Circles, Triangles, Curves)

.NET 4.0 and Visual Studio 2010 Page 363 of 548


private void Form1_Paint(object sender, PaintEventArgs e)
{
this.Size = new Size(409, 435);
Graphics g = this.CreateGraphics();
//dividing lines
g.DrawLine(Pens.Green, 200, 0, 200, 400);
g.DrawLine(Pens.Green, 0, 200, 400, 200);
//rectangle
g.DrawRectangle(Pens.Red, 50, 50, 100, 100);
//circle or ellipse
g.DrawEllipse(Pens.Red, 250, 50, 100, 100);
//triangle (with polygon)
Point[] p1 = new Point[3];
p1[0] = new Point(100, 250);
p1[1] = new Point(50, 350);
p1[2] = new Point(150, 350);
g.DrawPolygon(Pens.Red, p1);
//curve
Point[] p2 = new Point[6];
p2[0] = new Point(250, 350);
p2[1] = new Point(250, 250);
p2[2] = new Point(350, 250);
p2[3] = new Point(350, 350);
p2[4] = new Point(300, 300);
p2[5] = new Point(250, 350);
g.DrawCurve(Pens.Red, p2);
}

Application 133: Demo on GDI (Drawing Circles)

.NET 4.0 and Visual Studio 2010 Page 364 of 548


private void Form1_MouseClick(object sender, MouseEventArgs e)
{
Graphics g = this.CreateGraphics();
int x = e.X;
int y = e.Y;
g.DrawEllipse(Pens.Brown, x-20, y-20, 40, 40);
}

Application 134: Demo on GDI (Drawing Filled Objects)

private void Form1_Paint(object sender, PaintEventArgs e)


{
this.Size = new Size(409, 435);
Graphics g = this.CreateGraphics();
//dividing lines
g.DrawLine(Pens.Green, 200, 0, 200, 400);
g.DrawLine(Pens.Green, 0, 200, 400, 200);
//rectangle
g.FillRectangle(Brushes.Violet, 50, 50, 100, 100);
//circle or ellipse
g.FillEllipse(Brushes.Salmon, 250, 50, 100, 100);
//triangle (with polygon)
Point[] p1 = new Point[3];

.NET 4.0 and Visual Studio 2010 Page 365 of 548


p1[0] = new Point(100, 250);
p1[1] = new Point(50, 350);
p1[2] = new Point(150, 350);
g.FillPolygon(Brushes.Chocolate, p1);
//curve
Point[] p2 = new Point[5];
p2[0] = new Point(250, 350);
p2[1] = new Point(250, 250);
p2[2] = new Point(350, 250);
p2[3] = new Point(350, 350);
p2[4] = new Point(300, 300);
g.FillClosedCurve(Brushes.LightSeaGreen, p2);
}

Application 135: Demo on GDI (Drawing Filled Objects)

private void Form1_Paint(object sender, PaintEventArgs e)


{
this.Size = new Size(509, 535); Graphics g =
this.CreateGraphics(); g.FillRectangle(Brushes.Pink, 0, 0, 100,
500); g.FillRectangle(Brushes.Purple, 101, 0, 100, 500);
g.FillRectangle(Brushes.LightGreen, 201, 0, 100, 500);
g.FillRectangle(Brushes.Linen, 301, 0, 100, 500);
g.FillRectangle(Brushes.MediumTurquoise, 401, 0, 100, 500);
}

.NET 4.0 and Visual Studio 2010 Page 366 of 548


SQL Server 2005 Basics
1. Open SQL Server:
 Click on ―Start‖ – ―Programs‖ – ―Microsoft SQL Server 2005‖ – ―SQL Server
Management Studio‖.
 It displays ―Connect to Server‖ dialog box.

 Enter the following values:


1. Server type: Database Engine
2. Server name: Name of the system (You can see the computer name in
he ―My Computer‖ properties)
3. Authentication: SQL Server Authentication
 Login: sa
 Password: xxxx (The password can be given at the time of SQL
Server software installation) Ex: 123
(or)
Authentication: Windows Authentication
 After successful login to the server, it displays ―SQL Server Management Studio‖
window.

.NET 4.0 and Visual Studio 2010 Page 367 of 548


Edited with the trial version of
Foxit Advanced PDF Editor
To remove this notice, visit:
www.foxitsoftware.com/shopping

.NET 4.0 and Visual Studio 2010 Page 368 of 548


2. Object Explorer:
 In SQL Server Management Studio, the
―Object Explorer‖ displays the
information about the databases, tables,
stored procedures and functions.
 First of all, expand the option
―Databases‖; then it displays list of
databases that currently exist on this
system.
 If you expand any database (For ex:
sample), it displays some folders like
―Tables‖, ―Views‖, ―Programmability‖
etc.
 When you expand the ―Tables‖ folder, it
displays the list of tables that exist the
selected database.
 If you want to see the table structure,
right click on that table and choose
―Modify‖ option. There you can make
any changes in the table design
(structure).
 If you want to open the table data, right
click on that table and choose ―Open Table‖. Then the table rows will be opened.
Here also you can make changes in the table data, and also you can add new
rows here.

.NET 4.0 and Visual Studio 2010 Page 369 of 548


3. Creating a new Database:
 A database is a collection of tables.
 To create a new database, right click on ―Databases‖ and choose ―New
Database‖.
 Then enter the new database name. Ex: mydata
 Click on OK.

.NET 4.0 and Visual Studio 2010 Page 370 of 548


4. Creating a new Table:
 Right click on ―Tables‖ option in the ―Object Explorer‖ and choose ―New Table‖.
 Enter the table structure of the new table.

 Click on ―Save‖ button to save the table. Then it asks for the table name. Enter
the desired table name.

 Close the window finally.

.NET 4.0 and Visual Studio 2010 Page 371 of 548


5. Important Data Types in SQL Server:
 varchar(width)
 datetime
 numeric(width)
 int
 float
 decimal(width,dec)
 bit
 image

6. Workingwith“Querywindow”:
 ―Query window‖ is a window, where you can enter the SQL queries and execute
them.
 Open the ―Query window‖, by clicking on ―New Query‖ window option in the
toolbar.
 Select the database from the database list, in which your query is to be
executed.
 Enter the required SQL query in the window.
 To execute, press ―F5‖ (or) click on ―Execute‖ button in the toolbar.

.NET 4.0 and Visual Studio 2010 Page 372 of 548


 Then the SQL statement will be executed.

7. IMP SQL Statements:


 DDL:
1. CREATE
 create table tablename(column1 datatype(width), column2
datatype(width), …);

2. DROP
 drop table tablename;

3. ALTER
 alter table tablename add columnname datatype(width);
 alter table tablename drop column columnname;

.NET 4.0 and Visual Studio 2010 Page 373 of 548


 alter table tablename alter column columnname
datatype(width);

 DML:
1. SELECT
 select * from tablename;
 select column1, column2, .. from tablename;
 select * from tablename where condition;
 select column1, column2, … from tablename where condition;

2. INSERT
 insert into tablename values(value1, value2,…);

3. DELETE
 delete from tablename;
 delete from tablename where condition;

4. UPDATE
 update tablename set column1=value1, column2=value2;
 update tablename set column1=value1, column2=value2 where
condition;

Some exercise on SQL:

use master
drop database test
GO

create database test


GO

use test
GO

create table Products


(ProductID int primary key,
ProductName varchar(40),
Price decimal(18,2))

.NET 4.0 and Visual Studio 2010 Page 374 of 548


insert into products values(101,'Monitors',7890)
insert into products values(102,'Keyboards',450)
insert into products values(103,'Mouses',590)
insert into products values(104,'Processors',6202)
insert into products values(105,'RAM',2829)

select * from products

select ProductID,ProductName from Products

select Price*10/100 Tax from Products

select * from Products where Productid=104

select * from Products order by price desc

select * from Products where price between 2000 and 8000

select * from Products where price not between 2000 and 8000

select * from Products where price like '%0.00'

select * from Products where price like ' _.00'

update products set price=price+1000

select * from products

delete from products where price<1500

select * from products

.NET 4.0 and Visual Studio 2010 Page 375 of 548


8. T-SQL (Transaction SQL):
 Procedures:
create procedure procedurename(@variable datatype(width),…)
as begin
declare @variable datatype(width)
…….
…….
end

 Functions:
create function functionname(@variable datatype(width),…)
returns returndatatype
as begin
declare @variable datatype(width)
…….
…….
return returnvalue
end

Note: The procedure can’t return any value; and a function should return any value. For every
variable in T-SQL, we have to prefix “@” symbol without fail.

.NET 4.0 and Visual Studio 2010 Page 376 of 548


Some exercise on T-SQL:

Procedure:

create procedure ShowSquare(@a int)


as begin
declare @sq int
set @sq = @a * @a
print @sq
end

GO
execute ShowSquare 5

Function:

create function GetCube(@a int) returns int


as begin
declare @cb int
set @cb = @a * @a * @a
return @cb
end

GO

select dbo.GetCube(5)

.NET 4.0 and Visual Studio 2010 Page 377 of 548


ADO.NET
(ActiveX Data Objects.NET)

 ADO.NET is known as ―Database Technology‖, which is used to connect with the


databases. That means some objects will work for interacting with the databases.
 Basically, why we require database connection is: the frontend application itself, can‘t
store any data permanently. So that we require a storage mechanism. That storage
mechanism is nothing but our databases.
 It can be used for database connections and offers to perform database manipulations
like inserting data to the tables, deleting un-necessary data, retrieving the required data
from the tables etc.
 It can be used in any type of applications like console applications, windows forms
applications, web sites, web services, WCF services etc.
 It can be used in any .NET language like C#.NET, VB.NET, VC++.NET etc.
 It was developed based on its previous version called ―ADO‖.
 It offers much efficient features to easily handle with the database tables, especially
when you are dealing with multiple tables.

What type of databases we can connect using ADO.NET:


 File Databases:
dBASE, FoxPro, MS Access, MS Excel etc.
 Server Databases:
SQL Server, Oracle, My SQL etc.

.NET 4.0 and Visual Studio 2010 Page 378 of 548


What we can do using ADO.NET:

 Insert some data into the database table.


 Delete some data from the database table.
 Update the data of a table.
 Retrieve some data from the table.
 Execute a stored procedure / function, i.e. already created at backend using PL/SQL.

ADO.NET Database Connection Architecture

Driver .NET Application


db

Note: Here, the driver acts as mediator between the frontend application and backend
databases. The driver can also be called as ―Provider‖. This provider may be released by Backend
Company or Frontend Company.

For various databases, we have respective providers.


Database Provider Released by
SQL Server sqloledb.1 Microsoft Corp.
oraoledb.oracle.1 Oracle Corp.
Oracle
msdaora.1 Microsoft Corp.
MS Access / MS Excel / FoxPro /
microsoft.jet.oledb.4.0 Microsoft Corp.
dBASE
MS Access 2007 / 2010 microsoft.ace.oledb.12.0 Microsoft Corp.

.NET 4.0 and Visual Studio 2010 Page 379 of 548


Understanding the Connection String:
 The connection string provides the details about the connection string. That means, if
you want to connect with the database, you have to specify some details about the
connection like:
1. Server
2. User ID
3. Password
4. Provider
 Server: Specify the name of the server system, which you want to connect. If you want
to connect with other server system on the network, you specify the name of that
system. Ex: myserver. If you want to connect with the same system, mention the server
name as ―localhost‖. The server name can also be called as ―data source‖.
 User ID: Specify the user name for logging-in with the database.
 Password: Specify the password for logging-in with the database.
 Provider: Specify the name of the driver / provider, which you want to use with the
connection. You can see the available provider names, in the above table.

Syntax of Connection String:


―provider=xxxxx; user id=xxxxx; password=xxxx; data source=xxxxx‖

Note: Just for separation of the individual values, we are using ―;‖.

ADO.NET Library
 To perform above mentioned database operations, ADO.NET technology offers some pre-
defined classes, organized in the form of namespaces.
 Library: System.Data

.NET 4.0 and Visual Studio 2010 Page 380 of 548


Data

DataSet

DataTable

DataRow

DataColumn

SqlClient OleDb

SqlConnection OleDbConnection

SqlCommand OleDbCommand

SqlDataReader OleDbDataReader

SqlDataAdapter OleDbDataAdapter

SqlParameter OleDbParameter

ADO.NET NameSpaces:

1) System.Data
Contains necessary classes and namespaces to manipulate the databases.
2) System.Data.SqlClient
Contains necessary classes, used to interact with the SQL Server database.
3) System.Data.OleDb
Contains necessary classes, used to interact with any other databases. Of course,
the OleDb namespace also supports to connect with SQL server database, but
we won‘t use it for SQL Server, because ―SqlClient‖ namespace is especially
available for that.

.NET 4.0 and Visual Studio 2010 Page 381 of 548


ADO.NET Classes:

1) Connection:
Maintains the connection with the database.
2) Command:
Executes a query statement (select statement), non-query statement (insert
statement / delete statement / update statement) or a stored procedure /
function at backend.
3) DataReader:
It acts as a buffer, which holds the data, after execution of a query statement at
backend.
4) DataAdapter:
Executes a query statement at backend.
5) Parameter:
Sends a parameter (argument) value to a backend stored procedure / function.
6) DataSet:
Acts as a buffer, which holds multiple tables at-a-time.
7) DataTable:
Acts as a buffer, which holds a single table (collection of rows and columns).
8) DataRow:
Acts as a buffer, which holds a single row.
9) DataColumn:
Acts as a buffer, which holds a single column.

Note: All of above are the classes; you need to create object(s) for those classes.

.NET 4.0 and Visual Studio 2010 Page 382 of 548


Connecting the Database

 Library: SqlConnection / OleDbConnection

Connection
 ConnectionString
 Open()
 Close()

 ConnectionString: This property contains the connection string, used for the
connection.
 Open(): This method opens the database connection.
 Close(): This method disconnects the database connection.

Connecting with SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
Note: The ―initial catalog‖ specifies the name of the SQL Server database, in which
your table exists.
 Open the connection:
cn.Open();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 383 of 548


Connecting with Oracle / MS Access / Fox Pro:
 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Prepare the Connection string:
cn.ConnectionString = ―provider=oraoledb.oracle.1; data

Oracle source=<name of the server>; user id=<user name>;


password=<password>‖;
MS
cn.ConnectionString = ―provider=microsoft.jet.oledb.4.0;data
Access /
dBASE / source=<path of the database file>‖;
FoxPro

 Open the connection:


cn.Open();
 Close the connection:
cn.Close();

Application 136: Demo on ADO.NET with SQL Server Database

 Create a new Windows Forms Application. It automatically creates ―Form1‖.


 Set the following properties of ―Form1‖:
1. WindowState: Maximized
2. IsMdiContainer: True
3. Text: ADO.NET Demo
 Drag and drop ―MenuStrip‖ control into the form.
 Design the MenuStrip as shown in this screen:

.NET 4.0 and Visual Studio 2010 Page 384 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖.
 Enter the form name as ―DatabaseConnectionDemo‖.
 Click on ―Add‖.
 Double click on ―Database Connection Demo‖ menu item and write the code:

private void databaseConnectionDemoToolStripMenuItem_Click(object sender,


EventArgs e)
{
DatabaseConnectionDemo f = new DatabaseConnectionDemo();
f.MdiParent = this;
f.Show();
}

 Open the ―DatabaseConnectionDemo‖ form, from Solution Explorer and design it as


shown:

.NET 4.0 and Visual Studio 2010 Page 385 of 548


 Write the code:

.NET 4.0 and Visual Studio 2010 Page 386 of 548


using System.Data.SqlClient;
using System.Data.OleDb;

private void button1_Click(object sender, EventArgs e)


{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123";
cn.Open();
MessageBox.Show("Successfully Connected with SQL Server");
cn.Close();
}

private void button2_Click(object sender, EventArgs e)


{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=oraoledb.oracle.1;user id=scott;password=tiger";
cn.Open();
MessageBox.Show("Successfully Connected with Oracle");
cn.Close();
}

private void button3_Click(object sender, EventArgs e)


{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data
source=c:\\database1.mdb";
cn.Open();
MessageBox.Show("Successfully Connected with MS Access");
cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 387 of 548


Sending Commands to the Database
 After connecting the database, you can send the commands to the database.
 ADO.NET supports to send the following types of commands.
1. Insertion Command
2. Deletion Command
3. Updation Command
4. Select Command / Query Command
5. Stored Procedure / Function Command

1) Insertion Command:
To insert a new row into the table.
SQL statement: insert into tablename values(value1, value2,…)

2) Deletion Command:
To delete one or more rows from the table.
SQL statement: delete from tablename where condition

3) Updation Command:
To update (modify) the table data.
SQL statement: update tablename set column1=value1, column2=value2
where condition

4) Select Command:
To retrieve the data from the database table, into the frontend application.
SQL statement: select * from tablename

5) Stored Procedure / Function Command:


To call a stored procedure / function from the frontend application, that is
already created at backend.
SQL statement: No SQL statement is needed

.NET 4.0 and Visual Studio 2010 Page 388 of 548


Understanding the “Command” class:
 In order to send the commands, you need to use ―Command‖ class.
 Library: SqlCommand / OleDbCommand

Connection Command
 ConnectionString  CommandText
 Open()  Connection
 Close()  CommandType
 Parameters
 ExecuteNonQuery()
 ExecuteReader()

a) CommandText: This property contains the SQL statement (insrtion statement


/ deletion statement / updation statement / select statement)

b) Connection: This property contains the reference of the connection object,


based on which, the above given SQL statement is to be executed.

c) CommandType: This property specifies the type of the command that you want
to execute. It is of two types:
 Text: (default) This is used for any SQL statement (insertion statement /
deletion statement / updation statement / select statement)
 StoredProcedure: This is used for Stored Procedure / Function only.

d) Parameters: This property contains the list of parameters (argument values),


that are to be sent to backend, while you are calling a stored procedure /
function. It is of ―collection‖ type, so that you can add any no. of parameters.

e) ExecuteNonQuery(): This method is used to execute any SQL statement


(insertion statement / deletion statement / updation statement / select
statement) or a stored procedure / function also. In other words, this method
moves the execution flow to backend database, execute the command there and
then come back with some result. This method returns ―no. of rows affected‖,
which represents the count of the rows, which are affected by executing this

.NET 4.0 and Visual Studio 2010 Page 389 of 548


command. Suppose, after executing a delete statement, 2 rows are deleted. So it
returns the integer value ―2‖.

f) ExecuteReader(): This method is used to execute ―select‖ statement only. In


other words, it is used to retrieve some data from the database, based on the
given select statement. In other words, this method moves the execution flow to
backend database, execute the command there and then come back with some
result data. This method returns the table data, based on the given select
statement.

Implementation Code for SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―insert statement / delete statement / update statement‖;
 Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
 Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 390 of 548


Implementation Code for Oracle (or any other database):
 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―insert statement / delete statement / update statement‖;
 Assign the reference of connection object, based which the command is to be
executed:
cmd.Connection = cn;
 Execute the command and receive the no. of rows affected:
int n = cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 391 of 548


Demo:
 Open SQL Server 2005.
 Create a new database, with name as ―demo‖.
 In that database, create a table named ―Customers‖, as shown below.

 Open the previous demo application.


 Add the menu item ―Database Commands Demo‖ and design the menu as shown below:

.NET 4.0 and Visual Studio 2010 Page 392 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as ―Insertion‖.
Click on ―Add‖.
 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as ―Deletion‖. Click
on ―Add‖.
 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as ―Updation‖.
Click on ―Add‖.
 Double click on menu items one-by-one and write the following code in the ―Form1.cs‖:

Form1.cs

private void insertionToolStripMenuItem_Click(object sender, EventArgs e)


{
Insertion f = new Insertion();
f.MdiParent = this;
f.Show();
}

.NET 4.0 and Visual Studio 2010 Page 393 of 548


private void deletionToolStripMenuItem_Click(object sender, EventArgs e)
{
Deletion f = new Deletion();
f.MdiParent = this;
f.Show();
}

private void updationToolStripMenuItem_Click(object sender, EventArgs e)


{
Updation f = new Updation();
f.MdiParent = this;
f.Show();
}

 Design the ―Insertion‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 394 of 548

You might also like