Csharp Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 278

What is C#?

C# is intended to be a simple, modern, general-purpose, object-oriented programming


language. Its development team is led by Anders Hejlsberg. The most recent version is C#
4.0, which was released on April 12, 2010. C# (pronounced "see sharp") is a multiparadigm programming language encompassing imperative, declarative, functional, generic,
object-oriented (class-based), and component-oriented programming disciplines. It was
developed by Microsoft within the .NET initiative and later approved as a standard by Ecma
(ECMA-334) and ISO (ISO/IEC 23270). C# is one of the programming languages designed
for the Common Language Infrastructure.

Features of C#
Some notable distinguishing features of C# are:

There are no global variables or functions. All methods and members must be
declared within classes. Static members of public classes can substitute for global
variables and functions.

Managed memory cannot be explicitly freed instead, it is automatically garbage


collected.

Garbage collection addresses the problem of memory leaks by freeing the


programmer of responsibility for releasing memory which is no longer needed.

In addition to the try...catch construct to handle exceptions, C# has a try...finally


construct to guarantee execution of the code in the finally block.

Multiple inheritance is not supported by C#, although a class can implement any
number of interfaces.

C# and .Net Framework


Microsoft announced C# in July 2000, its unveiling was part of a much larger event the
announcement of the .NET Framework. The .NET Framework is, in essence, a new
development framework that provides a fresh application programming interface (API) to
the services and APIs of classic Windows operating systems (especially the Windows 2000
family), while bringing together a number of disparate technologies that emerged from
Microsoft during the late 1990s. Among the latter are COM+ component services, the ASP
web development framework, a commitment to XML and object-oriented design, support for
new web services protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet
Information Services.

What is CLR?

CLR (Common Language Runtime) is the most important component of .Net Framework. It
manages and executes code written in .Net Languages, CLR activates objects and perform
security checks. The CLR allows programmers to ignore many details of the specific CPU
that will execute the program. It also provides other important services, including the
following:

Memory management

Thread management

Exception handling

Garbage collection

Security Central to the .NET Framework is its runtime execution environment,


known as the Common Language

Runtime (CLR) or the .NET runtime. Code running under the control of the CLR is often
termed as managed code.

What is CTS?
In .NET Framework, the Common Type System (CTS) is a standard that specifies how Type
definitions and specific values of Types are represented in computer memory. It is intended
to allow programs written
in different programming languages to easily share information. Functions of the Common
Type System:-

CTS establishes a framework that helps enable cross-language integration, type


safety, and high performance code execution.

CTS provides an object-oriented model that supports the complete implementation of


many programming languages.

CTS also defines rules that languages must follow, which helps ensure that objects
written in different languages can interact with each other.

Languages supported by .NET can implement all or some common data types.

Type categories the common type system supports two general categories of types:

Value types:

Value types directly contain their data, and instances of value types
are either allocated on the stack or allocated inline in a structure. Value types can be built-in
(implemented by the runtime), user-defined, or enumerations.

Reference types:

Reference types store a reference to the value's memory


address, and are allocated on the heap. Reference types can be self-describing types,
pointer types, or interface types. The type of a reference type can be determined from
values of self-describing types. Self-describing types are further split into arrays and class
types. The class types are user-defined classes, boxed value types, and delegates.

What is CLS?
The Common Language Specification (CLS) is a part of the standardized specification of
the .NET Framework originally defined by Microsoft, and later standardized by the European
Computer Manufacturers Association (ECMA). A key feature of .NET Framework is that
applications written in different languages can interoperate with one another, taking
advantage of inheritance, polymorphism, exceptions and other features.
CLS provides,
set of specification to be adhered by new language writer/compiler writer for .Net
Framework to ensure interoperability. because .net supports many languages.For
example Asp.Net application written in C#.Net language. Now we can refer any other DLL
which has been written in any other language supported by .Net Frame Work.

.Net Frameworks Architecture

.Net is not an Operating System. It is a IDE. It provides some functionality for the
programmers to build their solution in the most constructive and intellegent way ever. Just
to tell you the truth, most of the codes in .Net environment resembles with the JAVA coding
as if some people coming from Java would find it as to their native language.

.NET is a Framework that loads into your operating system, which you need not to load in
the later versions of windows like Windows 2003 server or Just a new release of Windows
Vista. As it is going to be added as a component in the next generation of windows.
Now, What is the .Net all about? Well, Its a framework that supports Common Language
Runtime (CLR). As the name suggests, Common Language Runtime will be something that
will run a native code for all the programming languages provided within the Architecture.
Another feature of .net is language independence, to tell you about language Independence,
.Net is not at all efficient in that. Just Microsoft built their own version of languages like C+
+, J# (for Java), C#, VB etc that can communicate between each other. After all J#, even if
they resembles with JAVA is not purely Java.. Thus, the word may look to you somewhat
fake. Now what is the most prospective part of .NET? Now, with the growing Internet, ASP.
NET may be the most important part of .NET technology. Well, ASP. NET has a new
technology where the controls reside server side. You don't bother to use traditional client
side controls. In .NET technology as there is a provision of runtime building of machine
codes, a web server can directly compile and transmit codes to the browser during runtime.
This is , I think the most approved and widely accepted part of .NET.
NEW things of .NET? well, during the last two years , Microsoft is constantly changing the
.NET technology, that may not be good for a settled programmer. Well, first of all, in .NET
2003 Microsoft changed some features and also adds some new things. Well, new things are
good, but changing the existing in such a quick succession is not at all good from
programmers point of view. Again, in 2005, Microsoft publishes the new release of VISUAL
STUDIO.NET 8 . This is a completely new environment. It have new releases of controls, the
IDE is also different. That's not what we all wanted as a programmer. What do you say?
Now, Microsoft is also increasing its scope.. One of the most important feature that is just
now introduced is AJAX. Well, the name is what can be said as Asynchronous Java Script
with XML.

.Net Frameworks Architecture

C# DataTypes
Data Types means what type of data a variable can hold . C# is a strongly typed language,
therefore every variable and object must have a declared type. The C# type system
contains three Type categories.

Value Types

Reference Types

Pointer Types

In C# it is possible to convert a value of one type into a value of another type . The
operation of Converting a Value Type to a Reference Type is called Boxing and the reverse
operation is called Unboxing .

Ex.

int month;
int : is the data type
month: is the variable name

int

int can store signed 32 bit integer values in the range of -2,147,483,648 to +2,147,483,647
C# Runtime type : System.Int32
C# declaration : int month;
C# Initialization : month = 10;
C# default initialization value : 0

decimal
Decimal is of a 128-bit data type.The approximate range and precision for the decimal type
are -1.0 X 10-28 to 7.9 X 1028
C# Runtime type : System.Decimal
C# declaration : decimal val;
C# Initialization : val = 0.12;
C# default initialization value : 0.0M

string
Represents a string of Unicode characters. string variables are stored any number of
alphabetic,numerical, and special characters .
C# Runtime type : System.String
C# declaration : string str;
C# Initialization : str = ".Net Environment";

bool

Bool is used to declare variables to store the Boolean values, true and false. In C# , there is
no conversion between the bool type and other types.
C# Runtime type : System.Boolean
C# declaration : bool flag;
C# Initialization : flag = true;
C# default initialization value : false
The following list shows the list of data types available in C# and their corresponding
class/struct in .NET class library.
C# Data type

Mapped to .NET class/struct

sbyte

System.SByte

byte

System.Byte

char

System.Char

float

System.Single

decimal

System.Decimal

double

System.Double

ushort

System.UInt16

short

System.Int16

uint

System.UInt32

int

System.Int32

ulong

System.UInt64

long

System.Int64

bool

System.Boolean

string

System.String

object

System.Object

Boxing:

Converting value types to reference types is also known as boxing. As can be


seen in the example below, it is not necessary to tell the
compiler an Int32 is boxed to an object, because it takes care of this itself.
e.g.-

Int32 a = 10;
object count = a ; // Implicit boxing
Console.WriteLine("The Object count = {0}",count); // prints out 10
//However, an Int32 can always be explicitly boxed like this:
Int32 a = 10;
object count = (object) a; // Explicit boxing
Console.WriteLine("The object count = {0}",count); // prints out 10

Unboxing: The following example intends to show how to unbox a reference type back to a
value type. First an Int32 is boxed to an object, and then it is
unboxed again. Note that unboxing requires explicit cast.
Ex.

Int32 a = 5;
object count = a; // Implicit
Boxing a = (int)count; // Explicit Unboxing

Type Conversions Conversion is based on type compatibility and data compatibility.

Implicit Conversion: Implicit Conversion


make conversion for us without asking.

In implicit conversion the compiler will

char -> int -> float is an example of data compatibility.

using System;
class Program
{
static void Main(string[] args)
{

int x =10000;
int y =20000;
long total;
// In this the int values are implicitly converted to long data type;
//you need not to tell compiler to do the conversion, it
automatically does.
total = x + y;
Console.WriteLine("Total is : " + total);
Console.ReadLine();
}
}

Explicit Conversion: In explicit conversion we specifically ask the compiler to


convert the value into another data type. CLR checks for data compatibility at
runtime.

using System;
class Program
{
static void Main(string[] args)
{
int x = 65;
char value;
value = (char)x;
// In this the int values are explicitly converted to char data
type;
//you have to tell compiler to do the conversion, it uses
casting.
Console.WriteLine("Value is: " + value);
Console.ReadLine();
}
}

Microsoft .NET provides three ways of type conversion:

Parsing
Parsing is used to convert string type data to primitive value type. For this we use
parse methods with value types.

using System;
class Program
{
static void Main(string[] args)

//using parsing
int number;
float weight;
Console.Write("Enter any number : ");
number = int.Parse(Console.ReadLine());
Console.Write("Enter your weight : ");
weight = float.Parse(Console.ReadLine());
Console.WriteLine("You have entered : " +
number);
Console.WriteLine("You weight is : " + weight);
Console.ReadLine();
}
}

Convert Class
Convert class contains different static methods like ToInt32(), ToInt16(), ToString(),
ToDateTime() etc used in type conversion.

using System;
class Program
{
static void Main(string[] args)
{
// example of using convert class
string num = "23";
int number = Convert.ToInt32(num);
int age = 24;
string vote = Convert.ToString(age);
Console.WriteLine("Your number is : " + number);
Console.WriteLine("Your voting age is : " + age);
Console.ReadLine();
}
}

Explicit Cast Operator ()


It can used with any type having type compatibility and data type compatibility.

using System;
class Program
{
static void Main(string[] args)
{

int num1, num2;


float avg;
num1 = 10;
num2 = 21;
avg = (float)(num1 + num2) / 2;
Console.WriteLine("average is : " + avg);
Console.ReadLine();

Similarity and difference with C/C++

C# is directly related to C and C++, C++ is a superset of C. C and C++ shares


several syntax, library and functionality. In addition structures, unions, arrays,
strings and pointers are most important and similar functionality for both languages.

C# inherits most of its operators, keywords, and statements directly from C++.
Enums are clearly a meaningful concept in C++.
Finally I can clearly say that C# is the first component-oriented language in the C/C+
+ family.

C# constructors are verisimilar with C++ constructors. Like C++, methods are nonvirtual by default, but can be marked as virtual.

There is also some difference between C# and C++, C# supports multiple inheritance of
interfaces, but not of classes. Another difference is destructors, their syntax is same with
C++ but actually they are very different.

Difference between C# and VB


1.

C# allows 'unsafe' code, or pointer manipulation. VB allows methods with optional


parameters.

2.

C# allows assignments embedded in expressions (e.g., if ((x = y.Value) == 2)).VB


allows types within interfaces.

3.

C# has anonymous methods.VB has the very flexible Select construct (much more
flexible than the C# switch).

4.

C# has the useful conditional ternary operator (?:). The VB If function is not a good
substitute since the arguments must all be evaluated. VB has the When filter for
catch block headers (no equivalent exists in C#).

Difference between C# and Java

Features of C# not present in Java

1.

C# provides integration with COM.

2.

C# has "Explicit Member Implementation" which allows a class to specifically


implement methods of an interface, separate from its own class methods.

3.

C# has the ability to alias namespaces.

4.

C# has support for output parameters, aiding in the return of multiple values, a
feature shared by C++ and SQL.

5.

C# implements properties as part of the language syntax.

6.

C# allows switch statements to operate on strings.

7. Namespace in C#
8. Namespaces group related classes and types, and they define categories in which we
can include any new class that provides related functionality.

namespace MyCompany.r4r
{
class MyClass
{
// some code here
}
}
namespace MyCompany.r4r
{
class MyClass1
{
// some code here
}
}

9. Classes and Object in C#


10. Defining Classes: To define a new type or class, first declare it, and then define its

methods and fields. Declare a class using the class keyword. The complete syntax
is as follows: [attributes] [access-modifiers] class identifier [:base-class]
{
class-body
}
11. For Example.

public class Test


{
public static int Main( )
{
Console.Writeline("This is Class");
}

12. Defining Object: A distinction is drawn between value types and reference types.

The primitive C# types (int, char, etc.) are value types, and are created on
the stack. Objects, however, are reference types, and are created on the heap, using
the keyword new, as in the following:

Test t = new Test();

13.

t does not actually contain the value for the test class object; it contains the address
of that (unnamed) object that is created on the heap. t itself is just a reference to
that object.

14.How to create a program in C#?


15. Step 1: Start notepad from Start -> Program Files -> Accessories -> Notepad so

that you can write the HelloWorld program. The program you write in C# is also
called as source code.
16. Step 2: Write the HelloWorld program, you can either type the program shown below
into notepad or just copy-paste it from here-

public class Helloworld


{
public static void Main()
{
System.Console.WriteLine("you are welcome in world of
C#");
}
}
Step 3: Once you have finished typing your program you should Save the source code file.
In fact after making any changes to your source code, you should always save the file. To
save the file for the first time in notepad click on File menu -> Save As. In the Save As
dialog select the directory from the Save In dropdown where you want to save your files, I

generally save my files to C:\csharp, and then in the File name textbox, enter the file name
as HelloWorld.cs (although you can provide any name you want but it should have an
extension.cs). and click Save. Once you have saved the
source code, and if you make any further modifications, in notepad use the Ctrl+S keyboard
short-cut to save your source code file.
Step 4: Since you have finished writing the source code its time to compile it. Since we are
using a command-line compiler that ships with the .NET SDK, start the command prompt
from Start -> Program Files -> Accessories -> Command Prompt. Or go to Start -> Run,
type cmd and press enter. Now from the command prompt navigate to the directory where
you have stored the source code file by issuing the following DOS commands.cd\ -To
navigate to the root of the derived csharp - To navigate to the csharp directory. Once you
are in the csharp directory where you
saved the source code file earlier, its time to run the C# Compiler csc.exe. Issue the
following command to compile our HelloWorld.cs
program:csc HelloWorld.cs
Step 5: If the compilation of the source code was successful then a new executable (Exe)
file by the name HelloWorld.exe will be created in the directory you compiled the source
code. To execute the program simply type the name of the executable file at the command
prompt.
Points to Remember

1.

C# code can be written in any text editor like notepad.

2.

C# Source Code files are saved with the extension.cs.

3.

C# is a case-sensitive language so you have to be careful while typing.

4.

C# runs on the .NET Platform, hence you need to install the .NET SDK in order to
compile C# programs.

5.

The C# compiler is contained within the file csc.exe, which generally resides in the
C:\windows\Microsoft. NET\Framework\v1.0.4322 directory.

6. Operators, types and variables in C#


7. Variables: A variable is a storage location with a type. Variables can have values
8.

assigned to them, and those values can be changed programmatically. A constant is


a variable whose value cannot be changed.
Types: Like C++ and Java, C# divides types into two sets: intrinsic Built-in types
that the language offers and user-defined types that the programmer defines. C#
also divides the set of types into two other categories: value types and reference
types. The principal difference between value and reference types is the manner in
which their values are stored in memory. C# is a "Strongly Typed" language. Thus all
operations on variables are performed with consideration of what the variable's
"Type" is. There are rules that define what operations are legal in order to maintain
the integrity of the data you put in a variable.

9.

The Boolean Type: Boolean types are declared using the keyword, bool. They have
two values: true or false. In other languages, such as C and C++, boolean conditions
can be satisfied where 0 means false and anything else means true. However, in C#
the only values that satisfy a boolean condition is true and false, which are official
keywords.

using System;
class Booleans
{
public static void Main()
{
bool content = true;
bool noContent = false;
Console.WriteLine("{0} C# programming language content.",
content);
Console.WriteLine("This is second statement {0}.", noContent);
}
}

10. Integral Types: In C#, an integral is a category of types. For anyone confused
because the word Integral sounds like a mathematical term, from the perspective of
C# programming, these are actually defined as Integral types in the C#
programming language specification. They are whole numbers, either signed or
unsigned, and the char type. The char type is a Unicode character, as defined by the
Unicode Standard.
11. Floating Point and Decimal Types: A C# floating point type is either a float or
double. They are used any time you need to represent a real number. Decimal types
should be used when representing financial or money values.
12. The string Type: A string is a sequence of text characters. You typically create a
string with a string literal, enclosed in quotes: "This is an example of a string."
You've seen strings being used in Lesson 1, where we used the Console.WriteLine
method to send output to the console.
13. The Array Type: Another data type is the Array, which can be thought of as a
container that has a list of storage locations for a specified type. When declaring an
Array, specify the type, name, dimensions, and size.

using System;
class NewArray
{
public static void Main()
{
int[] myInts = { 5, 10, 15 };
bool[][] myBools = new bool[2][];
myBools[0] = new bool[2];

myBools[1] = new bool[1];


double[,] myDoubles = new double[2, 2];
string[] myStrings = new string[3];
Console.WriteLine("myInts[0]: {0},
myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1],
myInts[2]);
myBools[0][0] = true;
myBools[0][1] = false;
myBools[1][0] = true;
Console.WriteLine("myBools[0][0]:
{0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
myDoubles[0, 0] = 4.245;
myDoubles[0, 1] = 6.355;
myDoubles[1, 1] = 8.415;
myDoubles[1, 0] = 56.1148917;
Console.WriteLine("myDoubles[0, 0]:
{0}, myDoubles[1, 0]: {1}", myDoubles[0, 0],
myDoubles[1, 0]);
myStrings[0] = "An";
myStrings[1] = "App";
myStrings[2] = "Cattt";
Console.WriteLine("myStrings[0]:
{0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0],
myStrings[1], myStrings[2]);
}
}

The if Statement
if statement is used to take different paths of logic, depending on the conditions.

using System;
using System.Windows.Forms;
class iftest
{
public static void Main()
{
if (totalMarks >= 80)
{
MessageBox.Show("Got Higher First Class ");
}
else if (totalMarks >= 60)

{
MessageBox.Show("Got First Class ");
}
else if (totalMarks >= 40)
{
MessageBox.Show("Just pass only");
}
else
{
MessageBox.Show("Failed");
}

}
}

The switch Statement


Another form of selection statement is the switch statement, which executes a set of logic
depending on the value of a given parameter. The types of the values a switch statement
operates on can be booleans, enums, integral types, and strings.

using System;
class SwitchTest
{
public static void Main()
{
Console.WriteLine("milk bottel size: 1=Small 2=Medium
3=Large");
Console.Write("Please enter your selection: ");
string s = Console.ReadLine();
int n = int.Parse(s);
int price = 0;
switch(n)
{
case 1:
price += 25;
break;
case 2:
price += 25;
goto case 1;
case 3:
price += 50;
goto case 1;
default:
Console.WriteLine("Invalid selection. Please select 1, 2,
or 3.");
break;

}
if (price != 0)
Console.WriteLine("Please insert {0} cents.", price);
Console.WriteLine("Thank you for your business.");
}

The while Loop


While loop is used to check a condition and then continues to execute a block of code as
long as the condition evaluates to a boolean value of true. Syntax:while (<boolean expression>)
{
<statements>
}
When the boolean expression evaluates to false, the while loop statements are skipped and
execution begins after the closing brace of that block of code.

using System;
class whiletest
{
static void Main()
{
//
// Continue in while loop until index is equal to ten.
//
int i = 0;
while (i < 10)
{
Console.Write("While statement ");
//
// Write the index to the screen.
//
Console.WriteLine(i);
//
// Iterate the variable.
//
i++;
}
}
}

The do Loop

A do loop is similar to the while loop, except that it checks its condition at the end of the
loop. This means that the do loop is guaranteed to execute at least one time.

using System;
class DoWhileLoopDemo
{
public static void Main()
{
int i = 0;
// Initialize counter variable
do
{
if ((i % 2) == 0)
{
Console.WriteLine(i);
}
i++;
//Increment the counter
}
while (i <= Limit); // Condition check
}
}

The for Loop


It works like a while loop, except that the syntax of the for loop includes initialization and
condition modification. for loops are appropriate when you know exactly how many times
you want to perform the statements within the loop. The contents within the for loop
parentheses hold three sections separated by semicolons (<initializer list>; <boolean
expression>; <iterator list>) { <statements> }.

using System;
class ForLoop
{
public static void Main()
{
for (int i=0; i < 20; i++)
{
if (i == 10)
break;
if (i % 2 == 0)
continue;

}
}

Console.Write("{0} ", i);


}
Console.WriteLine();

Foreach Statement:
The foreach statement is new to the C family of languages; it is used for looping through
the elements of an array or a collection.

class ForEachTest
{
static void Main(string[] args)
{
int[] num = new int[] { 0, 1, 2, 3, 4, 5, 6,7,8 };
foreach (int i in num)
{
System.Console.WriteLine(i);
}
}
}

Array
An array is the collection of similar type of objects. Array in C# is different for the array of
C++ and other languages because they are
objects. This provides them useful methods and property. Arrays allow a group of elements
of a particular type to be stored
in a contiguous block of memory. Array types derive from System.Array and are declared in
C# using brackets ([]).
Syntax- datatype [] array-name;
e.g.- int [] age;
The square brackets ([]) tell the C# compiler that you are declaring an array, and the type
specifies the type of the elements it will
contain. In the previous example, age is an array of integers. Instantiate an array using the
new keyword. For example:
age = new int[5]; This declaration sets aside memory for an array holding five integers.

Multidimensional Array:
Multidimensional Arrays of two types Rectangular Array and Jagged Array Rectangular Array
represents n-dimensional blocks.
e.g.- int [ , ,] age = new int[17,20,34];
Jagged Arrays are arrays of arrays.

int [][][] books = new int [3][][];

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


{
books[i] = new int [4][];
for (int j = 0; j < 4; j++)
books[i][j] = new int [5];
}
// assign an element
books1 [1,1,1] = books [1][1][1] = 7;
Indexer: Indexers are usually known as smart array in C#.It is used for treating object as
an array.Defining an indexer in C# is much like same as
defining properties. Or we can say that an indexer is a member that enables an object to be
indexed in the same way as an array.
Syntax<access modifier> <return type> this [argument list]
{
get
{
// Write here some code for Get
}
set
{
// Write here some code for Get
}
}

Collections: Collections are the enumerable data structure in C# that can be assessed
using indexes or keys. Types of collections in C# are given belowSystem.Collections namespace
This provides a lot of classes, methods and properties to interact with the varying data
structures that are supported by it. The interfaces
that are defined in this namespace include:

IEnumerable

IEnumerator

ICollection

IList

IDictionary
System.Collections.Stack
System.Collections.Queue Both are derived from ICollection Interface.
The collections that inherit the IDictionary interface include:

System.Collections.SortedList
System.Collections.Hashtable
The IList interface represents collections that only have value. The following are the
classes that extend this interface.
System.Array

System.Collections.ArrayList

System.Collections.Specialized.StringCollection

Concrete Collection Classes:


ArrayList class- This works by maintaining an internal array of objects that is replaced
with a larger array when it reaches its capacity of elements.
BitArray class- It is a dynamically sized array of Boolean values. It is more memoryefficient than a simple array of bools because it uses only one bit for each value.
Hashtable class- A Hashtable is a standard dictionary (key/value) data structure that uses
a hashing algorithm to store and index values efficiently.
Queue class- A Queue is a standard first-in, first-out (FIFO) data structure, providing
simple operations to enqueue, dequeue, peek, etc.
SortedList class-A SortedList is a standard dictionary data structure that uses a binarychop search to index efficiently.
Stack class- A Stack is a standard last-in first-out (LIFO) data structure.
StringCollection class- A StringCollection is a standard collection data structure for storing
strings.

Inheritance
In C#, the specialization relationship is generally implemented by using inheritance.
Inheritance is also provides the reusability, or we can say that extracts some features from
one class to another class.

class Bird
{
public Bird()
{
Console.WriteLine("Bird
}
public void Greet()
{
Console.WriteLine("Bird
}
public void Talk()
{
Console.WriteLine("Bird
}
public virtual void Sing()
{
Console.WriteLine("Bird

constructor");

says Hello");

talk");

song");

}
}
class Peacock : Bird
{
public Peacock()
{
Console.WriteLine("Peacock constructor");
}
public new void Talk()
{
Console.WriteLine("Peacock talk");
}
public override void Sing()
{
Console.WriteLine("Peacock song");
}
}
Bird a1 = new Bird();
a1.Talk();
a1.Sing();
a1.Greet();
Bird a2 = new Peacock();
a2.Talk();
a2.Sing();
a2.Greet();
Types of Inheritance:
In Object Oriented Programming concept there are 3 types of inheritances.
1. Single Inheritance,
2. Multiple Inheritance
3. Multilevel Inheritance
Single Inheritance:
public class A
{
}
public class B:A
{
}
Multiple Inheritance:
public class A
{
}
public class B
{

}
public class C:A,B
{
}

Multilevel Inheritance:
public class A
{
}
public class B:A
{
}
public class C:B
{
}
In the above three types C# don't proved Multiple Inheritance. As there is conflict of
multiple override methods in base classes (say A, B in above example) As in Place C# give
another feature called Interfaces using interfaces you can achieve multiple Inheritance
feature.
Polymorphism
Poly means many and morph means form. Thus, polymorphism refers to being able to use
many forms of a type without regard to the details.
Creating Polymorphic Types:
For creating polymorphism there are two steps1. Create a base class with virtual methods.
2. Create derived classes that override the behavior of the base classs virtual methods.
To create a method in a base class that supports polymorphism, mark the method as
virtual.
Example.

public class BaseClass


{
public virtual void DoWork()
{
}
public virtual int WorkProperty
{
get {
return 0;
}
}
}

public class DerivedClass : BaseClass


{
public override void DoWork()
{

}
public override int WorkProperty()
{
get {
return 0;
}
}

Properties
In C#, properties are natural extension of data fields. But C# provides a built in mechanism
called properties. Usually inside a class, we declare a data field as private and will provide a
set of public. In C#, properties are defined using the property declaration syntax. The
general form of declaring a property is as follows.
<acces_modifier> <return_type> <property_name>
{
get
{
}
set
{
}
}
SET and GET methods to access the data fields, since the data fields are not directly
accessible out side the class. We must use the set/get methods to access the data fields.
Example:

using System;
class Myproperty
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;

}
}
}
class Myprop
{
public static void Main()
{
Myproperty mc = new Myproperty();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}
Properties and Inheritance
The properties of a Base class can be inherited to a Derived class.

using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();
d1.X = 10;
Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'
}
}

Properties & Polymorphism

A Base class property can be polymorphic overridden in a Derived class. But remember that
the modifiers like virtual, override etc are using at property level, not at accessor level.

using System;
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 = new Derived();
b1.X = 10;
Console.WriteLine(b1.X);//Displays 'Derived SET
Derived GET 10'
}
}

Abstract Properties
It is declared as abstract by using the keyword abstract. Remember that an abstract
property in a class carries no code at all. The get/set assessors are simply represented with
a semicolon. In the derived class we must implement both set and get assessors.

using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 = new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);//Displays 'SET GET 10'
}
}

Attributes
Attributes contains a powerful method of associating declarative information with C# code
for types, methods, properties. Once associated with a program entity, the attribute can be
queried at run time and used in any number of ways.
Uses of Attributes:

Associating help documentation with program entities (through a Help attribute).

Associating value editors to a specific type in a GUI framework (through a Value


Editor attribute).

using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
public string Topic
{
get
{
return topic;
}
set
{

// Topic is a named parameter

topic = value;
}

public HelpAttribute(string url) // url is a positional parameter


{
this.Url = url;
}
}

private string topic;

When do we need attributes ?

1.

The System.ObsoleteAttribute attribute that we have just described is a good


example of how an attribute is used by the compiler, certain standard attributes
which are only destined for the compiler are not stored in the assembly.

2.

An attribute can be consumed by the CLR during execution. For example the .NET
Framework offers the System.ThreadStaticAttribute attribute. When a static field is
marked with this attribute the CLR makes sure that during the execution, there is
only one version of this field per thread.

3.

An attribute can be consumed by a debugger during execution. Hence, the


System.Diagnostics.DebuggerDisplayAttribute attribute allows personalizing the
display of an element of the code the state of an object for example) during
debugging.

Structs
Structure is the collection of dissimilar data types. A struct is a simple user-defined type, a
lightweight alternative to classes. Structs are somewhat more efficient in their use of
memory in arrays. The C# struct is a lightweight alternative to a class. It can do almost the
same as a class, but it's less "expensive" to use a struct rather than a class.

class Program
{
static void Main(string[] args)
{
Home home;
Home = new Home("Blue");
Console.WriteLine(Home.Describe());
Home = new Home("Red");
Console.WriteLine(Home.Describe());
Console.ReadKey();
}

struct Home
{
private string color;
public Home(string color)
{
this.color = color;
}
public string Describe()
{
return "This Home is " + Color;
}
public string Color
{
get { return color; }
set { color = value; }
}
}

A struct is a value type and a class is a reference type. When a struct is created, the
variable to which the struct is assigned holds the struct's actual data. and When an object of
the class is created, the variable to which the object is assigned holds only a reference to
that memory.
When the struct is assigned to a new variable, it is copied and When the object reference is
assigned to a new variable. The new variable and the original variable therefore contain two
separate copies of the same data. Changes made to one copy do not affect the other copy.
the new variable refers to the original object.

In general, classes are used to model more complex behavior, or data that is intended to be
modified after a class object is created.
Structs are best suited for small data structures that contain primarily data that is not
intended to be modified after the struct is created.
When to Use Structures?

If the instances are relatively small

If the instance life-time is going to be very short

If you are going to embed the instance into some other instances

Delegate
A delegate in

C# language allows us to reference a method. If we are using a C or


C++ then we would sound familiar because a delegate because it
is basically a function pointer. Delegates have other uses in addition to event
handling. Delegate maintains three important pieces of information :
1. The name of the method on which it make calls.
2. Any argument (if any) of this method.
3. The return value (if any) of this method.

What is a Function Pointer?


Function Pointers are pointers, i.e. variables, which point to the address of a
function.

Types of Delegate
Delegates are of two types

1.Single Cast delegate


public delegate <return type> <delegate name>(parameters)
2.Multi Cast delegate
public delegate void <delegate name>(parameters)

Advantage of using Delegate

Example

Dynamic binding can be done by using delegate because we can call more than one
methods at a time dynamically by calling the delegate in which the methods is
defined.

namespace delgnew

public delegate int Delg(int x, int y);


public class Math
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
}
class Fun
{
static void Main(string[] args)
{
Delg del1 = new Delg(Math.Add);
int add1 = del1(7, 7);
Console.WriteLine("7 + 7 = {0}\n",
add1);
Delg del2 = new Delg(Math.Multiply);
int multiply1 = del2(7,7);
Console.WriteLine("7 * 7 = {0}",
multiply1);
Console.ReadLine();
}
}
}

Static Delegates
Denoting static field is meaning that it will not be modified. You can invoke delegates
without declaring a local delegate instance. Just pass in the static delegate of the
class.
Delegates as Properties
The problem with static delegates is that they must be instantiated whether or not
they are ever used.

Event

Defining Event

An event might be a button push, a menu selection in short we can cay that
something happens and you must respond to it. You cannot predict the order in
which events will arise.
For example- when you click a button, it might raise the Click event. When you add
to a drop-down list, it might raise a List Changed event.

using System;
class Eventtest
{
public event EventHandler myfun
{
add
{
Console.WriteLine ("Event Fired");
}
remove
{
Console.WriteLine ("Controlled");
}
}
static void Main()
{
Eventest et = new Eventtest();
et.myfun += new EventHandler
(et.DoNothing);
et.myfun -= null;
}
void DoNothing (object sender, EventArgs e)
{
}
}

An event allows a class (or other object) to send notifications to other classes (or
objects) that something has occurred. In simple terms an event is the outcome of a
specific action. If you have developed programmers in graphical user interfaces
(GUI) then you are very familiar with Event handling.
When a user interacts with a GUI control (e.g., clicking a button on a form), one or
more methods are executed in response to the above event. Events can also be
generated without user interactions. Event handlers are methods in an object that
are executed in response to some events occurring in the application.

What is Exception?
The exceptions are anomalies that occur during the execution of a program. Exception
handling is a mechanism in .NET framework to detect
and handle run time errors. They can be because of user, logic or system errors. If a user
(programmer) do not provide a mechanism to handle these anomalies, the .NET run time
environment provide a default mechanism, which terminates the program execution.
In C# there are three keywords Try, Catch and Finally for handling exceptions.
In try block statements it might throw an exception whereas catch handles that caused by
try block if one exists.
The finally block is used for doing any clean up process. The statement in finally block
always executes.
e.g.

try
{
// this can cause an exception.
}
catch (Type x)
{
// for handling the exception.
}
finally
{
//this will execute.
}

Handling Exceptions
In catch block, if don't use a brackets or arguments, we can catch all exceptions occurred
inside a try block. Even we can use a catch
block with an Exception type parameter to catch all exceptions happened inside the try
block.
Since in C#, all exceptions are directly or indirectly inherited from the Exception class.
e.g.
class newexp
{
public static void Main()
{
int a = 0;
int div = 0;
try
{
div = 100/a;
Console.WriteLine("This will not print");
}
catch
{
Console.WriteLine("oException" );
}
Console.WriteLine("Result is {0}",div);
}
}

Exceptions Classes
Following are some common exception classes.
SystemException- This exception means a failed run-time check used as a base
class for other.
AccessException- This exception means failure to access a type member, such as a
method or field.

ArgumentException- This exception means an argument to a method was invalid.


ArgumentNullException- This exception means a null argument was passed to a
method that doesn't accept it.
ArgumentOutOfRangeException-This exception means argument value is out of
range.
ArithmeticException- This exception means arithmetic over or underflow has
occurred.
ArrayTypeMismatchException- This exception means attempt to store the wrong
type of object in an array.
BadImageFormatException- This exception means image is in the wrong format.
CoreException- This exception means base class for exceptions thrown by the
runtime.
DivideByZeroException- This exception means an attempt was made to divide by
zero.
FormatException- This exception means the format of an argument is wrong.
IndexOutOfRangeException- This exception means an array index is out of
bounds.
InvalidCastExpression- This exception means an attempt was made to cast to an
invalid class.
InvalidOperationException- This exception means a method was called at an
invalid time.
MissingMemberException- This exception means an invalid version of a DLL was
accessed.
NotFiniteNumberException- This exception means a number is not valid.
NotSupportedException- This exception means indicates that a method is not
implemented by a class.
NullReferenceException- This exception means attempt to use an unassigned
reference.
OutOfMemoryException- This exception means not enough memory to continue
execution.
StackOverflowException- This exception means a stack has overflow.

What is thread ?
Threads are typically created when you want a program to do two things at once.

Starting Threads
The simplest way to create a thread is to create a new instance of the Thread class. The
Thread constructor takes a single argument: a
delegate type. The CLR provides the ThreadStart delegate class specifically for this purpose,
which points to a method you designate.
This allows you to construct a thread and to say to it "when you start, run this method." The
ThreadStart delegate declaration is:
public delegate void ThreadStart( );

Example for Creating Thread:

using System;
using System.Threading;
public class CreatingThread
{
static void Main(string[] args)
{
Thread MyThread = new Thread(new
ThreadStart(ThreadProc));
MyThread.Start();
MyThread.Join();
}
protected static void ThreadProcess()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
}
}
}

Creating a Thread of Execution:


using System;
using System.Threading;
class MyThread
{
public int count;
string thrdName;
public MyThread(string name) {
count = 0;
thrdName = name;
}
public void run()
{
Console.WriteLine(thrdName + " starting.");
do {
Thread.Sleep(500);
Console.WriteLine("In " + thrdName +", count is
" + count);
count++;
} while(count < 10);
Console.WriteLine(thrdName + " terminating.");
}
}
public class MultiThread
{
public static void Main()

{
Console.WriteLine("Main thread starting.");
MyThread mt = new MyThread("Child #1");
Thread newThrd = new Thread(new
ThreadStart(mt.run));
newThrd.Start();
do {
Console.Write(".");
Thread.Sleep(100);
} while (mt.count != 10);
Console.WriteLine("Main thread ending.");
}
}

Joining Threads
To join thread1 (t1) onto thread2 (t2), write:
t2.Join( );
Joining the current thread to each thread in the collection in turn:

foreach (Thread myThread in myThreads)


{
myThread.Join( );
}
Console.WriteLine("All my threads are done.");

Create multiple threads of execution


using System;
using System.Threading;
class MyThread
{
public int count;
public Thread thrd;
public MyThread(string name)
{
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
void run()
{
Console.WriteLine(thrd.Name + " starting.");
do
{

Thread.Sleep(500);
Console.WriteLine("In " + thrd.Name +", count
is " + count);
count++;
} while(count < 10);
Console.WriteLine(thrd.Name + " terminating.");
}
}
public class MoreThreads {
public static void Main() {
Console.WriteLine("Main thread starting.");
MyThread mt1 = new MyThread("Child #1");
MyThread mt2 = new MyThread("Child #2");
MyThread mt3 = new MyThread("Child #3");
do
{
Console.Write(".");
Thread.Sleep(100);
} while (mt1.count < 10 || mt2.count < 10 ||
mt3.count < 10);
Console.WriteLine("Main thread ending.");
}
}

Suspending Threads
To cause your thread to sleep for one second, you can invoke the static method of Thread,
Sleep, which suspends the thread in which it is
invoked:
Thread.Sleep(1000);

Killing Threads
For killing a thread Abort( ) method is used. This causes a ThreadAbortException exception
to be thrown, which the thread can catch,
and thus provides the thread with an opportunity to clean up any resources it might have
allocated.
catch (ThreadAbortException)
{
Console.WriteLine("[{0}] Aborted! Cleaning up...",
Thread.CurrentThread.Name);
}
Example for Suspending, resuming, and stopping a thread:

using System;
using System.Threading;

class MyThread {
public Thread thrd;
public MyThread(string name) {
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
void run() {
Console.WriteLine(thrd.Name + " starting.");
for(int i = 1; i <= 1000; i++) {
Console.Write(i + " ");
if((i%10)==0) {
Console.WriteLine();
Thread.Sleep(250);
}
}
Console.WriteLine(thrd.Name + " exiting.");
}
}
public class SuspendResumeStop {
public static void Main() {
MyThread mt1 = new MyThread("My Thread");
Thread.Sleep(1000); // let child thread start executing
mt1.thrd.Suspend();
Console.WriteLine("Suspending thread.");
Thread.Sleep(1000);
mt1.thrd.Resume();
Console.WriteLine("Resuming thread.");
Thread.Sleep(1000);
mt1.thrd.Suspend();
Console.WriteLine("Suspending thread.");
Thread.Sleep(1000);
mt1.thrd.Resume();
Console.WriteLine("Resuming thread.");
Thread.Sleep(1000);
Console.WriteLine("Stopping thread.");
mt1.thrd.Abort();
mt1.thrd.Join(); // wait for thread to terminate
Console.WriteLine("Main thread terminating.");
}
}
Synchronization
Synchronization is provided by a lock on the object, which prevents a second thread from
barging in on your
object until the first thread is finished with it.

Microsoft Visual Studio


Visual Studio is an integrated development environment (IDE) developed by Microsoft. It
can be used to develop console and graphical user interface applications along with Windows

Forms applications, web sites, web applications, and web services in both native code
together with managed code for all platforms supported by Microsoft Windows, Windows
Mobile, Windows CE.

Architecture
It does not support any programming language, solution or tool intrinsically. Instead, it
allows plugging in various types of functionality, that is coded as a VSPackage.
The IDE provides three services:
SVsSolution, which provides the ability to enumerate projects and solutions;
SVsUIShell, which provides windowing and UI functionality (including tabs, toolbars and tool
windows)
SVsShell, which deals with registration of VSPackages.
In addition, the IDE also manages for coordinating and enabling communication between
services. All editors, designers, project types and other tools are implemented as
VSPackages. Visual Studio uses COM to access the VSPackages. The Visual Studio SDK also
includes the Managed Package Framework (MPF), which is a set of managed wrappers
around the COM-interfaces that allow the Packages to be written in any CLI compliant
language. However, MPF does not provide all the functionality exposed by the Visual Studio
COM interfaces. The services can then be consumed for creation of other packages, which
add functionality to the Visual Studio IDE.

Features of Microsoft Visual Studio

Code editor: Code editor that supports syntax highlighting and code completion using
IntelliSense for not only variables, functions and methods but also language constructs like
loops and queries.
Debugger: It works both as a source-level debugger and as a machine-level debugger. It
works with both managed code as well as native code and can be used for debugging
applications written in any language supported by Visual Studio.
Designer: It includes a host of visual designers to aid in the development of applications.
These tools includes

Windows Forms Designer: It includes a palette of UI widgets and controls (including


buttons, progress bars, labels, layout containers and other controls) that can be
dragged and dropped on a form surface.

WPF(Windows Presentation Foundation) Designer: It is used to author user interfaces


targeting Windows Presentation Foundation. It supports all WPF functionality
including data binding and automatic layout management.

Web designer/development: It is used for developing ASP.NET applications and


supports HTML, CSS and JavaScript. It uses a code-behind model to link with
ASP.NET code. From Visual Studio 2008 onwards, the layout engine used by the web
designer is shared with Microsoft Expression Web.

Class designer: The Class Designer can generate C# and VB.NET code outlines for
the classes and methods. It can also generate class diagrams from hand-written
classes.

Data designer: The data designer can be used to graphically edit database schemas,
including typed tables, primary and foreign keys and constraints. It can also be used
to design queries from the graphical view.

Mapping designer: The mapping designer is used by LINQ to SQL to design the
mapping between database schemas and the classes that encapsulate the data.

Other tools
ToolBox Explorer

Open Tabs Browser: It is used to list all open tabs and to switch between them. It is
invoked using CTRL+TAB.
Properties Editor: It is used to edit properties in a GUI pane inside Visual Studio.

Object Browser: It can be used to browse the namespaces (which are arranged
hierarchically) in managed assemblies.

Solution Explorer: It is used to manage and browse the files in a solution.

Team Explorer: It is used to integrate the capabilities of Team Foundation Server, the
Revision Control System into the IDE (and the basis for Microsoft's CodePlex hosting
environment for open source projects). In addition to source control it provides the ability to
view and manage individual work items (including bugs, tasks and other documents) and to
browse TFS statistics.
Data Explorer: It is used to manage databases on Microsoft SQL Server instances.
Server Explorer: It tool is used to manage database connections on an accessible
computer.

Included products

Microsoft Visual C++: It is Microsoft's implementation of the C and C++ compiler


and associated languages-services and specific tools for integration with the Visual
Studio IDE.

Microsoft Visual C#: Microsoft's implementation of the C# language, targets the .NET
Framework, along with the language services that lets the Visual Studio IDE support
C# projects.

Microsoft Visual Basic: Microsoft's implementation of the VB.NET language and


associated tools and language services. It was introduced with Visual Studio .NET
(2002).

Creating Windows Application


For creating a new project you need to first load Visual Studio .NET and select Windows
Application as in Figure below . Type the name of the project below along with selecting the
desired location to store your files.

Designing The Interface: We are going to design a simple application for adding values
in List Box from from textbox input by the user, for this will need to add the following items
onto your form.
GroupBox
Label
ComboBox
Textbox
Button
ListBox

Adding The Code: When this form loads we need to populate the ComboBox with the
appropriate values. Add the following code by clicking on the form on the outside of the
groupBox. You should see something like this:
write this code on Form Load Event-

private void Form1_Load(object sender, EventArgs e)


{
comboBox1.Items.Add("Dr.");
comboBox1.Items.Add("Er.");
comboBox1.Items.Add("Mr.");
comboBox1.Items.Add("Mrs.");
comboBox1.Items.Add("Ms.");
comboBox1.Focus();
}

Double-click on the OK button and add the following code:

private void button1_Click(object sender, EventArgs e)


{
listBox1.Items.Add(comboBox1.Text + " " +textBox1.Text + " "
+ textBox2.Text);
textBox1.Text = "";
textBox2.Text = "";
comboBox1.Text = "";
comboBox1.Focus();
}
When we want to allow the user to clear all fields entered into the listBox, we will need to go
back like we did above to the visual designer and double-click on the Clear List button, this
should again switch to a code view and allow you to add the following code-

private void button2_Click(object sender,


EventArgs e)
{
listBox1.Items.Clear();
comboBox1.Focus();
}

And finally we want to allow the user to be able to close the application when they want. To
show you another way to allow the user to close the program aside from that catchy X in
the upper right-hand corner, I have provided a button entitled Close.

private void button3_Click(object sender, EventArgs


e)
{
this.Dispose();
}

Controls
System.Windows.Forms.Control class This class defines the basic functionality of the
controls, which is why many properties and events in the controls. Some controls, named
custom or user controls, derive from another class: System.Windows.Forms.UserControl.
This class is itself derived from the Control class and provides the functionality we need to
create controls ourselves.
Properties

All controls have a number of properties that are used to manipulate the behavior of the
control. The base class of most controls, Control, has a number of properties that other
controls either inherit directly or override to provide some kind of custom behavior.

Name

Availabilit
y

Description

Anchor

Read/Write

It tells how control behaves when its


container is resized.

BackColor

Read/Write

about background color of a control.

Bottom

Read/Write

You can specify the distance from the


top of the window to the bottom of
the control. This is not the same as
specifying the height of the control.

Read/Write

by this property you can make a


control dock to the edges of a
window.

Enabled

Read/Write

Enabled to true usually means that


the control can receive input from the
user. Setting Enabled to false usually
means that it cannot.

ForeColor

Read/Write

foreground color of the control.

Height

Read/Write

distance from the top to the bottom


of the control.

Left

Read/Write

left edge of the control relative to the


left edge of the window.

Name

Read/Write

name of the control. This name can


be used to reference the control in
code.

Parent

Read/Write

parent of the control.

Right

Read/Write

right edge of the control relative to


the left edge of the window.

TabIndex

Read/Write

number the control has in the tab


order of its container.

TabStop

Read/Write

Specifies whether the control can be


accessed by the Tab key.

Tag

Read/Write

This value is usually not used by the


control itself, and is there for you to
store information about the control on
the control itself. When this property
is assigned a value through the
Windows Form designer, you can only
assign a string to it.

Top

Read/Write

The top edge of the control relative to


the top of the window.

Visible

Read/Write

Dock

Specifies whether or not the control is


visible

at runtime.
Width

Read/Write

width of the control.

Events
When a user clicks a button or presses a button, you as the programmer of the application,
want to be told that this has happened. To do so, controls use events. The Control class
defines a number of events that are common to the controls we'll use in this chapter.

Name

Description

MouseMove

Occurs continually as the mouse travels over the


control.

MouseUp

Occurs when the mouse pointer is over a control and a


mouse button
is released.

Click

Occurs when a control is clicked. In some cases, this


event will also occur when a user presses Enter.

Occurs when a control is double-clicked. Handling the


Click event on some controls, such as the Button
DoubleClick
control will mean that the DoubleClick event can never
be called.
DragDrop

Occurs when a drag-and-drop operation is completed,


in other words, when an object has been dragged over
the control, and the user releases the mouse button.

DragEnter

Occurs when an object being dragged enters the


bounds of the control.

DragLeave

Occurs when an object being dragged leaves the


bounds of the control.

DragOver

Occurs when an object has been dragged over the


control.

KeyDown

Occurs when a key becomes pressed while the control


has focus. This event always occurs before KeyPress
and KeyUp.

KeyPress

Occurs when a key becomes pressed, while a control


has focus. This event always occurs after KeyDown and
before KeyUp. The difference between KeyDown and
KeyPress is that KeyDown passes the keyboard code of
the key that has been pressed, while KeyPress passes
the corresponding char value for the key.

KeyUp

Occurs when a key is released while a control has


focus. This event always occurs after KeyDown and
KeyPress.

GotFocus

Occurs when a control receives focus. Do not use this


event to perform validation of controls. Use Validating
and Validated instead.

LostFocus

Occurs when a control looses focus. Do not use this


event to perform validation of controls. Use Validating
and Validated instead.

Occurs when the mouse pointer is over a control and a


MouseDow mouse button is pressed. This is not the same as a
n
Click event because MouseDown occurs as soon as the
button is pressed and before it is released.
Paint

Occurs when the control is drawn.

Validated

This event is fired when a control with the


CausesValidation property set to true is about to receive
focus. It fires after the Validating event finishes and
indicates that validation is complete.

Validating

Fires when a control with the CausesValidation property


set to true is about to receive focus. Note that the
control which is to be validated is the control which is
losing focus, not the one that is receiving it.

The Button Control


The button control exists on just about any Windows dialog you can think of. A button is
primarily used to perform three kinds of tasks:
For closing a dialog with a state (for example, OK and Cancel buttons)
For performing an action on data entered on a dialog (for example clicking Search after
entering some search criteria)
For opening another dialog or application (for example, Help buttons)
Properties of Button Control

Name

Availabilit
y

Description

FlatStyle

Read/Write

If you set the style to PopUp, the button will


appear flat until the user moves the mouse pointer
over it. When that happens, the button pops up to
its normal 3D look.

Enabled

Read/Write

Enabled property to false means that the button


becomes grayed out and nothing happens when
you click it.

Image

Read/Write

Allow you to specify an image (bitmap, icon etc.),


which will be displayed on the button.

ImageAlign Read/Write

Button Events

With this property, you can set where the image on


the button should appear.

The most used event of a Button is the Click event. This occurs whenever a user clicks the
button, by which we mean pressing the left mouse button and releasing it again while over
the button. This means that if you left-click on the button and then draw the mouse away
from the button before releasing it the Click event will not be raised. Also, the Click event is
raised when the button has focus and the user press Enter. If you have a button on a form,
you should always handle this event.
Adding the Event Handlers
When you double-click the control two things happens in the code behind the form. First of
all, a subscription to the event is created in the InitializeComponent() method:
this.btnEnglish.Click += new System.EventHandler(this.btnEnglish_Click);
The second thing that happens, is that the event handler itself is added.

private void button1_Click(object sender, EventArgs e)


{
label1.Text = "You have clicked the button!!!";
}

Label and Link Label


The label is a simple control with one purpose only: to present a caption or short hint to
explain something on the form to the user.
Visual Studio.NET includes two label controls that are able to present them selves to the
user in two distinct ways:
Label, the standard Windows label
LinkLabel, a label like the standard one (and derived from it), but presents itself as an
internet link (a hyperlink)

The TextBox Control


Text boxes should be used when you want the user to enter text that you have no
knowledge of at design time (for example the name of the user). The primary function of a
text box is for the user to enter text, but any characters can be entered, and it is quite
possible to force the user to enter numeric values only.
Properties of TextBox

Name

Availabilit
y

CausesValidatio
Read/Write
n

CharacterCasing Read/Write

Description
When a control that has this property set to
true is about to receive focus, two events are
fired: Validating and Validated. You can
handle these events in order to validate data
in the control that is losing focus. This may
cause the control never to receive focus. The
related events are discussed below.
A value indicating if the TextBox changes the
case of the text entered. The possible
values are:

q Lower: All text entered into the text box is


converted lower case.
q Normal: No changes are made to
the text.
q Upper: All text entered into the text box is
converted to upper case.

MaxLength

Read/Write

A value that specifies the maximum length in


characters of any text, entered into the
TextBox. Set this value to zero it the
maximum limit is limited only by available
memory.

Multiline

Read/Write

Indicates if this is a Multiline control. A


Multiline control is able to show multiple lines
of text.

PasswordChar

Read/Write

Specifies if a password character should


replace the actual characters entered into a
single line textbox. If the Multiline property is
true then this has no effect.

ReadOnly

Read/Write

A Boolean indicating if the text is read only.

ScrollBars

Read/Write

Specifies if a multilane text box should


display scrollbars.

SelectedText

Read/Write

The text that is selected in the text box.

SelectionLength Read/Write

The number of characters selected in the


text. If this value is set to be larger than the
total number of characters in the text, it is
reset by the control to be the total number of
characters minus the value of SelectionStart.

SelectionStart

Read/Write

The start of the selected text in a text box.

WordWrap

Read/Write

Specifies if a multiline text box should


automatically wrap words if a line exceeds
the width of the control.

Events of TextBox

Name
Enter
GotFocus
Leave
Validating
Validated

Description
These six events occur in the order they are listed here. They are
known as "Focus Events" and are fired whenever a controls focus
changes, with two exceptions. Validating and Validated are only
fired if the control that receives focus has the CausesValidation
property set to true. The reason why it's the receiving control
that fires the event is that there are times where you do not
want to validate the control, even if focus changes. An example
of this is if the user clicks a Help button.

LostFocus
These three events are known as "Key Events". They allow you to
monitor and change what is entered into your controls.
KeyDown
KeyPress
KeyUp

Change

KeyDown and KeyUp receive the key code corresponding to the


key that was pressed. This allows you to determine if special
keys such as Shift or Control and F1 were pressed.
KeyPress, on the otherhand, receives the character
corresponding to a keyboard key. This means that the value for
the letter "a" is not the same as the letter "A". It is useful if you
want to exclude a range of characters, for example, only allowing
numeric values to be entered.
Occurs whenever the text in the textbox is changed, no matter
what
the change.

TextBox Test

First Design a form on choosing New Project of Windows Application. and then set the
properties of label, button and forms like shown in above picture.
Adding the events
Code for Ok Button Click

private void okbtn_Click(object sender, EventArgs e)


}
if (nametxt.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text
== "")
}
MessageBox.Show("Please fill all Information", "Alert",
,MessageBoxButtons.OKCancel
;(MessageBoxIcon.Information
{
else
}
;string output
Concatenate the text values of the four TextBoxes //
;"output = "Name: " + this.nametxt.Text + "\r\n
;"output += "Address: " + this.textBox2.Text + "\r\n
;"output += "Occupation: " + this.textBox3.Text + "\r\n
;output += "Age: " + this.textBox4.Text
Insert the new text //
;this.textBox5.Text = output
{
{
Code for Help Button Click-

private void button1_Click(object sender, EventArgs e)


{
string output;
output = "Name = Enter Your name\r\n";
output += "Address = Enter Your
address\r\n";
output += "Occupation = Enter
Occupation\r\n";
output += "Age = Enter Your age";
// Insert the new text
this.textBox5.Text = output;
}
Adding Events on TextBoxEvent on TextBox Leave Event-

private void nametxt_Leave(object sender, EventArgs e)


{
if (nametxt.Text == "")
{
}

nametxt.BackColor = Color.Red;

}
Event on TextBox Keypress Event-

private void nametxt_KeyPress(object sender,


KeyPressEventArgs e)
{
if (nametxt.BackColor == Color.Red)
{
nametxt.BackColor = Color.Snow;
}
}

Radio Button

Radio buttons themselves as a label with a dot to the left of it, which can be either selected
or not. You should use the radio buttons when you want to give the user a choice between
several mutually exclusive options. for Example, if you want to ask for the gender of the
user.
To group radiobuttons together so that they create one logical unit you must use a
GroupBox control. By first placing a group box on a form, and then placing the RadioButton
controls you need within the borders of the group box, the RadioButton controls will know to
change their state to reflect that only one within the group box can be selected. If you do
not place them within a group box, only one RadioButton on the form can be selected at any
given time.

CheckBox Controls
A CheckBox traditionally displays itself as a label with a small box with a checkmark to the
left of it. You should use the check box when you want to allow the user to choose one or
more options. An example could be a questionnaire asking which operating systems the
user has tried (for example, Windows 95, Windows 98, Linux, Max OS X, and so on.)

RadioButton Properties

Name

Availabilit
y

Description

Read/Write

A RadioButton can be displayed either as a


label with a circular check to the left,
middle or right of it, or as a standard
button. When it is displayed as a button,
the control will appear pressed when
selected and 3D otherwise.

AutoCheck

Read/Write

When this property is true, a check mark is


displayed when the user clicks the radio
button. When it is false, the check mark is
not displayed by default.

CheckAlign

Read/Write

By using this property, you can change the


alignment of the radio button. It can be
left, middle, and right.

Checked

Read/Write

Indicates the status of the control. It is true

Appearance

if the control has a check mark, and false


otherwise.

RadioButton Events
Name

Description

This event is sent when the check of the RadioButton


changes. If there is more than one RadioButton control on
CheckChange
the form or within a group box, this event will be sent twice,
d
first to the control, which was checked and now becomes
unchecked, then to the control which becomes checked.

Click

This event is sent every time the RadioButton is clicked. This


is not the same as the change event, because clicking a
RadioButton twice or more times in succession only changes
the checked property once and only if it wasn't checked
already.

CheckBox Properties

Name

Availabilit
y

Description

CheckStat
Read/Write
e

Unlike the RadioButton, a CheckBox can have


three states: Checked, Indeterminate, and
Unchecked. When the state of the check box is
Indeterminate, the control check next to the label
is usually grayed, indicating that the current
value of the check is not valid or has no meaning
under the current circumstances. An example of
this state can be seen if you select several files in
the Windows Explorer and look at their
properties. If some files are ReadOnly and others
are not, the ReadOnly checkbox will be checked,
but grayed indeterminate.

ThreeState Read/Write

When this property is false, the user will not be


able to change the CheckBox' state to
Indeterminate. You can, however, still change the
state of the check box to Indeterminate from
code.

CheckBox Events

Name

CheckedChanged

Description
Occurs whenever the Checked property of the check
box changes. Note that in a CheckBox where the
ThreeState property is true, it is possible to click the
check box without changing the Checked property.
This happens when the check box changes from
checked to indeterminate state.

Occurs whenever the CheckedState property


changes. As Checked and Unchecked are both
CheckedStateChange possible values of the CheckedState property, this
d
event will be sent whenever the Checked property
changes. In addition to that, it will also be sent when
the state changes from Checked to Indeterminate.
Example: In following image i have created a window form for saving information of
student like personal info and subjects of his/her. For this you have to drag and drop 4
textboxes, 2 radiobuttons, 5 labels and 3 buttons. Change all controls properties like in
picture.

In figure 2 if user direct click on ok button then he/she will get massage for alert to fill all
information. In Figure 3 if user fill personal information and then click on Ok button then
he/she will get alert message for choosing gender. And in figure 4 if user not choose subject
and click on ok button then he will get another alert message for choosing subject. To
making all these validation you have to write following code on Ok button Click.
Code For Ok Button Click:

private void button2_Click(object sender, EventArgs e)


{
if (textBox1.Text == "" || textBox2.Text == "" || textBox4.Text
== "")

MessageBox.Show("Please fill all personal information",


"Warning",
MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);

}
else if (radioButton1.Checked == false &&
radioButton2.Checked == false)
{
MessageBox.Show("Please select Gender", "Warning",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning);
}
else if (checkedListBox1.Text=="")
{
MessageBox.Show("Please select Subjects", "Warning",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning);
}
else
{
if (radioButton1.Checked)
{
// Concatenate the text values of the four TextBoxes
output = "Name: " + this.textBox1.Text + "\r\n";
output += "Address: " + this.textBox2.Text + "\r\n";
output += "Course: " + this.textBox4.Text + "\r\n";
output += "Sex: " + this.radioButton1.Text + "\r\n";
output += "Subject:";
foreach (string sub in checkedListBox1.CheckedItems)
output += " " + sub;
}
if (radioButton2.Checked)
{
// Concatenate the text values of the four TextBoxes
output = "Name: " + this.textBox1.Text + "\r\n";
output += "Address: " + this.textBox2.Text + "\r\n";
output += "Course: " + this.textBox4.Text + "\r\n";
output += "Sex: " + this.radioButton2.Text+"\r\n";
output += "Subject:";
foreach (string sub in checkedListBox1.CheckedItems)
output += " " + sub;
}
this.textBox3.Text = output;
}

Now if you to give condition for user that he should must choose at least three subjects
then you can add code for this on Checklistbox Leave Event. Like following code.

Code for Leave Event on Checklist Box.

private void checkedListBox1_Leave(object sender,


EventArgs e)
{
int count =
checkedListBox1.CheckedItems.Count;
{
if(count<=3)
MessageBox.Show("Your minimum choice is
Three subject");
}
}

Final output will show like in below figure

GroupBox Control

Windows Forms GroupBox controls are used to provide a most important facility for
grouping other controls. Typically, you use group boxes to subdivide a form by function. For
example, you may have an order form that specifies mailing options such as which
overnight carrier to use. Grouping all options in a group box gives the user a logical visual
cue. The GroupBox control is similar to the Panel control; however, only the GroupBox
control displays a caption, and only the Panel control can have scroll bars.

Group Box Properties

Group Box Event:

Rich TextBox Control


Like the normal TextBox, the RichTextBox control is derived from TextBoxBase. Because of
this, it shares a number of features with the TextBox, but is much more diverse. Where a
TextBox is commonly used with the purpose of obtaining short text strings from the user,
the RichTextBox is used to display and enter formatted text (for example bold, underline,
and italic). It does so using a standard for formatted text called Rich Text Format or RTF.
RichTextBox Properties

Name

Availabilit

Description

CanRedo

Read only

This property is true if something has


been undone, that can be reapplied,
otherwise false.

CanUndo

Read only

This property is true if it is possible to


perform an undo action on the
RichTextBox, otherwise it is false.

Read only

This property holds the name of an


action that be used to redo something
that has been undone in the
RichTextBox.

DetectUrls

Read/Write

Set this property to true to make the


control detect URLs and format them
(underline as in
a browser).

Rtf

Read/Write

This corresponds to the Text property,


except that this holds the text in RTF.

Read/Write

Use this property to get or set the


selected text in the control, in RTF. If
you copy this text to another
application, for example, MS Word, it
will retain all formatting.

SelectedText

Read/Write

Like SelectedRtf you can use this


property to get or set the selected
text. Unlike the RTF version of the
property however, all formatting is
lost.

SelectionAlignment

Read/Write

This represents the alignment of the


selected text. It can be Center, Left, or
Right.

SelectionBullet

Read/Write

Use this property to find out if the


selection is formatted with a bullet in
front of it, or use it to insert or remove
bullets.

BulletIndent

Read/Write

Use this property to specify the


number of pixels a bullet should be
indented.

SelectionColor

Read/Write

Allow you to change the color of the


text in
the selection.

SelectionFont

Read/Write

Allow you to change to font of the text


in the selection.

SelectionLength

Read/Write

Using this property, you either set or


retrieve the length of a selection.

SelectionType

Read only

RedoActionName

SelectedRtf

This property holds information about


the selection. It will tell you if one or

more OLE objects are selected or if


only text is selected.
ShowSelectionMargi
Read/Write
n

If you set this property to true, a


margin will be shown at the left of the
RichTextBox. This will make it easier
for the user to select text.

UndoActionName

Read only

Gets the name of the action that will


be used if the user chooses to undo
something.

Read/Write

You can specify that certain parts of


the text should not be changed by
setting this property
to true.

SelectionProtected

RichTextBox Events

Name

Description

LinkedClick

This event is sent when a user clicks on a link


within the text.

Protected

This event is sent when a user attempts to modify


text that has been marked as protected.

This event is sent when the selection changes. If


SelectionChange for some reason you don't want the user to
d
change the selection, you can prevent the change
here.
Example of Rich TextBox: To implement rich textbox create new application and design
form like below image, and change properties according to your choice.

In following image i am making selected text bold on clicking the bold Button. Coding for
bold button is given below.

Code for Bold Button

private void button1_Click(object sender, EventArgs e)


{
Font oldFont;
Font newFont;
// Get the font that is being used in the selected text
oldFont = this.richTextBox1.SelectionFont;
// If the font is using bold style now, we should remove
the
// Formatting
if (oldFont.Bold)
newFont = new Font(oldFont, oldFont.Style &
~FontStyle.Bold);
else
newFont = new Font(oldFont, oldFont.Style |
FontStyle.Bold);
// Insert the new font and return focus to the
RichTextBox

this.richTextBox1.SelectionFont = newFont;
this.richTextBox1.Focus();
}

In following image i am making selected text Italic on clicking the italic Button. Coding for
italic button is given below.

Code for Italic Button

private void button2_Click(object sender, EventArgs e)


{
Font oldFont;
Font newFont;
// Get the font that is being used in the selected text
oldFont = this.richTextBox1.SelectionFont;
// If the font is using Italic style now, we should remove
it

if (oldFont.Italic)
newFont = new Font(oldFont, oldFont.Style &
~FontStyle.Italic);
else
newFont = new Font(oldFont, oldFont.Style |
FontStyle.Italic);
// Insert the new font
this.richTextBox1.SelectionFont = newFont;
this.richTextBox1.Focus();
}

In following image i am making selected text Underline on clicking the Underline Button.
Coding for Underline Button is given below.

Coding for Underline Button

private void button3_Click(object sender, EventArgs e)


{
Font oldFont;
Font newFont;

// Get the font that is being used in the selected text


oldFont = this.richTextBox1.SelectionFont;
// If the font is using Underline style now, we should
remove it
if (oldFont.Underline)
newFont = new Font(oldFont, oldFont.Style &
~FontStyle.Underline);
else
newFont = new Font(oldFont, oldFont.Style |
FontStyle.Underline);
// Insert the new font
this.richTextBox1.SelectionFont = newFont;
this.richTextBox1.Focus();
}

In following image i am making selected text Center on clicking the Center Button. Coding
for Center Button is given below.

Coding for Center Button

private void button4_Click(object sender, EventArgs e)


{
if (this.richTextBox1.SelectionAlignment ==
HorizontalAlignment.Center)
this.richTextBox1.SelectionAlignment =
HorizontalAlignment.Left;
else
this.richTextBox1.SelectionAlignment =
HorizontalAlignment.Center;
this.richTextBox1.Focus();
}

In following image i am making selected text size large and small by putting the value in
size textbox. Coding for this is given below.

Coding for Size Change


for this you have to write following code on textbox validating event.

private void txtSize_Validating(object sender,


CancelEventArgs e)
{

TextBox txt = (TextBox)sender;


ApplyTextSize(txt.Text);
this.richTextBox1.Focus();
}

And then you have to write keypress event on textbox event.

private void txtSize_KeyPress(object sender, KeyPressEventArgs e)


{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 &&
e.KeyChar != 13)
{
e.Handled = true;
}
else if (e.KeyChar == 8)
{
MessageBox.Show("Please input valid size");
}
else if (e.KeyChar == 13)
{
// Apply size if the user hits enter
TextBox txt = (TextBox)sender;
if (txt.Text.Length > 0)
ApplyTextSize(txt.Text);
e.Handled = true;
this.richTextBox1.Focus();
}
}

and then make a method for applytextsize method

private void ApplyTextSize(string textSize)


{
// Convert the text to a float because we'll be needing a
float shortly
float newSize = Convert.ToSingle(textSize);
FontFamily currentFontFamily;
Font newFont;
// Create a new font of the same family but with the new

size
currentFontFamily =
this.richTextBox1.SelectionFont.FontFamily;
newFont = new Font(currentFontFamily, newSize);
// Set the font of the selected text to the new font
}

this.richTextBox1.SelectionFont = newFont;

ListBox Controls
These controls are used to show a list of strings from which one or more can be selected at
a time. Just like check boxes and radio buttons, the list box provides a means of asking the
user to make one or more selections. You should use a list box when at design time you
don't know the actual number of values the user can choose from (an example could be a
list of co-workers). Even if you know all the possible values at design time, you should
consider using a list box if there are a great number of values.

Properties of Listbox

Name
SelectedIndex

Availabilit
y
Read/Write

Description
This value indicates the zero-based index of
the selected item in the list box. If the list
box can contain multiple selections at the

same time, this property holds the index of


the first item in the selected list.
ColumnWidth

Read/Write

In a list box with multiple columns, this


property specifies the width of the columns.

Items

Read-only

The Items collection contains all of the items


in the list box. You use the properties of this
collection to add and remove items.

MultiColumn

Read/Write

A list box can have more than one column.


Use this property the get or set the number
of columns in the list box.

SelectedIndices

Read-only

This property is a collection, which holds all


of the zero-based indices of the selected
items in the list box.

SelectedItem

Read/Write

In a list box where only one item can be


selected, this property contains the selected
item if any. In a list box where more than
one selection can be made, it will contain the
first of the selected items.

SelectedItems

Read-only

This property is a collection, which contains


all of the items currently selected.
You can choose between four different
modes of selection in a list box:
q None: No items can be selected.

SelectionMode

Read/Write

q One: Only one item can be selected at any


time.
q MultiSimple: Multiple items can be
selected.
q MultiExtended: Multiple items can be
selected and the user can use the Ctrl, Shift
and arrows keys to make selections.

Sorted

Text

CheckedIndicies

Read/Write

Setting this property to true will cause the


ListBox to sort the items it contains
alphabetically.

Read/Write

We've seen Text properties on a number of


controls, but this one works very differently
than any we've seen so far. If you set the
Text property of the list box control, it
searches for an item that matches the text,
and selects it. If you get the Text property,
the value returned is the first selected item
in the list. This property cannot be used if
the SelectionMode is None.

Read-only

(CheckedListBox only) This property is a


collection, which contains all indexes in the
CheckedListBox that is a checked or
indeterminate state.

(CheckedListBox only) This is a collection of


all the items in a CheckedListBox that are in
a checked or indeterminate state.

CheckedItems

Read-only

CheckOnClick

Read/Write

(CheckedListBox only) If this property is


true, an item will change its state whenever
the user clicks it.

ThreeDCheckBoxe
Read/Write
s

(CheckedListBox only) You can choose


between Checkboxes that are flat or normal
by setting
this property.

ListBox Methods

Name

Description

ClearSelected

Clears all selections in the ListBox,

FindString

Finds the first string in the ListBox beginning with a string


you specify for example FindString("a") will find the first
string in the ListBox beginning with 'a'

FindStringExact

Like FindString but the entire string must be matched

GetSelected

Returns a value that indicates whether an item is selected

SetSelected

Sets or clears the selection of an item

ToString

Returns the currently selected item

GetItemChecked

(CheckedListBox only) Returns a value indicating if an item


is checked or not

GetItemCheckStat (CheckedListBox only) Returns a value indicating the check


e
state of an item
SetItemChecked

(CheckedListBox only) Sets the item specified to achecked


state.

SetItemCheckState (CheckedListBox only) Sets the check state of an item


ListBox Events

Name
ItemCheck

Description
(CheckedListBox only) Occurs when the check state of
one of the list items changes

SelectedIndexChange
Occurs when the index of the selected item changes
d
Sample Example for ListBox control

In following image i have taken 2 ListBox controls and 4 buttons and add items in ListBox
one with collection property of this.and change property according to your choice.

My purpose of taking two ListBox is for moving items from listbox1 to ListBox 2 by button
click ad show below with single selection and multi selection if user click on button without
selecting item from listbox1 then he/she will get alert message for choosing items from
ListBox.
Code for this is given below

Write following code on Single selection Button by double click on button.

private void button1_Click(object sender, EventArgs e)


{
if (listBox1.SelectedIndex >= 0)
{
string selectitem = listBox1.SelectedItem.ToString();
listBox2.Items.Add(selectitem);
listBox1.Items.Remove(selectitem);
}
else
{
MessageBox.Show("Please Choose Item to move",
"Warning");
}
}

Code for moving all items from one ListBox to another.

private void button2_Click(object sender,


EventArgs e)
{
foreach (string item in listBox1.Items)
{

listBox2.Items.Add(item);
}
listBox1.Items.Clear();
}

You will get output as follows

Similarly you can write for moving items from listbox2 to listbox1.

ComboBox Controls
The ComboBox control is used to save space on a dialog because the only part of the combo
box that is permanently visible are the text box and button parts of the control. When the
user clicks the arrow button to the right of the text box, a list box unfolds in which the user
can make a selection. As soon as he or she does so, the list box disappears and the display
returns to normal.
As the name implies, a combo box combines a number of controls, to be specific the
TextBox, Button, and ListBox controls. Unlike the ListBox, it is never possible to select more
than one item in the list of items contained in a ComboBox and it is optionally possible to
type new entries in the list in the TextBox part of the ComboBox.

ComboBox Properties

Name

Availabilit
y

Description

A combo box can be displayed with three


different styles:
q DropDown: The user can edit the text box
part of the control, and must click the arrow
button to display the list part of the control.
DropDownStyle Read/Write

q Simple: Same as DropDown, except that the


list part of the control is always visible, much
like a normal ListBox.
q DropDownList: The user cannot edit the text
box part of the control, and must click the
arrow button to display the list part of the
control.

DroppedDown Read/Write

Indicates whether the list part of the control is


dropped down or not. If you set this property
to true, the list will unfold.

Items

Read-only

This property is a collection, which contains all


the items in the list contained in the combo
box.

Read/Write

By setting this property to anything other than


zero, you control the maximum number of
characters it is possible to enter into the text
box part of the control.

MaxLength

SelectedIndex Read/Write

Indicates the index of the currently selected


item in the list.

SelectedItem

Read/Write

Indicates the item that is currently selected in


the list.

SelectedText

Read/Write

Represents the text that is selected in the text


box part of the control.

Read/Write

In the text box part of the control, this


property represents the index of the first
character that
is selected.

SelectionStart

SelectionLengt
Read/Write
h

The length of the text selected in the text box


part of the control.

Sorted

Read/Write

Set this property to true to make the control


sort the items in the list portion alphabetically.

Read/Write

If you set this property to null, any selection in


the list portion of the control is removed. If
you set it to a value, which exists in the list
part of the control, that value is selected. If
the value doesn't exist in the list, the text is
simply shown in the text portion.

Text

ComboBox Events

Name
DropDown

Description
Occurs when the list portion of the control is dropped
down.

SelectedIndexChange Occurs when the selection in the list portion of the


d
control changed.
KeyDown, KeyPress,
KeyUp

These events occur when a key is pressed while the text


portion of the control has focus. Please refer to the
descriptions of the events in the text box section earlier
in this chapter.

TextChanged

Occurs when the Text property changes

ComboBox Text Example


In following image i have designed a window form for saving the address of user. Make
design of your application in following image manner and change properties according to
you.

In following figure for selecting country i have used ComboBox for selecting country and
after that he/she will get the name of corresponding state name of that country he/she
selected.
Code for Combobox1 to add the items in Combobox2. Write following code on
Combobox1 selected index change

private void comboBox1_SelectedIndexChanged(object sender,


EventArgs e)
{
comboBox2.Items.Clear();
comboBox2.Enabled = true;
if (comboBox1.SelectedItem.ToString() == "India")
{
comboBox2.Items.Add("NewDelhi");
comboBox2.Items.Add("Chennai");
comboBox2.Items.Add("Banglore");
comboBox2.Items.Add("Mumbai");
}
else if (comboBox1.SelectedItem.ToString() == "Australia")
{
comboBox2.Items.Add("Sydney");
comboBox2.Items.Add("Johnsberg");
comboBox2.Items.Add("Perth");
comboBox2.Items.Add("Melborn");
}
else if (comboBox1.SelectedItem.ToString() == "United States")

comboBox2.Items.Add("NewYork");
comboBox2.Items.Add("Los Ageles");
comboBox2.Items.Add("California");
comboBox2.Items.Add("LosBegas");

}
}

After that choosing State name he/she will get the location in ComboBox 3. Like in
following figure.

Code for ComboBox2 is given below write that code on Combobox2 Selected Index
Changed

private void comboBox2_SelectedIndexChanged(object sender,


EventArgs e)
{
comboBox3.Items.Clear();
comboBox3.Enabled = true;
if (comboBox2.SelectedItem.ToString() == "NewDelhi")
{
comboBox3.Items.Add("East Delhi");
comboBox3.Items.Add("West Delhi");
comboBox3.Items.Add("North Delhi");
comboBox3.Items.Add("South Delhi");
}
else if (comboBox2.SelectedItem.ToString() == "Chennai")
{
comboBox3.Items.Add("Chennai");
}
else if (comboBox2.SelectedItem.ToString() == "Mumbai")
{
comboBox3.Items.Add("Mumbai");
comboBox3.Items.Add("Navi Mumbai");
}
else if (comboBox2.SelectedItem.ToString() == "Banglore")
{
comboBox3.Items.Add("Banglore");

}
else if (comboBox2.SelectedItem.ToString() == "Johnsberg")
{
comboBox3.Items.Add("Johnsberg");
}
else if (comboBox2.SelectedItem.ToString() == "Sydney")
{
comboBox3.Items.Add("Sydney");
}
else if (comboBox2.SelectedItem.ToString() == "Perth")
{
comboBox3.Items.Add("Perth");
}
}

Code for Save Button Click

private void button1_Click(object sender, EventArgs e)


{
string output;
output = "Name: " + this.textBox1.Text + "\r\n";
output += "Address : " + this.textBox2.Text + "\r\n";
output += "
" + this.textBox3.Text + "\r\n";

output += "
" + this.comboBox3.Text+ "\r\n";
output += "
" + this.comboBox2.Text + "\r\n";
output += "Country: " + this.comboBox1.Text + "\r\n";
textBox4.Text = output;
}

Final you will get output Like this.

The ListView Control


The list from which you select files to open in the standard dialog boxes in Windows is a
ListView control Everything you can do to the view in the standard list view dialog (large
icons, details view, and so on). The list view is usually used to present data where the user
is allowed some control over the detail and style of the presentation. It is possible to display
the data contained in the control as columns and rows much like in a grid, as a single
column or in with varying icon representations. The most commonly used list view is like the
one seen above which is used to navigate the folders on a computer.
ListView Control Property

Name
Activation

Availabilit
y

Description

Read/Write By using this property, you can control how a


user activates an item in the list view. You
should not change the default setting unless you

have a good reason for doing so, because you


will be altering a setting that the user have set
for his or her entire system. The possible values
are: Standard: This setting is that which the
user has chosen for his or her machine.
OneClick: Clicking an item activates it.
TwoClick: Double-clicking an item activates it.

Alignment

his property allows you to control how the items


in the list view are aligned. The four possible
values are:
Default: If the user drags and drops an item it
remains where he or she dropped it.
Read/Write Left: Items are aligned to the left edge of the
ListView control.
Top: Items are aligned to the top edge of the
ListView control.
SnapToGrid: The ListView control contains an
invisible grid to which the items will snap.

AllowColumn
Reorder

If you set this property to true, you allow the


user to change the order of the columns in a list
view. If you do so, you should be sure that the
Read/Write
routines that fill the list view are able to insert
the items properly, even after the order of the
columns is changed.

AutoArrange

If you set this property to true, items will


automatically arrange themselves according to
the Alignment property. If the user drags an item
to the center of the list view, and Alignment is
Read/Write
Left, then the item will automatically jump to the
left of the list view. This property is only
meaningful if the View property is LargeIcon or
SmallIcon.

CheckBoxes

If you set this property to true, every item in the


list view will have a CheckBox displayed to the
Read/Write
left of it. This property is only meaningful if the
View property is Details or List.

CheckedIndice
s

Read-only

These two properties gives you access to a


collection of indices and items, respectively,
containing the checked items in the list.

Columns

Read-only

A list view can contain columns. This property


gives you access to the collection of columns
through which you can add or remove columns.

FocusedItem

Read-only

This property holds the item that has focus in


the list view. If nothing is selected, it is null.

FullRowSelect

When this property is true, and an item is


clicked, the entire row in which the item resides
Read/Write
will be highlighted. If it is false, only the item
itself will be highlighted.

GridLines

Read/Write Setting this property to true will cause the list

CheckedItems

view to draw grid lines between rows and


columns. This property is only meaningful when
the View property is Details.

HeaderStyle

You can control how the column headers are


displayed. There are three styles:
Clickable: The column header works like a
Read/Write button.
NonClickable: The column headers do not
respond to mouse clicks.
None: The column headers are not displayed.

When this property is true, the user can select


HoverSelection Read/Write an item in the list view by hovering the mouse
pointer over it.
Items

Read-only

The collection of items in the list view.

LabelEdit

Read/Write

When this property is true, the user can edit the


content of the first column in a Details view.

LabelWrap

Read/Write

If this property is true, labels will wrap over as


many lines is needed to display all of the text.

This property holds the ImageList, which holds


LargeImageList Read/Write large images. These images can be used when
the View property is LargeIcon.
Set this property to true to allow the user to
select multiple items.

MultiSelect

Read/Write

Scrollable

Read/Write Set this property to true to display scrollbars.

SelectedIndice
s

Read-only

SelectedItems

These two properties contain the collections


that hold the indices and items that are selected,
respectively.

When the View property is SmallIcon this


SmallImageList Read/Write property holds the ImageList that contain the
images used.

Sorting

You can allow the list view to sort the items it


contains. There are three possible modes:
Read/Write Ascending
Descending
None

The ImageList contains masks for images that


are used as overlays on the LargeImageList and
StateImageList Read/Write
SmallImageList images to represent
custom states.
TopItem

Read-only

Returns the item at the top of the list view.

View

Read/Write A list view can display its items in four


different modes:
LargeIcon: All items are displayed with a large
icon (32x32) and a label.
SmallIcon: All items are displayed with a small
icon (16x16) and a label.
List: Only one column is displayed. That column
can contain an icon and a label

Details: Any number of columns can be


displayed. Only the first column can contain an
icon.

ListView Methods
Name

Description

By calling this method, you tell the list view to stop drawing
updates until EndUpdate is called. This is useful when you are
BeginUpdate
inserting many items at once, because it stops the view from
flickering and dramatically increases speed.
Clear

Clears the list view completely. All items and columns are
removed.

EndUpdate

Call this method after calling BeginUpdate. When you call this
method, the list view will draw all of its items.

EnsureVisibl When you call this method, the list view will scroll itself to make
e
the item with the index you specified visible.
GetItemAt

Returns the item at position x, y in the list view.

ListView Events
Name

Description

AfterLabelEdit This event occurs after a label have been edited


BeforeLabelEdi
This event occurs before a user begins editing a label
t
ColumnClick

This event occurs when a column is clicked

ItemActivate

Occurs when an item is activated

ListViewItem
The ListViewItem holds information such as text and the index of the icon to display.
ListViewItems have a collection called SubItems that holds instances of another class,
ListViewSubItem. These sub items are displayed if the ListView control is in Details mode.
ColumnHeader
To make a list view display column headers, you add instances of a class called
ColumnHeader to the Columns collection of the ListView. ColumnHeaders provide a caption
for the columns that can be displayed when the ListView is in Details mode.
The ImageList Control

The ImageList control provides a collection that can be used to store images that is used in
other controls on your form. You can store images of any size in an image list, but within
each control every image must be of the same size. In the case of the ListView, which
means that you need two ImageList controls to be able to display both large and small
images.
Example of Listview Control
For using Listview Control make your window form design view like following image. And
change controls property according to your choice. Take
2 listimage Control name as
Large_Image and small_image and add images in that collection property and set
large_image size 32X32.

Write code on Form Loading for holding folders like below


private System.Collections.Specialized.StringCollection folderCol;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)

folderCol = new
System.Collections.Specialized.StringCollection();
CreateHeadersAndFillListView();
PaintListView(@"D:\");
folderCol.Add(@"D:\");
this.lwFilesAndFolders.ItemActivate += new
System.EventHandler(this.lwFilesAndFolders_ItemActivate);
}

Code for Creating Header and ListView in ListView Control.

private void CreateHeadersAndFillListView()


{
ColumnHeader colHead;
// First header
colHead = new ColumnHeader();

colHead.Text = "Filename";
this.lwFilesAndFolders.Columns.Add(colHead); // Insert
the header
// Second header
colHead = new ColumnHeader();
colHead.Text = "Size";
this.lwFilesAndFolders.Columns.Add(colHead); // Insert
the header
// Third header
colHead = new ColumnHeader();
colHead.Text = "Last accessed";
this.lwFilesAndFolders.Columns.Add(colHead); // Insert
the header
}

Code for ListView


private void PaintListView(string root)
{
try
{
// Two local variables that is used to create the items
to insert
ListViewItem lvi;
ListViewItem.ListViewSubItem lvsi;
// If there's no root folder, we can't insert anything
if (root.CompareTo("") == 0)
return;
// Get information about the root folder.
System.IO.DirectoryInfo dir = new
System.IO.DirectoryInfo(root);
// Retrieve the files and folders from the root folder.
DirectoryInfo[] dirs = dir.GetDirectories(); // Folders

FileInfo[] files = dir.GetFiles();

// Files

// Clear the ListView. Note that we call the Clear


method on the
// Items collection rather than on the ListView itself.
// The Clear method of the ListView remove
everything, including column
// headers, and we only want to remove the items
from the view.
this.lwFilesAndFolders.Items.Clear();
// Set the label with the current path
this.lblCurrentPath.Text = root;
// Lock the ListView for updates
this.lwFilesAndFolders.BeginUpdate();
// Loop through all folders in the root folder and insert
them
foreach (System.IO.DirectoryInfo di in dirs)
{
// Create the main ListViewItem
lvi = new ListViewItem();
lvi.Text = di.Name; // Folder name
lvi.ImageIndex = 0; // The folder icon has index 0
lvi.Tag = di.FullName; // Set the tag to the
qualified path of the
// folder
// Create the two ListViewSubItems.

this column

lvsi = new ListViewItem.ListViewSubItem();


lvsi.Text = ""; // Size - a folder has no size and so
// is empty
lvi.SubItems.Add(lvsi); // Add the sub item to the

ListViewItem
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = di.LastAccessTime.ToString(); // Last
accessed column
lvi.SubItems.Add(lvsi); // Add the sub item to the
ListViewItem
// Add the ListViewItem to the Items collection of
the ListView
}

this.lwFilesAndFolders.Items.Add(lvi);

// Loop through all the files in the root folder


foreach (System.IO.FileInfo fi in files)
{
// Create the main ListViewItem
lvi = new ListViewItem();
lvi.Text = fi.Name; // Filename
lvi.ImageIndex = 1; // The icon we use to
represent a folder has
// index 1
lvi.Tag = fi.FullName; // Set the tag to the qualified
path of the
// file
// Create the two sub items

file

lvsi = new ListViewItem.ListViewSubItem();


lvsi.Text = fi.Length.ToString(); // Length of the
lvi.SubItems.Add(lvsi); // Add to the SubItems

collection
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = fi.LastAccessTime.ToString(); // Last
Accessed Column
lvi.SubItems.Add(lvsi); // Add to the SubItems

collection
// Add the item to the Items collection of the
ListView
}

this.lwFilesAndFolders.Items.Add(lvi);

// Unlock the ListView. The items that have been


inserted will now
// be displayed
this.lwFilesAndFolders.EndUpdate();
}
catch (System.Exception err)
{
MessageBox.Show("Error: " + err.Message);
}

Code for Listview Control for activating items


private void lwFilesAndFolders_ItemActivate(object sender, EventArgs e)
{
// Cast the sender to a ListView and get the tag of the first
selected
// item.
System.Windows.Forms.ListView lw =
(System.Windows.Forms.ListView)sender;
string filename = lw.SelectedItems[0].Tag.ToString();
if (lw.SelectedItems[0].ImageIndex != 0)
{
try
{
// Attempt to run the file
System.Diagnostics.Process.Start(filename);
}
catch

// If the attempt fails we simply exit the method


return;

}
else
{
// Insert the items
PaintListView(filename);
folderCol.Add(filename);
}
}

Code for making small icons view. Write below code on radio
button named small icon
private void rdoSmallIcon_CheckedChanged(object sender,
EventArgs e)

RadioButton rdb = (RadioButton)sender;


if (rdb.Checked)
this.lwFilesAndFolders.View = View.List;

Code for making large icons view. Write below code on radio
button named large icon
private void rdoLargeIcon_CheckedChanged(object sender,
EventArgs e)
{
RadioButton rdb = (RadioButton)sender;
if (rdb.Checked)
this.lwFilesAndFolders.View = View.LargeIcon;
}

StatusBar Control
A status bar is commonly used to provide hints for the selected item or information about an
action currently being performed on a dialog. Normally, the StatusBar is placed at the
bottom of the screen, as it is in MS Office applications and Paint, but it can be located
anywhere you like.

StatusBar Properties

Name

Availabilit
y

Description

BackgroundImag
Read/Write
e

It is possible to assign an image to the


status bar that will be drawn in the
background.

Panels

Read-only

This is the collection of panels in the status


bar. Use this collection to add and remove
panels.

ShowPanels

Read/Write

If you want to display panels, this property


must be set to true.

Text

Read/Write

When you are not using panels this


property holds the text that is displayed in
the status bar.

StatusBar Events
Name

Description

DrawItem

Occurs when a panel that has the OwnerDraw style set needs
to be redrawn. You must subscribe to this event if you want to
draw the contents of a panel yourself.

PanelClick

Occurs when a panels is clicked.

The StatusBarPanel Class


This class contains all the information about the individual panels in the Panels collection.
The information that can be set ranges from simple text and alignment of text to icons to be
displayed and the style of the panel.

Example For StatusBar


To understanding StatusBar control drag and drop status strip and make text blank and add
2toolstatuslabel and 1 toolstatusprogressbar. And drag 1textbox and 1 button,1timer control
and change property according to your choice.

Code for button click on go button


private void button1_Click_1(object sender, EventArgs
e)
{
toolStripProgressBar1.Visible = true;
toolStripStatusLabel2.Text = "";
timer1.Enabled = true;

webBrowser1.Navigate(textBox1.Text);
toolStripStatusLabel1.Text = textBox1.Text;
}

On clicking button progress bar will show on status strip control until webpage will not open.
when web page is loaded progress bar will not be display and label text will be web address
and done that means page has been loaded as shown below

Code for timer Control


private void timer1_Tick(object sender, EventArgs e)
{
10;

toolStripProgressBar1.Value = toolStripProgressBar1.Value +

if (toolStripProgressBar1.Value ==
toolStripProgressBar1.Maximum)
{
toolStripProgressBar1.Value= 0;
toolStripProgressBar1.Visible = false;
timer1.Enabled = false;

toolStripStatusLabel2.Text = "Done";

Write following code on document complete event of


WebbrowserControl so that progressbar stops
private void webBrowser1_DocumentCompleted(object
sender,
WebBrowserDocumentCompletedEventArgs e)
{
toolStripProgressBar1.Visible = false;
}

Tabcontrol Control
The TabControl provides an easy way of organizing a dialog into logical parts that can be
accessed through tabs located at the top of the control. A TabControl contains TabPages that
essentially work in a similar way to a GroupBox control, though it is somewhat more
complex:

TabControl Properties

Name

Availabilit
y

Description

Alignment

Read/Write

Controls where on the tab control the tabs are


displayed. The default is at the top.

Appearance

Read/Write

Controls how the tabs are displayed. The tabs


can be displayed as normal buttons or with flat
style.

HotTrack

Read/Write

If this property is set to true the appearance of


the tabs on the control change as, the mouse
pointer passes over them.

Multiline

Read/Write

If this property is set to true, it is possible to


have several rows of tabs.

RowCount

Read-only

Returns the number of rows of tabs that is


currently displayed.

SelectedInde
Read/Write
x

Returns or sets the index of the selected tab.

TabCount

Read-only

Returns the total number of tabs.

TabPages

Read-only

This is the collection of TabPages in the control.


Use this collection to add and remove TabPages.

Working with TabControl


Drag and drop a TabControl and add pages as show in below picture.

Now change the text property of the TabControl tab page as shown in below
picture.
Design according to your choice or shown in below image.

Code for picking date- for this add a month calendar and make visibility false and true its
visibility on PickDate button click.

private void button1_Click(object sender, EventArgs e)


{
monthCalendar1.Visible = true;
}

private void monthCalendar1_DateChanged(object sender,


DateRangeEventArgs e)
{
textBox3.Text = DateTime.Now.ToLongDateString();
monthCalendar1.Visible = false;
}

On clicking next button you can move on next TabIndex code for this is given
below-

private void linkLabel1_LinkClicked(object sender,


LinkLabelLinkClickedEventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text
== "")
{
MessageBox.Show("Please fill your personal information");
}
else
{
this.tabControl1.SelectedIndex = 1;
}

Code for previous button Click

private void linkLabel3_LinkClicked(object sender,


LinkLabelLinkClickedEventArgs e)
{
this.tabControl1.SelectedIndex = 0;
}

NotifyIcon Control
Display an icon on notification area with corresponding to the application is running. Like
shown in below example.

Properties of NotifyIcon

Events of Notify Icon

Code for mouse double click event on NotifyIcon

private void notifyIcon1_MouseDoubleClick(object sender,


MouseEventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
// Activate the form.
this.Activate();
this.Focus();
}

On double-clicking Icon to tab control application you get your application as on desktop.

Masked Textbox
Sets the string governing the input allowed for this control. Masked TextBox is intelligent
user control enhances the function of the TextBox control, which can mask the Date, IP
Address, SSN, Phone numbers, digits, decimal and checks the validation, and automatically
set the delimiter location. The property Masked is set to None by default and the control
works like a normal TextBox control. If setting the property to Date Only, the control is
masked to Date format.
Like shown in below Image:

Code for Ok Button Click

private void button1_Click(object sender,


EventArgs e)
{
label2.Text = label2.Text +
maskedTextBox1.Text;
}

Window Media Player


You will not find the window media player control on toolbox list, so you have to add this
control on rightclick on tool box and select option choose item as shown in below picture.

After this you will get another window for choosing toolbox item go to COM component
panel and check window media player item and then click ok button. This control will add on
your Visual Studio Framework toolbox list.

Now you can drag and drop window media player control from toolbox list.

Code for playing a song on window media player.

private void Form1_Load(object sender, EventArgs e)


{
axWindowsMediaPlayer1.URL = @"D:\Documents and
Settings\R4R\My Documents
\Downloads\aakrosh02(www.songs.pk).mp3";
}

Dialog Controls

Code for New Button


private void newToolStripMenuItem_Click(object sender,
EventArgs e)
{

if (richTextBox1.Modified)
{
DialogResult result = MessageBox.Show("Do you wish

to Save
changes?", "Save Changes",
MessageBoxButtons.YesNoCancel);

if (result == DialogResult.Yes)
saveToolStripMenuItem_Click(sender, e);
else if (result == DialogResult.No)
{
richTextBox1.Text = "";
}
if (result == DialogResult.Cancel)
{
}
}
}

Code For Open Button


private void openToolStripMenuItem_Click(object sender,
EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
saveFileDialog1.FileName =
openFileDialog1.FileName;
}
}

Code for Save Button


private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog1.FileName != "")
{
richTextBox1.SaveFile(saveFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
else

saveAsToolStripMenuItem_Click(sender, e);

}
}

Code for Save As Button


private void saveAsToolStripMenuItem_Click(object sender,
EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(saveFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
}

Code for Exit Button


private void exitToolStripMenuItem_Click(object sender,
EventArgs e)
{
if (richTextBox1.Modified)
{
DialogResult result = MessageBox.Show
("Do you wish to Save changes?", "Save Changes",
MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
saveToolStripMenuItem_Click(sender, e);
else
if (result == DialogResult.Cancel)
{
}
}
this.Close();
}

Code for Form Closing

private void Form1_FormClosing(object sender, FormClosingEventArgs e)


{
if (richTextBox1.Modified)
{
DialogResult result = MessageBox.Show("Do you wish to Save
changes?", "Save Changes",
MessageBoxButtons.YesNoCancel);

if (result == DialogResult.Yes)
saveToolStripMenuItem_Click(sender, e);
else
if (result == DialogResult.Cancel)
e.Cancel = true;

Printing Controls
These controls are used to take printing of documents whether in form of print screen or as
printing in the content form . In following figure i tried to describe about these controls how
you will use in your window application.
For explaining this i had taken the previous example of dialog control, so lets proceed with
printing controls.

Code for Print Preview- For performing this action first add
namespaceusing System.Drawing.Printing;

e)

PrintDocument PrintDoc1 = new PrintDocument();


PrintPreviewDialog PrintPreviewDialog1 = new PrintPreviewDialog();
private void printToolStripMenuItem_Click(object sender, EventArgs
{

PrintPreviewDialog1.Document = PrintDoc1;
PrintDoc1.OriginAtMargins = true; //To set or Get the Position of a
Graphic Object

PrintDoc1.PrintPage += PDoc_PrintPage;
PrintPreviewDialog1.ShowDialog();
}
Create Method
private void PDoc_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bmp = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bmp, this.ClientRectangle);
this.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width,
bmp.Height)); //Takes the Snap of
the Exact WindowForm size as Bitmap image
e.Graphics.DrawImage(bmp, 0, 0);
}

Code for taking Print

private void printToolStripMenuItem1_Click(object sender,


EventArgs e)
{
}

PrintDoc1.Print();

Data Controls
For understanding data controls design form like shown in below picture and take datagrid
view control from toolbox. And add new database from solution explorer by choosing new
item.
Add namespace-

using System.Data.SqlClient;
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename= D:\Documents
and Settings\R4R\My Documents\Visual Studio 2008\Projects\WindowsFormsApplication14
\WindowsFormsApplication14\r4r.mdf;Integrated Security=True;User Instance=True");

Now i want to insert record in database by clicking on insert button. Code for this is given
belowCode for inserting Data in Database-

private void button1_Click(object sender, EventArgs e)


{
SqlCommand com = new SqlCommand("insert into emp_detail
values('"+textBox1.Text+
"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')",con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}

Code for viewing the total record in DataGridview by clicking the view button

private void button4_Click(object sender, EventArgs e)


{
SqlCommand com2 = new SqlCommand("select * from
emp_detail",con);
SqlDataAdapter da = new SqlDataAdapter(com2);
DataSet ds = new DataSet();
con.Open();
da.Fill(ds, "emp_detail");
con.Close();
dataGridView1.DataSource = ds.Tables[0];
}

Code for Updating the record from dataGrid View.

string name, address, sal, cont;


private void button2_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in
dataGridView1.SelectedRows)
{
if (row.Index != dataGridView1.Rows.Count)
{
id =
dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
name=
dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
address =
dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
sal =
dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
cont =
dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
dataGridView1.Rows.RemoveAt(row.Index);
}
}

SqlCommand com3 = new SqlCommand


("update emp_detail set emp_name='"+name+"',emp_address='"+
address+"',emp_sal='"+sal+"',emp_cont='"+cont+"' where emp_id
='" + id + "'", con);
con.Open();
com3.ExecuteNonQuery();
con.Close();
}

Code for Deleting the recording from Datagridview control-

private void button3_Click(object sender, EventArgs e)


{
foreach (DataGridViewRow row in
dataGridView1.SelectedRows)
{
if (row.Index != dataGridView1.Rows.Count)
{
id =
dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
dataGridView1.Rows.RemoveAt(row.Index);
}
}
SqlCommand com3 = new SqlCommand("delete from
emp_detail where emp_id ='"+id+"'",con);
con.Open();
com3.ExecuteNonQuery();
con.Close();
}

Error Provider Control


This control provides a user interface that indicates to user that a control on a form has
error associated with it. In other had it works as validation upon the controls to handle the
error causes by inputting wrong by user.
Drag this control as shown in below picture -

Adding error provider control on textbox for blank not allowWrite this code on textbox validating event- Output will shown in below picture if user
leave name blank.

private void textBox1_Validating(object sender, CancelEventArgs


e)
{
ValidateName();
}
private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == "")
{
errorProvider1.SetError(textBox1, "Please enter your
Name");
bStatus = false;
}
else
errorProvider1.SetError(textBox1, "");
return bStatus;
}

Validating for age. For validating age i have covered three conditions for validate
1-If user leave this blank.
2-If entered age is less than 18.
3-If user input character value in place of numeric.
Write this code on Textbox2 validating Event-

private void textBox2_Validating(object sender, CancelEventArgs e)


{
ValidateAge();
}
private bool ValidateAge()
{
bool bStatus = true;
if (textBox2.Text == "")
{
errorProvider1.SetError(textBox2, "Please enter your Age");
bStatus = false;
}
else
{
errorProvider1.SetError(textBox2, "");
try
{
int temp = int.Parse(textBox2.Text);
errorProvider1.SetError(textBox2, "");
if (temp < 18)
{
errorProvider1.SetError(textBox2, "You must be atleast 18
years old to setup a test");
bStatus = false;
}
else
{
errorProvider1.SetError(textBox2, "");
}
}
catch
{
errorProvider1.SetError(textBox2, "Please enter your age as a
number");
bStatus = false;
}
}
return bStatus;
}

Output of this error provider is shown below-

Using error provider control on DatetimePicker Control


If user select weekend day for test then he will get error message- Like shown in below
picture

private void dateTimePicker1_Validating(object sender, CancelEventArgs e)


{
ValidateTestDate();
}
private bool ValidateTestDate()
{
bool bStatus = true;
if ((dateTimePicker1.Value.DayOfWeek ==DayOfWeek.Sunday) ||
(dateTimePicker1.Value.DayOfWeek
==DayOfWeek.Saturday))
{
errorProvider1.SetError (dateTimePicker1, "Appointment cannot be
scheduled in
the weekend. Please select a weekday");
bStatus = false;
}
else
errorProvider1.SetError (dateTimePicker1, "");
return bStatus;
}

Write above code on DatetimePicker Validating Event.

Help Provider
This control is used to provide pop-up and online help to user on pressing F1 key. Drag and
Drop Help provider as show in below picture.

Code for using Help Provider- Write following code on Page load Event.

private void Form1_Load(object sender, EventArgs e)


{
helpProvider1.SetHelpString(textBox1,"Enter your Name
");
helpProvider1.SetHelpString(textBox2, "Enter your Age");
helpProvider1.SetHelpString(dateTimePicker1,"Pich date
for giving test");
}

You will get output as shown below picture on pressing F1 key.

Crystal Report
Crystal Report is used to generate the report of database for taking preview and printout of
that particular data or report. Add crystal in your application by choosing new item you will
get new window like below and select reporting => then crystal report.

You can customize report according to your choice by the use of CrystalReport toolbox.
Choose database from field explorer window as shown below-

Now add fields in your report those you want to show in your report as shown below.

Drag and drop crystal report viewer from toolbox and set property that you want to
customize your CrystalReport.

Code for to show crystal report Form- write following code on View CrystalReport
Button.

private void linkLabel1_LinkClicked(object sender,


LinkLabelLinkClickedEventArgs e)
{
Crystal c = new Crystal();
c.ShowDialog();
}

Code for calling CrystalReport- Write following code on CrystalReport Page load event.

private void Crystal_Load(object sender, EventArgs e)


{
CrystalReport1 cryRpt = new CrystalReport1();
cryRpt = new CrystalReport1();
cryRpt.Load("\\preview_invoice_report.rpt");
crystalReportViewer1.ReportSource = cryRpt;
crystalReportViewer1.Refresh();
}

Report will generate as shown below-

Flow Layout Panel


The FlowLayoutPanel control is a container control where child controls are added, then
dynamically repositioned to flow in a particular direction. The FlowLayoutPanel automatically
positions all child controls in the direction indicated by the value of the FlowDirection
property.
Useful properties
AutoScroll - This property when set to true, allows scroll bars to be displayed.

BackColor - The background color of the Panel is defaulted to


System.Drawing.SystemColors.Control, but this can be set to any color you like.
BackgroundImage - Instead of a single color, an image can be displayed as the
background.
BorderStyle - This property determines if the panel is outlined with no visible border
(None), a plain line (FixedSingle), or a shadowed line (Fixed3D).
Controls - Gets the collection of controls contained within the control.
Enabled - If this property is set to false, the controls contained within the Panel will also be
disabled.
FlowDirection - Gets or sets a value indicating the flow direction of the FlowLayoutPanel
control. This property takes a value from the FlowDirection enumeration, the default value is
LeftToRight:
BottomUp - Elements flow from the bottom of the design surface to the top.
LeftToRight - Elements flow from the left edge of the design surface to the right.
RightToLeft - Elements flow from the right edge of the design surface to the left.
TopDown - Elements flow from the top of the design surface to the bottom.
TabIndex - Gets or sets the tab order of the control within its container.
TabStop - Gets or sets a value indicating whether the user can give the focus to this control
using the TAB key.
WrapContents - Gets or sets a value indicating whether the FlowLayoutPanel control
should wrap its contents or let the contents be clipped.
Useful methods
GetFlowBreak - Returns a value that represents the flow-break setting of the
FlowLayoutPanel control.
SetFlowBreak - Sets the value that represents the flow-break setting of the FlowLayoutPanel
control.
Example- First drag and drop FloyLayout Panel and add controls like- label->textbox>label->textbox->button. You will see that your controls are adding from left to right
because by default Flawlayout Panel Property i.e.. FlowDirection is left to right. So for
understanding this i have taken one checkbox to make wrapping controls in Flow layout
panel. By default it is false in Flow layout panel.

Code for check box event for wrapping control

private void checkBox1_CheckedChanged(object sender,


EventArgs e)
{
flowLayoutPanel1.WrapContents = true;
}

Table Layout Panel


The TableLayoutPanel control is a container control where child controls are added within a
table structure. Each cell in the table contains a single control, unless a container such as a
Panel is added first.
Useful properties
CellBorderStyle - This property determines if the cell is outlined with a border or not. A
value from the TableLayoutPanelCellBorderStyle enumeration is required, the default value is
None:
Inset - A single-line sunken border.
InsetDouble - A double-line sunken border.
None - No borders.

Outset - A single-line raised border.


Outset Double - A double-line raised border.
OutsetPartial - A single-line border containing a raised portion.
Single - A single-line border.
ColumnCount - Determines the number of columns in the table.
ColumnStyles - A collection of column styles, one for each column in the TableLayoutPanel
control.
Controls - Gets the collection of controls contained within the control.
GrowStyle - Determines whether the control should expand to accommodate new cells
when all existing cells are occupied. A value from the TableLayoutPanelGrowStyle
enumeration is required, the default value is AddRows:

AddColumns - The TableLayoutPanel gains additional columns after it is full.

AddRows - The TableLayoutPanel gains additional rows after it is full.

FixedSize - The TableLayoutPanel does not allow additional rows or columns after it is
full.

RowCount - Determines the number of rows in the table.

RowStyles - A collection of row styles, one for each row in the TableLayoutPanel
control.

Example

This dialog allows you to edit the SizeType property of each of the Columns and Rows in the
TableLayoutPanel. The SizeType property determines how the Height (RowStyle) or Width
(ColumnStyle) should be interpreted. A value from the SizeType enumeration is required,
the default value is Percent:

Absolute - The row or column should be sized to an exact number of pixels.

AutoSize - The row or column should be automatically sized to share space with its
peers.

Percent - The row or column should be sized as a percentage of the parent container.

Adding a TableLayoutPanel manually

// Create TableLayoutPanel
TableLayoutPanel tlp = new TableLayoutPanel();

// Set the BorderStyle to Inset


tlp.CellBorderStyle =
TableLayoutPanelCellBorderStyle.Inset;
// Grid has two columns
tlp.ColumnCount = 2;
// Grid has two rows
tlp.RowCount = 2;
// If grid is full add extra cells by adding column
tlp.GrowStyle =
TableLayoutPanelGrowStyle.AddColumns;
// Padding (pixels)within each cell (left, top, right,
bottom)
tlp.Padding = new Padding(1, 1, 4, 5);
// Add TableLayoutPanel to the Forms controls
this.Controls.Add(tlp);

Adding controls manually


Adding a control to a TableLayoutPanel at run time can be done in a couple of ways. Simply
using the Add method with just the name of the control adds the control to the first
available cell.

// Create buttons
Button button1 = new Button();
button1.Text = "Click Me";
// Add buttons to
TableLayoutPanel
tlp.Controls.Add(button1);

Panel Control
The Panel control is a container for other controls, customarily used to group related
controls. Panels are used to subdivide a form by function, giving the user a logical visual cue
of control grouping.
Useful properties

AutoScroll - This property when set to true, allows scroll bars to be displayed.

BackColor - The background color of the Panel is defaulted to


System.Drawing.SystemColors.Control, but this can be set to any color you like.

BackgroundImage - Instead of a single color, an image can be displayed as the


background.

BorderStyle - This property determines if the panel is outlined with no visible border
(None), a plain line (FixedSingle), or a shadowed line (Fixed3D).

Controls - Gets the collection of controls contained within the control.

Enabled - if this property is set to false, the controls contained within the Panel will
also be disabled.

TabIndex - Gets or sets the tab order of the control within its container. (inherited
from Control)

TabStop - Gets or sets a value indicating whether the user can give the focus to this
control using the TAB key.

Add a control to a Panel manually

public void CreateMyPanel()


{
Panel panel1 = new Panel();
TextBox textBox1 = new TextBox();
Label label1 = new Label();

// Initialize the Panel control.


panel1.Location = new Point(56,72);
panel1.Size = new Size(264, 152);
// Set the Borderstyle for the Panel to three-dimensional.
panel1.BorderStyle =
System.Windows.Forms.BorderStyle.Fixed3D;
// Initialize the Label and TextBox controls.
label1.Location = new Point(16,16);
label1.Text = "label1";
label1.Size = new Size(104, 16);
textBox1.Location = new Point(16,32);
textBox1.Text = "";
textBox1.Size = new Size(152, 20);
// Add the Panel control to the form.
this.Controls.Add(panel1);
// Add the Label and TextBox controls to the Panel.
panel1.Controls.Add(label1);
panel1.Controls.Add(textBox1);
}

Split Container Control


This control is an advance window's control or it is an extended version of old splitter
control. You can place it at form horizontally or vertically by specifying Orientation property
each represents left/top and right/bottom panels respectively.
The SplitContainer control can be thought of as a composite control; effectively it is two
Panel controls separated by a movable bar (also known as a splitter bar). When the mouse
pointer is over the bar, the pointer changes shape to show that the bar can be moved.
Useful properties

AutoScroll: This property when set to true, allows scroll bars to be displayed.

BackColor: The background color of the SplitContainer is defaulted to


System.Drawing.SystemColors.Control, but this can be set to any color you like. The
whole of the SplitContainer changes color, however, each Panel can have its own
background color.

BackgroundImage: Instead of a single color, an image can be displayed as the


background. The image only appears in the splitter bar.

BorderStyle: This property determines if the panel is outlined with no visible border
(None), a plain line (FixedSingle), or a shadowed line (Fixed3D).

Dock: Determines which SplitContainer borders are attached to the edges of the
container. When a SplitContainer control is dropped onto a container, this property
defaults to Fill.

FixedPanel: Determines which SplitContainer panel remains the same size when the
container is resized. This property takes a value from the FixedPanel enumeration,
the default value is None:

None: Specifies that neither SplitContainer.Panel1, SplitContainer.Panel2 is fixed. A


Control.Resize event affects both panels.

Panel1: Specifies that SplitContainer.Panel1 is fixed. A Control.Resize event affects


only SplitContainer.Panel2.

Panel2: Specifies that SplitContainer.Panel2 is fixed. A Control.Resize event affects


only SplitContainer.Panel1.

IsSplitterFixed: Gets or sets a value indicating whether the splitter is fixed or


movable.

Orientation:Gets or sets a value indicating the Horizontal or Vertical orientation of


the SplitContainer panels.

Panel1: Gets the left panel of a vertical SplitContainer or the top panel of a
horizontal SplitContainer. When you click on this property in the IDE properties pane,
you can edit the properties of the underlying Panel.

Panel1Collapsed: Determines whether Panel1 is collapsed or expanded. When this


value is true, Panel1 is hidden and Panel2 expands to fill the SplitContainer. This
property is mutually exclusive with Panel2Collapsed.

Panel1MinSize: Determines the minimum distance in pixels of the splitter from the
left or top edge of Panel1.

Panel2: Gets the right panel of a vertical SplitContainer or the bottom panel of a
horizontal SplitContainer. When you click on this property in the IDE properties pane,
you can edit the properties of the underlying Panel.

Panel2Collapsed: Determines whether Panel2 is collapsed or expanded. When this


value is true, Panel2 is hidden and Panel1 expands to fill the SplitContainer. This
property is mutually exclusive with Panel1Collapsed.

Panel2MinSize: Determines the minimum distance in pixels of the splitter from the
right or bottom edge of Panel2.

SplitterDistance: Determines the location of the splitter, in pixels, from the left
(Orientation = Vertical) or top (Orientation = Horizontal) edge of the SplitContainer.

SplitterIncrement: Gets or sets a value representing the increment of splitter


movement in pixels.

SplitterRectangle: Gets the size and location of the splitter relative to the
SplitContainer.

SplitterWidth: Determines the width of the splitter in pixels.

DateTimePicker and Month Calendar


DateTimePicker

DateTimePicker is ideal for choosing a single date and/or time value and requires the same
amount of space as an ordinary drop-down list box. When the user clicks the drop-down
button, a month calendar appears. The operation of the control from this point is exactly the
same as the MonthCalendar control.

Useful properties

BackColor - Indicates the background color of the DateTimePicker control.

CustomFormat - Determines the custom date/time format string.

DropDownAlign - Determines the alignment of the drop-down calendar on the


DateTimePicker control. Takes a value of either Left or Right.

ForeColor - Indicates the foreground color of the DateTimePicker control.

Format - Determines the format of the date and time displayed in the control.

MaxDate - Determines the maximum date and time that can be selected in the
control.

MaximumDateTime - Gets the maximum date value allowed for the DateTimePicker
control.

MinDate - Determines the minimum date and time that can be selected in the
control.

MinimumDateTime - Gets the minimum date value allowed for the DateTimePicker
control.

ShowCheckBox - Indicates whether a check box is displayed to the left of the


selected date.

ShowUpDown - Indicates whether a spin button control (also known as an up-down


control) is used to adjust the date/time value.

Value - Determines the date/time value assigned to the control.

Month Calendar
The MonthCalendar control presents an intuitive graphical interface for users to view and set
date information.

Useful properties

AnnuallyBoldedDates - Determines the array of DateTime objects that determines


which annual days are displayed in bold.

BoldedDates - Contains the array of DateTime objects that determines which


nonrecurring dates are displayed in bold.

CalendarDimensions - Determines the number of columns and rows of months


displayed. You can have multiple months displayed horizontally and vertically.

FirstDayOfWeek - Determines the first day of the week as displayed in the month
calendar. By default, Sunday is shown as the first day of the week.

MaxDate - Determines the maximum allowable date.

MaxSelectionCount - Determines the maximum number of days that can be selected


in a month calendar control.

MinDate - Determines the minimum allowable date.

MonthlyBoldedDates - Contains the array of DateTime objects that determine which


monthly days to bold.

SelectionEnd - Determines the end date of the selected range of dates.

SelectionRange - Determines the selected range of dates for a month calendar


control.

SelectionStart - Determines the start date of the selected range of dates.

ShowToday - Indicates whether the date represented by the TodayDate property is


displayed at the bottom of the control.

ShowTodayCircle - Indicates whether today's date is identified with a circle or square.

ShowWeekNumbers - Indicates whether the month calendar control displays week


numbers (1-52) to the left of each row of days.

SingleMonthSize - Gets the minimum size to display one month of the calendar.

TitleBackColor - Indicates the background color of the title area of the calendar.

TitleForeColor - Indicates the foreground color of the title area of the calendar.

TodayDate - Determines the value that is used by MonthCalendar as today's date.

TodayDateSet - Gets a value indicating whether the TodayDate property has been
explicitly set.

TrailingForeColor - Indicates the color of days in months that are not fully displayed
in the control.

Example

Code for DateTime Picker Control

private void dateTimePicker1_ValueChanged(object sender,


EventArgs e)
{
label1.Text = "DateTimePicker Date: " +
dateTimePicker1.Text;
}

Code for Month Calendar Control

private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)


{
label2.Text = "Month Calender Date : " +
monthCalendar1.SelectionStart.ToLongDateString();

}
NumericUpDown Control
This control is a simple way to give the user a way to select a number that falls between a
minimum and a maximum value. The numeric value can be incremented or decremented by
clicking the up or down buttons of the control. The user can also enter in a value.
NumericUpDown control is controlled by four integer properties:

Minimum, Maximum- Both defines the minimum and maximum values of the
control

Value-

Increment- The Increment property defines the amount by which the current
value is incremented or decremented when the user clicks the up or down arrow
buttons.

This shows the current value of the control.

ValueChanged Event
This event occurs Value property can be changed in code, by clicking the up or down button,
or by the user entering a new value that is read by the control. The new value is read when
the user hits the ENTER key or navigates away from the control. If the user enters a new
value and then clicks the up or down button, the ValueChanged event will occur twice.

ProgressBar and Timer Control


For explaining Progressbar control we have link it with event so that the value of progress
bar can increase, so here i have chosen timer control. And the the value of progressbar
control is increment with timer control tick event.
Progress bar control is used to hide the backend process so that user can aware of time
consumed by back process of that application.

Code for Timer Control Tick Event

private void timer1_Tick(object sender, EventArgs e)


{
progressBar1.Visible = true;
progressBar1.Value = progressBar1.Value + 5;
label3.Visible = true;
label3.Text = "Please Wait While we are checking Authentication...";
if (progressBar1.Value == progressBar1.Maximum)
{

if ((textBox1.Text == "r4r") && (textBox2.Text == "r4r"))


{
timer1.Enabled = false;

progressBar1.Visible = false;
label3.Text = "Welcome!! you are Authorised User.";
progressBar1.Enabled = false;
progressBar1.Value = 0;
groupBox1.Visible = false;
}
else
{

progressBar1.Enabled = false;
timer1.Enabled = false;
progressBar1.Visible = false;
progressBar1.Value = 0;
label3.Text = "Sorry!! Username or Password is Wrong.";

Make Progressbar Control Visible Property "false".


Make timer enabled property true on "OK" button click.

private void button1_Click(object sender, EventArgs e)


{
timer1.Enabled = true;
}

ToolTip Control
ToolTip Control Provides the information to user when user moves mouse pointer over
control. Like shown in below picture.

Adding ToolTip on Controls


Step-1: Drap and drop tooltip control from toolbox to your form in which you want to add .

Step-2: Set the property of ToolTip as shown in below picture.

Step-3: Add tool tip on control in which you want to add. in above picture i have added
ToolTip on textbox control. For this just simple type text on tooltip on ToolTip1 control: "
Enter user name". Like in below picture.

TreeView Control
TreeView Control is used for showing hierarchical structured data visually e.g.. XML.
Example for TreeView Control In shown Below -This is image of Explorer in Windows that
show files and folder in tree view.

Working With TreeView Control


Drag and drop TreeView Control from toolbox, Like shown in below image.

In following example I have taken a tree list view of colleges name for this i have taken
ContextMenuChild and Parent for adding nodes. And you can also add by on clicking add
child button and add sibling event.
Code for Add Child is given Below

private void buttonAddChild_Click(object sender, System.EventArgs e)


{
if (textBox1.Text != "")
AddChildToTheNode();
else
{
MessageBox.Show("Enter the Node Text to be added");
textBox1.Focus();
}
}
private void AddChildToTheNode()
{
TreeNode tnode = new TreeNode(textBox1.Text);
treeView1.SelectedNode.Nodes.Add(tnode);
treeView1.ExpandAll();
if (treeView1.SelectedNode.Nodes.Count > 1 &&
treeView1.SelectedNode.ForeColor != Color.Blue)
treeView1.SelectedNode.ForeColor = Color.Brown;
}

Code for Menu Item Click

private void menuItem2_Click(object sender, System.EventArgs e)


{
if (textBox1.Text != "")

AddChildToTheNode();
else
{
MessageBox.Show("Enter the Node Text to be added");
textBox1.Focus();
}
}

Code for Add Sibling

private void btnAddSibling_Click(object sender, System.EventArgs e)


{
if (textBox1.Text != "")
AddSiblingToTheNode();
else
{
MessageBox.Show("Enter the Node Text to be added");
textBox1.Focus();
}
}
private void AddSiblingToTheNode()
{
TreeNode tnode = new TreeNode(textBox1.Text);
tnode.ForeColor = Color.Brown;
treeView1.SelectedNode.Parent.Nodes.Add(tnode);
}

Code For Deleting Child and Sibling.

private void buttonDeleteParent_Click(object sender, System.EventArgs


e)
{
DeleteNode();
}
private void DeleteNode()
{
if (treeView1.SelectedNode.Nodes.Count == 0)
treeView1.SelectedNode.Remove();
else
MessageBox.Show("First Remove all the child nodes");
}

Menus and ToolBar Controls


In this category following controls comes-

MenuStrip

ToolStrip controls

ContextMenusStrip

StatusStrip

MenuStrip Control
Useful properties

AllowItemReorder (Inherited from ToolStrip) - Gets or sets a value indicating


whether drag-and-drop and item reordering are handled privately by the MenuStrip

class. Set the property to true to allow reordering. At run time, the user holds down
the ALT key and the left mouse button to drag a ToolStripMenuItem to a different
location on the MenuStrip.

AllowMerge (Inherited from ToolStrip) - When enabled, this property allows


multiple-document interface (MDI) children to combine their respective menus in the
MDI parent.

Dock - Gets or sets which edge of the parent container a MenuStrip is docked to.

LayoutStyle - Gets or sets a value indicating how the MenuStrip lays out its items.

Padding (Inherited from Control) - Gets or sets the control's internal spacing
characteristics. The default values for Padding are reasonably close to Windows user
interface guidelines.

RenderMode - Gets or sets the painting styles to be applied to the MenuStrip.

TextDirection (Inherited from ToolStrip) - Allows the text to be rotated within


the button. The property takes one of four values contained in the
ToolStripTextDirection enumeration.
Horizontal - Specifies horizontal text orientation.
Inherit - Specifies that the text direction is inherited from the parent control.
(Default state)
Vertical270 - Specifies that text is to be rotated 270 degrees clockwise.
Vertical90 - Specifies that text is to be rotated 90 degrees clockwise.

ToolStrip Control
The ToolStrip is a container for holding different types of controls that are derived from
ToolStripItem. In the example that we just created, the ToolStrip holds a selection of
buttons which are instances of ToolStripButton. Other items that can be held within the
ToolStrip are:

ToolStripSplitButton

ToolStripDropDownButton

ToolStripLabel

ToolStripProgressBar

ToolStripSeparator

ToolStripComboBox

ToolStripTextBox

A ToolStrip appears by default as Office-style with a flat look. Windows XP themes are
supported however the painting of the control may be overridden.
Adding standard Items in ToolStrip

ContextMenusStrip Control
Applications use two kinds of menusmain menus and context menus. Context menus are
"pop up" menus that provide additional options, usually when the user right-clicks a part of
the window.
Adding Menus in ContextMenusStrip

At runtime, your ContextMenusStrip wont appear. You have two choices to display it. The
easiest approach is to associate it with another control by setting the
Control.ContextMenuStrip property to your ContextMenusStrip object. When the user rightclicks the control, your context menu appears automatically. As shown in Picture.

Background Worker Control


The BackgroundWorker Component allows a form to run an operation asynchronously. This
is very useful when we deal with such kind of operations as database transactions, image
downloads etc.

Adding DoWork
The DoWork method is like any other event handler. Here we must look at the C# view of
your file, where we will see the DoWork method. You should see that the

backgroundWorker1_DoWork event is generated when you double-click on DoWork. For


testing, let's add a Thread.Sleep command there. The Thread.Sleep method will pause the
execution of the BackgroundWorker, but does not consume the entire CPU.

Code For DoWork Event is Given Below

private void backgroundWorker1_DoWork(object sender,


DoWorkEventArgs e)
{
TestObject argumentTest = e.Argument as TestObject;

Thread.Sleep(100);
argumentTest.OneValue = 12;
argumentTest.TwoValue = 14;
e.Result = argumentTest;
}

public Form1()
{
InitializeComponent();
InitializeComponent();
TestObject test = new TestObject
{
OneValue = 15,
TwoValue = 4
};
backgroundWorker1.RunWorkerAsync(test);
}
class TestObject
{
public int OneValue { get; set; }
public int TwoValue { get; set; }
}

Creating Slice Chart in windows using C#


Introduction: In C# with the help of GDI classes we can design or draw charts or graphs is
a very efficient manner in our projects. Charts are the pictorial representation of the data
through chart one can easily judge or see the ups and down or profit loss in other words we
can say we can show the groth rate of any business through chart. Slice Charts are consider
as cutting a cake into slices based on the weight. In this chart, angle of slice is linearly
proportional to weight. With the help of FillPie() method slice chart can be designed.
Void FillPie(Brush brush, int x,int y, int width,int height, int startAngle, int sweepAngle)

FillPie function is used to fill as ellipse if sweep angle is 360. To make it a circle, we make
height and width both equal to diameter of circle.

Brush brush: It is a brush object used to fill the Pie.

Int x: x co-ordinate of upper left corner of the bounding rectangle that defines the
ellipse from which the pie section comes.

So if the x co-ordinate of center of our circle is x0 and radius is r: - x = x0


r;
Int y: Same as x- co-ordinate. y = y0 r;
Int width: Width of bounding rectangle that defines the ellipse from which the pie
section comes. width = 2*radius;
Int startAngle: Angle in degrees measured clockwise from the x-axis to the first side
of the pie section.

So we start with 0 degrees and increment it with the sweepAngle for


the next slice to start right after the end of previous slice.
Int sweepAngle: Angle in degrees measured clockwise from the startAngle parameter
to the second side of pie section. So this is span of angle based on weight.

So 360 degrees is proportionally divided into 8 parts based on the


weight.
Example: To draw slice chart we have to take an array named alweight.
Code for on Form Load:

private void Form1_Load(object sender, EventArgs e)


{
alWeight = new int[] { 13, 23, 33, 15, 20, 10, 4, 11 };
}

Code for DrawSliceChart method

private void DrawSliceChart(PaintEventArgs e, int[] alWeight)


{
int numberOfSections = alWeight.Length;
int x0 = 100;
int y0 = 100;
int radius = 100;
int startAngle = 0;
int sweepAngle = 0;
int[] height = new int[numberOfSections];
int total = SumOfArray(alWeight);
Random rnd = new Random();
SolidBrush brush = new SolidBrush(Color.Aquamarine);
Pen pen = new Pen(Color.Black);
for (int i = 0; i < numberOfSections; i++)
{
brush.Color = Color.FromArgb(rnd.Next(200, 255), rnd.Next(255),
rnd.Next(255), rnd.Next(255));
if (i == numberOfSections - 1)
sweepAngle = 360 - startAngle;

else
sweepAngle = (360 * alWeight[i]) / total;
e.Graphics.FillPie(brush, x0 - height[i], y0 - height[i], 2
* radius, 2 * radius, startAngle, sweepAngle);
e.Graphics.DrawPie(pen, x0 - height[i], y0 - height[i], 2
* radius, 2 * radius, startAngle, sweepAngle);
startAngle += sweepAngle;
brush.Color = Color.FromKnownColor(KnownColor.Black);
}
}

Code for SumofArray method

private static int SumOfArray(int[] intArray)


{
int sum = 0;
for (int i = 0; i < intArray.Length; i++)
{
sum += intArray[i];
}
return sum;
}

Difference between FillPie( ) and DrawPie( )


The only difference between DrawPie and FillPie is that it takes Pen object instead of Brush.
Calling DrawSliceChart Method

private void Form1_Paint_1(object sender, PaintEventArgs e)


{
}

DrawSliceChart(e, alWeight);

Introduction of Socket
A Socket is an End-Point for communication link between two programs (Server Program
and Client Program ) running on the same network .Socket is bidirectional. We have to write
two programs for implementing a socket application in C#.

Server Socket Program ( Server )

Client Socket Program ( Client ) .

In C# network programming can be done by using namespaces


like System.Net and System.Net.Sockets . The classes and methods of these namespaces
can communicate across the network. The communication can be either connection oriented
or connectionless. They can also be either stream oriented or data-gram based.
Server Socket Program- Server program running on a computer has a socket that bound
to a Port Number on the same computer and listening to the client's incoming requests.
Client Socket Program- Client program have to know the IP Address ( Hostname ) of the
computer that the C# Server Socket Program resides and the Port Number assign for
listening for client's request .

Code for Server Socket Program

using System;
using System.Net.Sockets;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream =
clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0,
(int)clientSocket.ReceiveBufferSize);
string dataFromClient =
System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0,
dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " +
dataFromClient);
string serverResponse = "Server response " +
Convert.ToString(requestCount);

Byte[] sendBytes =
Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0,
sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

}
}

clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();

Code for Client Socket Program


For creating Client design a Client using windows application. Server is console application
but client is windows application. Server will give response when client request to sending
data or connecting with server.

using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.Windows.Forms;
System.Net.Sockets;

namespace New_Client
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new
System.Net.Sockets.TcpClient();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket.Connect("127.0.0.1", 8888);

}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + "
>> " + mesg;
}
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream =
System.Text.Encoding.ASCII.GetBytes("Message from Client$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0,
(int)clientSocket.ReceiveBufferSize);
string returndata =
System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}
}

First execute the Server Socket Program and then Client Socket Program as shown in above
pictures-

On Click to button "Send data to server" the data will send to server.

Creating Bar Chart in windows using C#


Introduction: For making bar chart we will make use of DrawRectangle in built function.
because we have to first create a big rectangle defining the boundary of bar graphs.
Parameters of DrawRectangle is :
1. Pen This defines the color and style of border
2. Rectangle Rectangle object to be created
Rectangle(int x, int y, int width,int height)
X and y are the co-ordinates of top left corner of rectangle. Width and height are width and
height of rectangle.

Height = (weight of current array element *height of outer rectangle )/ maximum weight.
X coordinate is incremented by width of bars everytime a new bar is created.
Y co-ordinate is calculated by the following formula:
y = y coordinate of outer rectangle + height of outer rectangle height of bar
Code for DrawBarChart

private void DrawBarChart(PaintEventArgs e, int[] alWeight)


{
int numberOfSections = alWeight.Length;

int lengthArea = 330;


int heightArea = 280;
int topX = 20;
int topY = 20;
int maxWeight = MaxValue(alWeight);
int[] height = new int[numberOfSections];
int total = SumOfArray(alWeight);
Random rnd = new Random();
SolidBrush brush = new SolidBrush(Color.Aquamarine);
Pen pen = new Pen(Color.Gray);
Rectangle rec = new Rectangle(topX, topY, lengthArea,
heightArea);
e.Graphics.DrawRectangle(pen, rec);
pen.Color = Color.Black;
int smallX = topX;
int smallY = 0;
int smallLength = (lengthArea / alWeight.Length);
int smallHeight = 0;
for (int i = 0; i < numberOfSections; i++)
{
brush.Color = Color.FromArgb(rnd.Next(200, 255),
rnd.Next(255), rnd.Next(255), rnd.Next(255));
smallHeight = ((alWeight[i] * heightArea) /
maxWeight);
smallY = topY + heightArea - smallHeight;
Rectangle rectangle = new Rectangle
(smallX, smallY, smallLength, smallHeight);
e.Graphics.DrawRectangle(pen, rectangle);
e.Graphics.FillRectangle(brush, rectangle);
brush.Color =
Color.FromKnownColor(KnownColor.Black);
e.Graphics.DrawRectangle(pen, rectangle);
smallX = smallX + smallLength;
}
}

What is DLL?
A dynamic linking library (DLL) is linked to your program at run time. DLL is similar to an
EXE but is not directly executable. Functions in the dll are called from the main exe. It
provides a way to split what would be a very large exe into an exe plus one or more dlls.
Creating DLL in C#
To creating DLL in C# just follow next stepsGoto File -> New Project then choose Class Library you will see window like below.

Here i am going to show DLL for addition, subtraction, multiplication, and division. Code for
this is given below-

using
using
using
using

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

namespace ClassLibrary1
{
public class Class1
{
public int add(int x,int y)
{
int z = x + y;
return z;
}
public int sub(int x, int y)

{
int z = x - y;
return z;

}
public int mul(int x, int y)
{
int z = x * y;
return z;
}
public int div(int x, int y)
{

}
}

int z = x / y;
return z;

After this Build this class by pressing F6 and dll will generate this class library now you can
use this in any other application where you want to use this dll.
Using DLL in C# Application
For using DLL in application you have to make add reference of the dll that you

Design the form as shown in below picture -

private void button1_Click(object sender, EventArgs e)


{
ClassLibrary1.Class1 c1 = new Class1();
int result=
c1.add(int.Parse(textBox1.Text),int.Parse(textBox2.Text));
textBox3.Text = result.ToString();
}

private void button2_Click(object sender, EventArgs e)


{
ClassLibrary1.Class1 c2 = new Class1();
int result = c2.sub(int.Parse(textBox1.Text),
int.Parse(textBox2.Text));
textBox3.Text = result.ToString();
}
private void button3_Click(object sender, EventArgs e)
{
ClassLibrary1.Class1 c3 = new Class1();
int result = c3.mul(int.Parse(textBox1.Text),
int.Parse(textBox2.Text));
textBox3.Text = result.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
ClassLibrary1.Class1 c4 = new Class1();
int result = c4.div(int.Parse(textBox1.Text),
int.Parse(textBox2.Text));
textBox3.Text = result.ToString();
}

Introduction of GDI(Graphics Design Interface)


GDI (Graphics Design Interface) through which we can design rectangle, circle, and more
shapes with the help of programming of classes and methods. Like other languages C#
also provides rich set of classes, methods and events for developing applications with
graphical capabilities.
GDI+ -

GDI+ is the advance evolution of GDI. Microsoft has taken care of most of the GDI
problems and have made it easy to use with GDI+.

GDI+ resides in System.Drawing.dll assembly.

All GDI+ classes are reside in the System.Drawing, System.Text, System.Printing,


System.Internal , System.Imaging, System.Drawing2D and System.Design
namespaces.

Graphics ClassesThe Graphics class encapsulates GDI+ drawing surfaces. Before drawing any object (for
example circle, or rectangle) we have to create a surface using Graphics class. Generally we
use Paint event of a Form to get the reference of the graphics. Another way is to override
OnPaint method.

protected override void OnPaint(PaintEventArgs e)


{
Graphics g = e.Graphics;
}
Some Graphics Class's Methods DrawArc ( )

Draws an arc from the specified ellipse.

DrawBezier( )

Draws a cubic bezier curve.

DrawBeziers ( )

Draws a series of cubic Bezier curves.

DrawClosedCurve Draws a closed curve defined by an


()
array of points.
DrawCurve ( )

Draws a curve defined by an array of


points.

DrawEllipse( )

Draws an ellipse.

DrawImage ( )

Draws an image.

DrawLine ( )

Draws a line.

DrawPath( )

Draws the lines and curves defined by a


GraphicsPath.

DrawPie ( )

Draws the outline of a pie section.

DrawPolygon( )

Draws the outline of a polygon.

DrawRectangle( ) Draws the outline of a rectangle.


DrawString ( )

Draws a string.

FillEllipse ( )

Fills the interior of an ellipse defined by


a bounding rectangle.

FillPath( )

Fills the interior of a path.

FillPie ( )

Fills the interior of a pie section.

FillPolygon( )

Fills the interior of a polygon defined by


an array of points.

FillRectangle ( )

Fills the interior of a rectangle with a


Brush.

FillRectangles ( )

Fills the interiors of a series of


rectangles with a Brush.

FillRegion( )

Fills the interior of a Region.

For making GDI+ application you have to first add Reference of System.Drawing.Dll like
shown in below picture.

After this you have to add two namespaces -

using System.Drawing;
using System.Drawing.Drawing2D;

Graphics ObjectsWith the help of Graphics object, you can draw lines, fill shapes, draw text and more. The
major objects are given below-

Pen

Used to draw lines and polygons, including rectangles,


arcs, and pies.

Brush

Used to fill enclosed surfaces with patterns,colors, or


bitmaps.

Color

Used to describe the color used to render a particular


object. In GDI+ color can be alpha blended.

Font

Used to describe the font to be used to render text.

Pen Class- A pen draws a line of specified width and style. You can initialize Pen with a
color or brush.
Initializes a new instance of the Pen class with the specified color.
public Pen(Color);
Initializes a new instance of the Pen class with the specified Brush.
public Pen(Brush);
Initializes a new instance of the Pen class with the specified Brush and width.
public Pen(Brush, float);
Initializes a new instance of the Pen class with the specified Color and Width.
public Pen(Color, float);
ExamplePen pn = new Pen( Color.Blue ); or Pen pn = new Pen( Color.Blue, 150 );
Properties of Pen Alignmen
Gets or sets the alignment for objects drawn with this Pen.
t
Brush

Gets or sets the Brush that determines attributes of this Pen.

Color

Gets or sets the color of this Pen.

Width

Gets or sets the width of this Pen.

Color Class: A Color represents an ARGB color. Properties of color is given below
A

Gets the alpha component value for this Color.

Gets the blue component value for this Color.

Gets the green component value for this Color.

Gets the red component value for this Color.

ExamplePen pn = new Pen( Color.Blue );


Font Class- The Font class defines a particular format for text such as font type, size, and
style attributes.

//Initializes a new instance of the Font class with the specified


attributes.
public Font(string, float);
//Initializes a new instance of the Font class from the specified existing
Font and FontStyle.
public Font(Font, FontStyle);
ExampleFont font = new Font("Times New Roman", 26);
Brush Class-

The Brush class is an abstract base class and cannot be instantiated. We always use its
derived classes to instantiate a brush object, like

SolidBrush

TextureBrush

RectangleGradientBrush

LinearGradientBrush.

ExampleLinearGradientBrush lBrush = new LinearGradientBrush(rect, Color.Red, Color.Yellow,


LinearGradientMode.BackwardDiagonal);

Example of Drawing a Rectangle

protected override void OnPaint(PaintEventArgs pe)


{
Graphics gcs = pe.Graphics;
Rectangle rect = new Rectangle(30, 30, 230, 200);
LinearGradientBrush lBrush = new LinearGradientBrush(rect,
Color.Bisque, Color.DarkMagenta,
LinearGradientMode.BackwardDiagonal);

gcs.FillRectangle(lBrush, rect);

How to Access IP Address of LAN Connected Computers


In C# with the help of Namespace System.Net.Sockets and System.Net we can build an
application through which we can find ID address of the machine connected with LAN.
Program code is given belowSystem.Net.IPHostEntry - Provides a container class for internet host address information .
Dns.Resolve("strhostname")- Resolve a DNS hostname or IP Address to
an System.Net.IPHostEntry instance.
Console.ReadKey()- Obtains the next character or function key pressed by the user. The
pressed key is optimally displayed in the console window.

using System;
using System.Net;
using System.Net.Sockets;
class GTest
{
public static void Main()
{
string strHost;

Console.Write("Input host : ");


strHost = Console.ReadLine();
IPHostEntry IPHost = Dns.Resolve(strHost);
Console.WriteLine(IPHost.HostName);
IPAddress[] address = IPHost.AddressList;
Console.WriteLine("List IP {0} :", IPHost.HostName);
for (int i = 0; i < address.Length; i++) // output list of IP address
Console.WriteLine(address[i]);
Console.ReadKey();

IP Address of Machine-02

IP Address of Machine-01

How to get IP Address of Websites in C# application


In C# with the help of Namespace System.Net.Sockets and System.Net we can build an
application through which we can find ID address of the websites.
Program code is given belowIPHostEntry - Provides a container class for internet host address information .
Dns.GetHostEntry("Hostname")- Resolve a DNS hostname or IP Address to
an System.Net.IPHostEntryinstance.

using System;
using System.Net;
using System.Net.Sockets;
class ip
{
public static void Main()
{
String HostName ;
Console.WriteLine("Enter Web Address:");
HostName = Console.ReadLine();
Console.WriteLine("Looking up: {0}",
HostName);

IPHostEntry NameToIpAddress;
NameToIpAddress =
Dns.GetHostEntry(HostName);
int AddressCount = 0;
foreach (IPAddress Address in
NameToIpAddress.AddressList)
Console.WriteLine("IP Address {0}: {1}", +
+AddressCount, Address.ToString());
Console.ReadLine();

}
}

IP Address of Gmail.com

IP Address of Facebook.com

Creating Line Chart in windows using C#


Introduction- For making Line Chart, we have to first create boundary with
DrawRectangle using built function. then we will decide on which points to draw the line.
Code for Draw Line Chart

private void DrawLineChart(PaintEventArgs e, int[] alWeight)


{
int numberOfSections = alWeight.Length;
int lengthArea = 300;
int heightArea = 200;
int topX = 35;
int topY = 90;
int maxWeight = MaxValue(alWeight);
int[] height = new int[numberOfSections];
int total = SumOfArray(alWeight);
Random rnd = new Random();
SolidBrush brush = new SolidBrush(Color.Aquamarine);
Pen pen = new Pen(Color.Gray);
Rectangle rec = new Rectangle(topX, topY, lengthArea,
heightArea);
e.Graphics.DrawRectangle(pen, rec);
pen.Color = Color.Black;
int smallX = topX;
int smallY = 0;

int smallLength = (lengthArea / (alWeight.Length + 1));


int smallHeight = 0;
Point p1 = new Point();
Point p2 = new Point();
for (int i = 0; i < numberOfSections; i++)
{
brush.Color = Color.FromArgb(rnd.Next(200, 255),
rnd.Next(255),
rnd.Next(255), rnd.Next(255));
p1 = p2;
p2.X = p2.X + smallLength;
smallHeight = ((alWeight[i] * heightArea) / maxWeight);
p2.Y = topY + heightArea - smallHeight;
if (p1.X != 0 && p1.Y != 0)
{
e.Graphics.DrawLine(pen, p1, p2);
}
DrawDots(e, p2);
smallX = smallX + smallLength;
}

Code for Drawing Dots

private void DrawDots(PaintEventArgs e, Point p1)


{
Pen pen = new Pen(Color.SeaGreen);
e.Graphics.DrawPie(pen, p1.X - 5, p1.Y - 5, 10, 10, 0, 360);
e.Graphics.FillPie(new SolidBrush(Color.Purple), p1.X - 5, p1.Y 5, 10, 10, 0, 360);
}

Code for Calculating Max Value and Sum of Array

private static
int
MaxValue(int[
] intArray)
{
int
maxVal =
intArray[0];
for
(int i = 0; i <
intArray.Lengt
h; i++)

if
(intArray[i] >
maxVal)
maxVal =
intArray[i];
}
return
maxVal;
}
___________
___________
___________
___________
___________
___________
___________
___________
___________
___________
_____
private
static int
SumOfArray(i
nt[] intArray)
{
int
sum = 0;
for
(int i = 0; i <
intArray.Lengt
h; i++)
{

sum +=
intArray[i];
}
return
sum;
}

Creating Pie Chart in windows using C#


Introduction: Pie Chart is another chart which also uses the buil in functions. In this
chart, angle of slice remains the same for all slices but the radius varies based on the
weight. For this we first find out maximum weight MaxWeight. Then MaxWeight will be equal
to the radius and other slices will have radius proportionally lesser then MaxWeight.
let weight is 30-

MaxWeight = 30;
width = (30*radius)/MaxWeight;
sweepAngle = 360/TotalNumberOfWeights;

startAngle will start from 0 and is incremented by sweepAngle. - startAngle += sweepAngle;


Code for DrawPie Chart

private void DrawPieChart(PaintEventArgs e, int[]


alWeight)
{
int numberOfSections = alWeight.Length;
int x0 = 180;
int y0 = 120;
int radius = 200;
int startAngle = 0;
int sweepAngle = 360 / numberOfSections;
int[] height = new int[numberOfSections];

int maxWeight = MaxValue(alWeight);


Random rnd = new Random(10);
SolidBrush brush = new
SolidBrush(Color.Aquamarine);
Pen pen = new Pen(Color.Black);
for (int i = 0; i < numberOfSections; i++)
{
height[i] = ((Convert.ToInt32(alWeight[i])) *
radius) / maxWeight;
brush.Color = Color.FromArgb(rnd.Next(200,
255), rnd.Next(255),
rnd.Next(255), rnd.Next(255));
e.Graphics.FillPie(brush, x0 - height[i], y0 height[i],
2 * height[i], 2 * height[i], (startAngle + i * 45),
sweepAngle);
e.Graphics.DrawPie(pen, x0 - height[i], y0 height[i],
2 * height[i], 2 * height[i], (startAngle + i * 45),
sweepAngle);
}
}

Code for Calculating MaxValue

private static int MaxValue(int[] intArray)


{
int maxVal = intArray[0];
for (int i = 0; i < intArray.Length; i+
+)
{
if (intArray[i] > maxVal)
maxVal = intArray[i];
}
return maxVal;
}

Calling DrawPieChart Method

private void Form1_Paint_1(object sender,


PaintEventArgs e)
{
}

DrawPieChart(e, alWeight);

How to make Setup of Windows Application


With the help of setup one can access your application with using .net framework and
application source code. You can give this setup for using your application. Here some steps
are given below for making setup windows applicationHere i have taken application of error provider-

Step-1:

Step-2: You will get window like below and choose setup project, give name that you want.

Step-3: you will get window like below.

Step-4:

Step-5:

Step-6:

Step-7: Add exe of current project.

Step-8: Create two shortcut of this exe and insert one into User's Desktop folder and
another into User's Programs Menu folder.
Step-9: Now right click on Setup and choose Build.

Final Step- Now you can install your project. You can find your setup in your current
project folder.

Synchronization in C#
Introduction of Synchronization- Synchronization is particularly important when threads
access the same data; its surprisingly easy to run aground in this area.
Synchronization constructs can be divided into four categories:

Simple blocking methods

Locking constructs

Signaling constructs

No blocking synchronization constructs

Synchronization in Threads- Synchronization is needed in thread when we have multiple


threads that share data, we need to provide synchronized access to the data. We have to
deal with synchronization issues related to concurrent access to variables and objects
accessible by multiple threads at the same time.

using System;
using System.Threading;

namespace CSharpThreadExample
{

class Program
{
static void Main(string[] arg)
{
Console.WriteLine("-----> Multiple Threads ---->");
Printer p=new Printer();
Thread[] Threads=new Thread[3];
for(int i=0;i<3;i++)
{
Threads[i]=new Thread(new
ThreadStart(p.PrintNumbers));
Threads[i].Name="Child "+i;
}
foreach(Thread t in Threads)
t.Start();
Console.ReadLine();
}
}
class Printer
{
public void PrintNumbers()
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
}
}

Why we use Lock keyword- lock(object) is used to synchronize the shared object.
Syntax:
lock (objecttobelocked)
{
objecttobelocked.somemethod();
}

objecttobelocked is the object reference which is used by more than one thread to
call the method on that object.

The lock keyword requires us to specify a token (an object reference) that must be
acquired by a thread to enter within the lock scope.

Using of Monitor- The lock scope actually resolves to the Monitor class after being
processed by the C# compiler. Lock keyword is just a notation for using
System.Threading.Monitor class.

using System;
using System.Threading;
namespace CSharpThreadExample
{
class Program
{
static void Main(string[] arg)
{

Console.WriteLine(" -----> Multiple Threads


----->");
Printer p = new Printer();
Thread[] Threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
Threads[i] = new Thread(new
ThreadStart(p.PrintNumbers));
Threads[i].Name = "Child " + i;
}
foreach (Thread t in Threads)
t.Start();
Console.ReadLine();
}

}
class Printer
{
public void PrintNumbers()
{
Monitor.Enter(this);
try
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
finally
{
Monitor.Exit(this);
}
}
}
}

Creating Word document using C#


Create a new windows application project and add a button to it. On click of that button, we
will create a new document(word) and write a simple text in it. To create a word document
using C# we need to first reference the following DLL(com)..

After That Write Code in .CS File:

using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
Word;

namespace WindowsFormsApplication53
{
public partial class createworddocument : Form
{
public createworddocument()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object missing = System.Reflection.Missing.Value;
object Visible=true;
object start1 = 0;
object end1 = 0;

ApplicationClass WordApp = new ApplicationClass();


Document adoc = WordApp.Documents.Add(ref
missing, ref missing, ref missing, ref missing);
Range rng = adoc.Range(ref start1, ref missing);

try
{
rng.Font.Name = "Georgia";
rng.InsertAfter("Hiiiiiiiiiiii I m Aditya!");

object filename = @"G:\MyWord.doc";


adoc.SaveAs(ref filename, ref missing, ref
missing, ref missing,
ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing,
ref missing, ref missing, ref missing, ref missing, ref
missing);
WordApp.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Output:

How to Add Manually CheckBox in C#


You can add a CheckBox to a form at run time in the following manner.
Code for Add mannualy CheckBox in C#:

public void AddCheckBox()


{
CheckBox chkBox = new CheckBox();
chkBox.Location = new Point(50, 50);
chkBox.AutoCheck = true;
chkBox.Text = "Checked";
chkBox.Checked = true;
chkBox.CheckState = CheckState.Checked;

chkBox.CheckedChanged += new
EventHandler(chkBox_CheckedChanged);
}

Controls.Add(chkBox);

private void chkBox_CheckedChanged(object sender,


System.EventArgs e)
{
if (sender is CheckBox)
{
CheckBox checkbox = sender as CheckBox;
if (checkbox.Checked)
{

checkbox.Text = "Checked";
}
else
{
checkbox.Text = "UnChecked";
}
}

How to Change The Color of Specific Word in Rich textbox using C#:
.CS Code:

using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static void HighlightPhrase(RichTextBox box, string phrase, Color
color)
{

int pos = box.SelectionStart;


string s = box.Text;
for (int ix = 0; ; )
{
int jx = s.IndexOf(phrase, ix,
StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
HighlightPhrase(richTextBox1, "a", Color.Red);
HighlightPhrase(richTextBox1, "b", Color.Blue);
}
}

Design Output:

Reading/Writing/Appending a Text File, Using c#:


.Cs Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication53
{
public partial class Form3 : Form
{
public StringReader sr;
public StringWriter sw;
public Form3()
{
InitializeComponent();
}
private void file_write()
{
string path = "G:\\ash";
// Parent
Directory
string name = richTextBox1.Text;
string ext = ".txt";
string fname = path + name + ext;

FileInfo file1 = new FileInfo(fname);


StreamWriter sw = file1.CreateText();
sw.WriteLine("This is a demo for writing to a
text file"); //Writing a string directly to the file
sw.WriteLine(richTextBox1.Text);
// Writing content read from the textbox in the form
sw.Close();
}
private void file_read()
{
string path = "G:\\raj";
// Parent
Directory
string name = richTextBox1.Text;
string ext = ".txt";
string fname = path + name + ext;
string readcontent;
FileInfo file1 = new FileInfo(fname);
StreamReader sr = new
StreamReader(fname);
readcontent = sr.ReadToEnd();
//
Reading content from the file and storing to a string
sr.Close();
richTextBox1.Text = readcontent;
//
Display contents in a textbox in the form
}
private void file_append()
{
string path = "G:\\raj";
// Parent
Directory
string name = richTextBox1.Text;
string ext = ".txt";
string fname = path + name + ext;
// FileInfo file1 = new FileInfo(fname);
StreamWriter sw = File.AppendText(fname);
sw.WriteLine("This is a demo for appending
text content to a file");
// Writing a string directly to the file
sw.WriteLine(richTextBox1.Text) // Writing
content read from the textbox in the form
sw.Close();
}
private void Form3_Load(object sender,
EventArgs e)
{
}

private void button2_Click(object sender,


EventArgs e)
{
file_write();
}
private void button1_Click(object sender,
EventArgs e)
{
file_read();
}
private void button3_Click(object sender,
EventArgs e)
{
file_append();
}
}
}

Output:

How to Find Max Value of X, Y ,Z From Text file Using C# :


.CS CODE:

using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.IO;
System.Text.RegularExpressions;// Add name space

namespace WindowsFormsApplication53
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnFindMaxY_Click(object sender, EventArgs e)
{
string[] Lines = File.ReadAllLines("TextFile1.txt");
int maxY=0;
foreach (string line in Lines)
{
string[] SplitString = line.Split(' ');
if (SplitString.Length > 1)
{
try
{
if (int.Parse(SplitString[1]) > maxY)
{
maxY = int.Parse(SplitString[1]);
}
}
catch { }
}

}
textBox1.Text = maxY.ToString();

private void button1_Click(object sender, EventArgs e)


{
string[] Lines = File.ReadAllLines("TextFile1.txt");
int maxZ = 0;
foreach (string line in Lines)
{
string[] SplitString = line.Split(' ');
if (SplitString.Length > 2)

try
{
if (int.Parse(SplitString[2]) > maxZ)
{
maxZ = int.Parse(SplitString[2]);
}
}
catch { }

}
textBox2.Text = maxZ.ToString();

private void button2_Click(object sender, EventArgs e)


{
string[] Lines = File.ReadAllLines("TextFile1.txt");
int maxX = 0;
foreach (string line in Lines)
{
string[] SplitString = line.Split(' ');
if (SplitString.Length > 3)
{
try
{
if (int.Parse(SplitString[3]) > maxX)
{
maxX = int.Parse(SplitString[3]);
}
}
catch { }
}
}
textBox3.Text = maxX.ToString();
}

}
Design:

Create Text file Like This:

Output:

How to Take Printout of RichtextBox:


.CS File:

using System;
using System.Collections.Generic;

using
using
using
using
using
using
using

System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.IO;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private StringReader myReader;
//for Preview
private void Preview_Click(object sender, EventArgs e)
{
try
{
string strText = this.richTextBox1.Text; // read
string from editor window
myReader = new StringReader(strText);
PrintPreviewDialog printPreviewDialog1 = new
PrintPreviewDialog(); // instantiate
new print preview dialog
printPreviewDialog1.Document =
this.printDocument1;
//printPreviewDialog1.BorderStyle =
FormBorderStyle.Fixed3D;
printPreviewDialog1.ShowDialog(); // Show the
print preview dialog, uses print
page event to draw preview screen
}
catch (Exception exp)
{
System.Console.WriteLine(exp.Message.ToString());
}
}
// TextBoxPrinter _textBoxPrinter;
private void printDocument1_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
float linesPerPage = 0;
float yPosition = 0;
int count = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;

string line = null;


Font printFont = this.richTextBox1.Font;
SolidBrush myBrush = new SolidBrush(Color.Black);
// Work out the number of lines per page, using the
MarginBounds.
linesPerPage = e.MarginBounds.Height /
printFont.GetHeight(e.Graphics);
// Iterate over the string using the StringReader,
printing each line.
while (count < linesPerPage && ((line =
myReader.ReadLine()) != null))
{
// calculate the next line position based on the
height of the font according to
the printing device
yPosition = topMargin + (count *
printFont.GetHeight(e.Graphics));
// draw the next line in the rich edit control
e.Graphics.DrawString(line, printFont, myBrush,
leftMargin, yPosition, new StringFormat());
count++;
}
// If there are more lines, print another page.
if (line != null)
e.HasMorePages = true;
else
e.HasMorePages = false;
myBrush.Dispose();// e.HasMorePages =
TextBoxPrinter.Print(e.Graphics,
richTextBox1, printDocument1, _screenResolutionX);
}
private void Print_Click(object sender, EventArgs e)
{
printDialog1.Document = printDocument1;
string strText = this.richTextBox1.Text;
myReader = new StringReader(richTextBox1.Text);
if (printDialog1.ShowDialog() == DialogResult.OK)
{
this.printDocument1.Print();
}
}
}

Output:

When you click on Preview it looks like below

When You click on print then Output:

Multiple Colored Texts in RichTextBox using C#


Actually This Application tells how to enter values in a richtextbox with multiple color texts.
There is a property to set colored text by using SelectionText. Richtextbox has the
properties of SelectionFont, SelectionColor and SelectedText. Setting the values for these
properties makes multiple colors in our richtextbox. I just tried to create it as a sample
application and it is done.
.CS Code:

using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace WindowsFormsApplication2
{

public partial class Form2 : Form


{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender,
EventArgs e)
{
Font font = new Font("Tahoma", 8,
FontStyle.Regular);
richTextBox1.SelectionFont = font;
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText =
Environment.NewLine + textBox1.Text;
}
private void button2_Click(object sender,
EventArgs e)
{
Font font = new Font("Tahoma", 8,
FontStyle.Regular);
richTextBox1.SelectionFont = font;
richTextBox1.SelectionColor = Color.Green;
richTextBox1.SelectedText =
Environment.NewLine + textBox1.Text;
}
}
}

Design Output:

How to Create Stopwatch in C#

private void timer1_Tick(object sender, System.EventArgs e)


{
TimeSpan span =
DateTime.Now.Subtract(da);
this.label1.Text = span.Hours.ToString() +
":"+
span.Minutes.ToString() + " : " + span.Seconds.ToString() + " : "
+ span.Milliseconds.ToString();
}
private void button1_Click(object sender,
System.EventArgs e)
{
if(this.timer1.Enabled)
{
timer1.Stop();
button1.Text = "Start";
}
else
{
da = DateTime.Now;
timer1.Start();
button1.Text = "Stop";
}
}

private void checkBox1_CheckedChanged(object


sender, System.EventArgs e)
{
if (this.checkBox1.Checked)
{
this.TopMost = true;
}
else
{
this.TopMost = false;
}

Output:

When you Click on Start button Output Looks Like Below

Storing Database Connection Strings in App.Config


.NET Framework 2.0 added a separate configuration section in both Windows Application
configuration (App.config) and Web Application configuration (Web.config) file. Developers
can use these section to store connection string information such as a connection string

name or provider type etc. In the following tutorial I will show you how you can store and
retrieve connection string information in .NET Windows Application using C#.
The following code shows how you can store connection strings in App.config file.

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<appSettings>
<add key="name" value="provider=microsoft.jet.oledb.4.0;data
source=E://invent.mdb"/>
</appSettings>
</configuration>

In the code behind you should import the following namespace:

using System.Configuration;

Then retreive the value from the App.Config by the following code:

string con = ConfigurationSettings.AppSettings["name"].ToString();

Example:

using
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.Configuration;
System.Data.OleDb;

namespace WindowsFormsApplication1
{
public partial class using_app : Form
{

public using_app()
{
InitializeComponent();
}
string con =
ConfigurationSettings.AppSettings["name"].ToString()
;
OleDbConnection mycon;
private void button1_Click(object sender,
EventArgs e)
{
mycon = new OleDbConnection(con);
mycon.Open();
OleDbCommand cmd1 = new
OleDbCommand("select location from purchasing ",
mycon);
OleDbDataReader dr =
cmd1.ExecuteReader();
while(dr.Read())
{
textBox1.Text = dr[0].ToString();
}
mycon.Close();

Blink Label Color In Every Half Of Second Using C#


.CS Code:

private void using_app_Load(object sender, EventArgs e)


{

As Red

Timer tmr = new Timer();


tmr.Interval = 500;
tmr.Tick += new EventHandler(tmr_Tick);
tmr.Enabled = true;
label1. ForeColor = Color.Red; //Set The Default Color

}
void tmr_Tick(object sender, EventArgs e)
{

if(label1.ForeColor == Color.Red)
{
label1.ForeColor = Color.Green;
}
else if (label1. ForeColor == Color.Green)
{
label1.ForeColor = Color.Red;
}
}

Change a label's forecolor on mouseovers in C#:


using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class graphics : Form
{
public Font myFont = new Font("Microsoft Sans Serif", 8,
FontStyle.Regular);
public Font myFontBold = new Font("Microsoft Sans Serif", 10,
FontStyle.Bold);
public graphics()
{
InitializeComponent();
}

private void graphics_Load(object sender, EventArgs e)


{
label1.Text = "Most Welcome";
}
private void label1_MouseEnter(object sender, EventArgs e)
{

label1.ForeColor = System.Drawing.Color.Red;
label1.Font = myFontBold;

private void label1_MouseLeave(object sender, EventArgs e)


{

label1.ForeColor = System.Drawing.Color.Blue;
label1.Font = myFont;
}

Output:

Change forecolor on Mouseover

Draw a curve on form using Graphics class in C #.net.


In this simple Example you will learn that how to draw curve on the form using Graphics
class in C #.net.
You cant draw graphics on simple load event of the form. To create graphics on the form,
you must override the onpaint() function of the form.
The syntax of the onpaint() function is:
C#:
protected override void OnPaint (PaintEventArgs e)
{
}
.CS CODE:

private void graphics_Paint(object sender, PaintEventArgs e)


{
System.Drawing.Pen pen = new
System.Drawing.Pen(System.Drawing.Color.Blue);
System.Drawing.Graphics obj;
obj = this.CreateGraphics();
System.Drawing.Point[] points = new Point[5];
points[0] = new Point(105, 75);
points[1] = new Point(3, 45);
points[2] = new Point(40,30);
points[3] = new Point(1, 78);
points[4] = new Point(1,95);
System.Drawing.SolidBrush brush = new
SolidBrush(Color.SpringGreen);
obj.DrawCurve(pen, points);

obj.Dispose();
}

Draw a polygon on form using Graphics class C #.net:


In this simple Example you will learn that how to draw polygon on the form using Graphics
class in C #.net.
In order to draw polygon on the form, firstly you should know the behavior of the form.
While playing with the graphics you must keep the following point in your mind:
You cant draw graphics on simple load event of the form. To create graphics on the form,
you must override the onpaint() function of the form.
Polygons draw function:
In order to draw a polygon, graphics class provides us a function named as drawPolygon().
It is an overloaded function. By using this function you can draw polygon on the form.
Depending on your requirement you can use any of the overloaded function. I use the
following:
This function takes two arguments. The first argument is the object of Pen class. Pen class
has the four overloaded constructor. You can use any of the constructors to initialize the
object of pen class.
Example:

using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class graphics : Form
{
public graphics()
{
InitializeComponent();
}
private void graphics_Paint(object sender, PaintEventArgs e)
{
System.Drawing.Pen pen = new System.Drawing.Pen(System.Drawing.Color.Red);
System.Drawing.Graphics obj;
obj = this.CreateGraphics();
System.Drawing.Point[] points = new Point[5];
points[0] = new Point(75, 35);
points[1] = new Point(85, 35);
points[2] = new Point(45, 95);
points[3] = new Point(65, 25);
points[4] = new Point(65, 55);
obj.DrawPolygon(pen, points);
obj.Dispose();
}
private void graphics_Load(object sender, EventArgs e)
{
}
}

Output:

Drawing Lines in C#
In this Article Describe how to Draw a line in C# using Graphic Object. Lines are drawn in
C# using the DrawLine() method of the Graphics Object. This method takes a preinstantiated Pen object and two sets of x and y co-ordinates (the start and end points of the
line) as arguments. For example, to draw a line from co-ordinates (10, 20) to (200, 250) on
our sample form.
.CS CODE

private void graphics_Paint(object sender,


PaintEventArgs e)
{

System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new
Pen(System.Drawing.Color.Red, 5);
graphicsObj.DrawLine(myPen, 20, 20, 200, 210);
}

Output:

Drawing Text with C#


Text is drawn onto a Graphics Object using the DrawText() method. The syntax for this
method is as follows:
graphicsobj.DrawString(string, font, brush, x, y);
The string argument specifies the text to be drawn. Font defines the font to be used to
display the text and requires the creation of a Font object. The brush object is similar to the
Pen object used to draw shapes with the exception that it specifies a fill pattern. Finally, the
x and y values specify the top left hand corner of the text.
.CS CODE:

private void graphics_Paint(object sender, PaintEventArgs e)


{

System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Font myFont = new System.Drawing.Font("Helvetica", 40,
FontStyle.Italic);
Brush myBrush = new
SolidBrush(System.Drawing.Color.Red);

graphicsObj.DrawString("R4R Tech Soft", myFont,


myBrush, 30, 30);
}

Output:

Export gridview to pdf in c#


Download itextsharp.dll
.CS Code:

using
using
using
using
using
using
using
using
using
using
using
using
using

System;
System.Collections;
System.Configuration;
System.Data;
System.Linq;
System.Web;
System.Web.Security;
System.Web.UI;
System.Web.UI.HtmlControls;
System.Web.UI.WebControls;
System.Web.UI.WebControls.WebParts;
System.Xml.Linq;
iTextSharp.text.pdf;

using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;

using iTextSharp.text;
public partial class pdf_genration :
System.Web.UI.Page
{
DataSet ds=new DataSet();
protected void Page_Load(object sender,
EventArgs e)
{

ds.ReadXml(MapPath("Regis.xml"));
GridView1.DataSource = ds;
//DataGrid1.DataSource = ds;
GridView1.DataBind();
}
public override void
VerifyRenderingInServerForm(Control control)// this
Event is must for Rendring
{
}
protected void Button1_Click(object sender,
EventArgs e)
{
Response.Clear(); //this clears the Response
of any headers or previous output
Response.Buffer = true; //ma
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.pdf");
Response.Cache.SetCacheability(HttpCacheability.N
oCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new
StringReader(sw.ToString());
Document pdfDoc = new
Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new

HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc,
Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}

.aspx Code:
Output:

When You Click On ExportGridview Button All gridview Data is bind In pdffile
Like this:

How to Draw Ellipse using mouse dragging in C#:


.CS Code

using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;

using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
Point start;
Point end;
Graphics g;
bool isDown = false;
public Form1()
{
InitializeComponent();
}
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
start = new Point(e.X, e.Y);
isDown = true;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if ( isDown )
{
g.DrawEllipse(new Pen(Form1.DefaultBackColor, 2),
start.X, start.Y, end.X - start.X , end.Y-start.Y);
end = new Point(e.X, e.Y);
g.DrawEllipse(new Pen(Color.Black, 2), start.X, start.Y,
end.X - start.X, end.Y - start.Y);
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isDown = false;
}
private void Form1_Load(object sender, EventArgs e)
{
g = CreateGraphics();
}
}

Output:

Difference between array and Arraylist


Char[] vowel=new Char[]; ArrayList a_list=new ArrayList();
Array is in the System
namespace

ArrayList is in the System.Collections namespace.

The capacity of an Array is


ArrayList can increase and decrease size dynamically
fixed
An Array is a collection of
similar items

ArrayList can hold item of different types.

An Array can have multiple


ArrayList always has exactly one dimension..
dimensions..

How to Rotate Image in Picture Box Using C#

Right Click On solution Explorer>> Add newitem >> Add Class


Class name: Utilities

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace RotatePictureBox
{
public sealed class Utilities
{
private Utilities()
{
}
public static Bitmap RotateImage(Image image, float angle)
{
return RotateImage(image, new PointF((float)image.Width / 2,
(float)image.Height / 2), angle);
}
public static Bitmap RotateImage(Image image, PointF offset, float angle)
{
if (image == null)
throw new ArgumentNullException("image");
//create a new empty bitmap to hold rotated image
Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
rotatedBmp.SetResolution(image.HorizontalResolution,
image.VerticalResolution);
//make a graphics object from the empty bitmap
Graphics g = Graphics.FromImage(rotatedBmp);
//Put the rotation point in the center of the image
g.TranslateTransform(offset.X, offset.Y);
//rotate the image
g.RotateTransform(angle);
//move the image back
g.TranslateTransform(-offset.X, -offset.Y);
//draw passed in image onto graphics object
g.DrawImage(image, new PointF(0, 0));
return rotatedBmp;

.CS Code:

using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;

namespace RotatePictureBox
{
public partial class Form1 : Form
{
private Bitmap image = null;
private float angle = 0.0f;
public Form1()
{
InitializeComponent();
angleNumericUpDown.Value = (Decimal)angle;
}
//Load image
private void LoadImageBtn_Click(object sender, EventArgs e)
{
lfd.InitialDirectory = Application.StartupPath;
lfd.ShowDialog();
}
private void lfd_FileOk(object sender, CancelEventArgs e)
{
try
{
image = new Bitmap(lfd.FileName);
pictureBox1.Image = (Bitmap)image.Clone();
ImagePathTxtBox.Text = lfd.FileName;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

RotateImage(pictureBox1, image, angle);

protected override void OnKeyDown(KeyEventArgs e)


{
switch (e.KeyCode)
{
case Keys.Up:
RotateImage(pictureBox1, image, angle++);
break;
case Keys.Down:
RotateImage(pictureBox1, image, angle--);
break;
case Keys.Right:
RotateImage(pictureBox1, image, angle++);
break;
case Keys.Left:
RotateImage(pictureBox1, image, angle--);
break;
}
}
private
void angleNumericUpDown_ValueChanged(object sender, EventArgs e
)
{
angle = (float)angleNumericUpDown.Value;
RotateImage(pictureBox1, image, angle);
}
private
void RotateImage(PictureBox pb, Image img, float angle)
{
if (img == null || pb.Image == null)
return;
Image oldImage = pb.Image;
pb.Image = Utilities.RotateImage(img, angle);
if (oldImage != null)
{
oldImage.Dispose();
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
}

Output:

When You Change Angel

Image Will be Rotate According To Angel


Like This

Calculating Duration Between Two Dates in Years, Months and Days


Right Click On solution Explorer>> Add newitem >> Add Class

Class name: DateDifference.cs

using System;
using System.Collections.Generic;
using System.Text;
namespace DurationCalculatorApp
{
public class DateDifference
{
private int[] monthDay = new int[12] { 31, -1, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31 };
private DateTime fromDate;
private DateTime toDate;
private int year;
private int month;
private int day;
public DateDifference(DateTime d1, DateTime d2)
{
int increment;
if (d1 > d2)
{
this.fromDate = d2;
this.toDate = d1;
}
else
{
this.fromDate = d1;
this.toDate = d2;
}
///
/// Day Calculation
///
increment = 0;
if (this.fromDate.Day > this.toDate.Day)
{
increment = this.monthDay[this.fromDate.Month - 1];
}

/// if it is february month


/// if it's to day is less then from day
if (increment == -1)
{
if (DateTime.IsLeapYear(this.fromDate.Year))
{
// leap year february contain 29 days
increment = 29;
}
else
{
increment = 28;
}
}
if (increment != 0)
{
day = (this.toDate.Day + increment) - this.fromDate.Day;
increment = 1;
}
else
{
day = this.toDate.Day - this.fromDate.Day;
}
///
///month calculation
///
if ((this.fromDate.Month + increment) > this.toDate.Month)
{
this.month = (this.toDate.Month + 12) (this.fromDate.Month + increment);
increment = 1;
}
else
{
this.month = (this.toDate.Month) - (this.fromDate.Month +
increment);
increment = 0;
}
///
/// year calculation
///
this.year = this.toDate.Year - (this.fromDate.Year + increment);
}
public override string ToString()
{
//return base.ToString();
return this.year + " Year(s), " + this.month + " month(s), " +
this.day + " day(s)";

}
public int Years
{
get
{
return this.year;
}
}
public int Months
{
get
{
return this.month;
}
}
public int Days
{
get
{
return this.day;
}
}
}

.CS Code:

using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;

namespace DurationCalculatorApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_FormClosed(object sender,


FormClosedEventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
DateDifference dateDifference = new
DateDifference(this.dateTimeTo.Value, this.dateTimeFrom.Value);
this.lblOutput.Text = "Difference between " +
this.dateTimeFrom.Value.ToShortDateString()
+ " and " +
this.dateTimeTo.Value.ToShortDateString() + " is :\n"
+ dateDifference.ToString();

Output:

Advantage of Remoting
Lease-Based Lifetime : Distributed garbage collection of objects is managed by a system
called 'leased based lifetime'. Each object has a
lease time, and when that time expires the object is disconnected from the .NET runtime
remoting infrastructure.
Net Remoting takes a Lease-base Lifetime of the object that is scaleable

Call Context : Additional information can be passed with every method call that is not part
of the argument with the help of SOAP
Header
Distributed Identities : If we pass a reference to a remote object, we will access the
same object using this reference.
Advantage over Web Services?

1.

It works using purely Commmon Type System.

2.

It supports high speed binary over tcp/ip communication.

Advantage over COM/DCOM?

1.

It does not have extra interface language (IDL)

2.

It Works using purely managed code

3.

It's using Common Type System.. No Safearrays etc

Disadvantages

1.

It is not an open standard like web services.

2.

It is not as widespread and established ad DCOM.

3.

Less support for transactions,load balancing compared with DCOM.

4. How to Save Data in XML File


5. XML is designed to store and transport data. We can store data in a Xml file or Can
6.

use Xml as a databse. Here is and example of how we can use xml file to store data
in Xml file using Asp.Net and C#.
Example: First Create Xml File Like This And Save Regis.xml

7.
8. .CS Code:
9. ADD NameSpace in .CS File:
10. Using System.XML;
11. Code of Saving Data in XML File
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(Server.MapPath("regis.xml"));
XmlElement parentelement =
xmldoc.CreateElement("Comments");
XmlElement name = xmldoc.CreateElement("Name");
name.InnerText = TextBox1.Text;
XmlElement location =
xmldoc.CreateElement("location");
location.InnerText = TextBox2.Text;
XmlElement email = xmldoc.CreateElement("Email");
email.InnerText = TextBox3.Text;
XmlElement Description =
xmldoc.CreateElement("Description");
Description.InnerText = TextBox4.Text;
XmlElement date = xmldoc.CreateElement("Date");
date.InnerText = DateTime.Now.ToString();
parentelement.AppendChild(name);
parentelement.AppendChild(location);
parentelement.AppendChild(email);
parentelement.AppendChild(Description);

parentelement.AppendChild(date);
xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("regis.xml"));
}

12. Code of Display XML File In Gridview:


protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(MapPath("Registration.xml"));
GridView1.DataSource = ds;
//DataGrid1.DataSource = ds;
GridView1.DataBind();
}

13. Design Output:

14.

You might also like