Csharp Programming
Csharp Programming
Csharp Programming
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.
Multiple inheritance is not supported by C#, although a class can implement any
number of interfaces.
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
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 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:
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 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.
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
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:
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
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();
}
}
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();
}
}
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();
}
}
using System;
class Program
{
static void Main(string[] args)
{
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.
2.
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#).
1.
2.
3.
4.
C# has support for output parameters, aiding in the return of multiple values, a
feature shared by C++ and SQL.
5.
6.
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
}
}
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.
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:
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.
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-
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.
2.
3.
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.
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];
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");
}
}
}
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.");
}
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
}
}
using System;
class ForLoop
{
public static void Main()
{
for (int i=0; i < 20; i++)
{
if (i == 10)
break;
if (i % 2 == 0)
continue;
}
}
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.
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
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 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'
}
}
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:
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
public string Topic
{
get
{
return topic;
}
set
{
topic = value;
}
1.
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.
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 you are going to embed the instance into some other instances
Delegate
A delegate in
Types of Delegate
Delegates are of two types
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
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.
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( );
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);
}
}
}
{
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:
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.
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.
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
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.
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#: 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.
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-
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.
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
BackColor
Read/Write
Bottom
Read/Write
Read/Write
Enabled
Read/Write
ForeColor
Read/Write
Height
Read/Write
Left
Read/Write
Name
Read/Write
Parent
Read/Write
Right
Read/Write
TabIndex
Read/Write
TabStop
Read/Write
Tag
Read/Write
Top
Read/Write
Visible
Read/Write
Dock
at runtime.
Width
Read/Write
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
MouseUp
Click
DragEnter
DragLeave
DragOver
KeyDown
KeyPress
KeyUp
GotFocus
LostFocus
Validated
Validating
Name
Availabilit
y
Description
FlatStyle
Read/Write
Enabled
Read/Write
Image
Read/Write
ImageAlign Read/Write
Button Events
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.
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:
MaxLength
Read/Write
Multiline
Read/Write
PasswordChar
Read/Write
ReadOnly
Read/Write
ScrollBars
Read/Write
SelectedText
Read/Write
SelectionLength Read/Write
SelectionStart
Read/Write
WordWrap
Read/Write
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
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
nametxt.BackColor = Color.Red;
}
Event on TextBox Keypress Event-
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
AutoCheck
Read/Write
CheckAlign
Read/Write
Checked
Read/Write
Appearance
RadioButton Events
Name
Description
Click
CheckBox Properties
Name
Availabilit
y
Description
CheckStat
Read/Write
e
ThreeState Read/Write
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.
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:
}
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.
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.
Name
Availabilit
Description
CanRedo
Read only
CanUndo
Read only
Read only
DetectUrls
Read/Write
Rtf
Read/Write
Read/Write
SelectedText
Read/Write
SelectionAlignment
Read/Write
SelectionBullet
Read/Write
BulletIndent
Read/Write
SelectionColor
Read/Write
SelectionFont
Read/Write
SelectionLength
Read/Write
SelectionType
Read only
RedoActionName
SelectedRtf
UndoActionName
Read only
Read/Write
SelectionProtected
RichTextBox Events
Name
Description
LinkedClick
Protected
In following image i am making selected text bold on clicking the bold Button. Coding for
bold button is given below.
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.
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.
In following image i am making selected text Center on clicking the Center Button. Coding
for Center Button is given below.
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.
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
Read/Write
Items
Read-only
MultiColumn
Read/Write
SelectedIndices
Read-only
SelectedItem
Read/Write
SelectedItems
Read-only
SelectionMode
Read/Write
Sorted
Text
CheckedIndicies
Read/Write
Read/Write
Read-only
CheckedItems
Read-only
CheckOnClick
Read/Write
ThreeDCheckBoxe
Read/Write
s
ListBox Methods
Name
Description
ClearSelected
FindString
FindStringExact
GetSelected
SetSelected
ToString
GetItemChecked
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
listBox2.Items.Add(item);
}
listBox1.Items.Clear();
}
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
DroppedDown Read/Write
Items
Read-only
Read/Write
MaxLength
SelectedIndex Read/Write
SelectedItem
Read/Write
SelectedText
Read/Write
Read/Write
SelectionStart
SelectionLengt
Read/Write
h
Sorted
Read/Write
Read/Write
Text
ComboBox Events
Name
DropDown
Description
Occurs when the list portion of the control is dropped
down.
TextChanged
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
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
}
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");
}
}
output += "
" + this.comboBox3.Text+ "\r\n";
output += "
" + this.comboBox2.Text + "\r\n";
output += "Country: " + this.comboBox1.Text + "\r\n";
textBox4.Text = output;
}
Name
Activation
Availabilit
y
Description
Alignment
AllowColumn
Reorder
AutoArrange
CheckBoxes
CheckedIndice
s
Read-only
Columns
Read-only
FocusedItem
Read-only
FullRowSelect
GridLines
CheckedItems
HeaderStyle
Read-only
LabelEdit
Read/Write
LabelWrap
Read/Write
MultiSelect
Read/Write
Scrollable
SelectedIndice
s
Read-only
SelectedItems
Sorting
Read-only
View
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
ListView Events
Name
Description
ItemActivate
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.
folderCol = new
System.Collections.Specialized.StringCollection();
CreateHeadersAndFillListView();
PaintListView(@"D:\");
folderCol.Add(@"D:\");
this.lwFilesAndFolders.ItemActivate += new
System.EventHandler(this.lwFilesAndFolders_ItemActivate);
}
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
}
// Files
this column
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);
file
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);
}
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)
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
Panels
Read-only
ShowPanels
Read/Write
Text
Read/Write
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
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
toolStripProgressBar1.Value = toolStripProgressBar1.Value +
if (toolStripProgressBar1.Value ==
toolStripProgressBar1.Maximum)
{
toolStripProgressBar1.Value= 0;
toolStripProgressBar1.Visible = false;
timer1.Enabled = false;
toolStripStatusLabel2.Text = "Done";
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
Appearance
Read/Write
HotTrack
Read/Write
Multiline
Read/Write
RowCount
Read-only
SelectedInde
Read/Write
x
TabCount
Read-only
TabPages
Read-only
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.
On clicking next button you can move on next TabIndex code for this is given
below-
NotifyIcon Control
Display an icon on notification area with corresponding to the application is running. Like
shown in below example.
Properties of NotifyIcon
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:
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.
Dialog Controls
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)
{
}
}
}
saveAsToolStripMenuItem_Click(sender, e);
}
}
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)
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);
}
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-
Code for viewing the total record in DataGridview by clicking the view button
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.
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-
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.
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.
Code for calling CrystalReport- Write following code on CrystalReport Page load event.
FixedSize - The TableLayoutPanel does not allow additional rows or columns after it is
full.
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:
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.
// Create TableLayoutPanel
TableLayoutPanel tlp = new TableLayoutPanel();
// 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.
BorderStyle - This property determines if the panel is outlined with no visible border
(None), a plain line (FixedSingle), or a shadowed line (Fixed3D).
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.
AutoScroll: This property when set to true, allows scroll bars to be displayed.
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:
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.
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.
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.
SplitterRectangle: Gets the size and location of the splitter relative to the
SplitContainer.
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
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.
Month Calendar
The MonthCalendar control presents an intuitive graphical interface for users to view and set
date information.
Useful properties
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.
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.
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
}
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.
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.
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.";
ToolTip Control
ToolTip Control Provides the information to user when user moves mouse pointer over
control. Like 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.
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
AddChildToTheNode();
else
{
MessageBox.Show("Enter the Node Text to be added");
textBox1.Focus();
}
}
MenuStrip
ToolStrip controls
ContextMenusStrip
StatusStrip
MenuStrip Control
Useful properties
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.
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.
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.
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
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; }
}
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.
Int x: x co-ordinate of upper left corner of the bounding rectangle that defines the
ellipse from which the pie section comes.
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);
}
}
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#.
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();
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.
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
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
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+.
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.
DrawBezier( )
DrawBeziers ( )
DrawEllipse( )
Draws an ellipse.
DrawImage ( )
Draws an image.
DrawLine ( )
Draws a line.
DrawPath( )
DrawPie ( )
DrawPolygon( )
Draws a string.
FillEllipse ( )
FillPath( )
FillPie ( )
FillPolygon( )
FillRectangle ( )
FillRectangles ( )
FillRegion( )
For making GDI+ application you have to first add Reference of System.Drawing.Dll like
shown in below picture.
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
Brush
Color
Font
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
Color
Width
Color Class: A Color represents an ARGB color. Properties of color is given below
A
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.
gcs.FillRectangle(lBrush, rect);
using System;
using System.Net;
using System.Net.Sockets;
class GTest
{
public static void Main()
{
string strHost;
IP Address of Machine-02
IP Address of Machine-01
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
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;
}
MaxWeight = 30;
width = (30*radius)/MaxWeight;
sweepAngle = 360/TotalNumberOfWeights;
DrawPieChart(e, alWeight);
Step-1:
Step-2: You will get window like below and choose setup project, give name that you want.
Step-4:
Step-5:
Step-6:
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:
Locking constructs
Signaling constructs
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)
{
}
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);
}
}
}
}
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;
try
{
rng.Font.Name = "Georgia";
rng.InsertAfter("Hiiiiiiiiiiii I m Aditya!");
Output:
chkBox.CheckedChanged += new
EventHandler(chkBox_CheckedChanged);
}
Controls.Add(chkBox);
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)
{
Design Output:
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;
Output:
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();
try
{
if (int.Parse(SplitString[2]) > maxZ)
{
maxZ = int.Parse(SplitString[2]);
}
}
catch { }
}
textBox2.Text = maxZ.ToString();
}
Design:
Output:
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;
Output:
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
{
Design Output:
Output:
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.
using System.Configuration;
Then retreive the value from the App.Config by the following code:
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();
As Red
}
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;
}
}
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();
}
label1.ForeColor = System.Drawing.Color.Red;
label1.Font = myFontBold;
label1.ForeColor = System.Drawing.Color.Blue;
label1.Font = myFont;
}
Output:
obj.Dispose();
}
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
System.Drawing.Graphics graphicsObj;
graphicsObj = this.CreateGraphics();
Pen myPen = new
Pen(System.Drawing.Color.Red, 5);
graphicsObj.DrawLine(myPen, 20, 20, 200, 210);
}
Output:
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);
Output:
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:
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:
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);
}
}
Output:
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];
}
}
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();
}
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.
2.
1.
2.
3.
Disadvantages
1.
2.
3.
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"));
}
14.