C Tutorials
C Tutorials
C Tutorials
in/c
C# Tutorials
1. Introduction
2. Net Framework Architecture
3. Data types in C#
4. C# and other Programming Languages
5. Fundamentals of C#
6. Operators, types and variables in C#
7. Control Statements
8. Arrays, Indexer and Collections
9. Inheritance and Polymorphism
10. Properties
11. Attributes
12. Structs
13. Delegates and Events
14. Exception Handling
15. File Handling in C#
16. Threading
17. Introduction to Visual Studio
18. Introducing Windows Forms
19. Button Control
20. Label and Link Label
21. TextBox control
using C#
64. Reading/Writing/Appending a Text File, Using c#
65. How to Find Max Value of X, Y ,Z From Text file Using C#
66. How to Take Printout of RichtextBox
Days
86. Advantage of Remoting,Advantage over Web
Features of C#
Some notable distinguishing features of C# are:
There are no global variables or functions. All methods and members must be
declared within classes. Static members of public classes can substitute for global
variables and functions.
Managed memory cannot be explicitly freed instead, it is automatically garbage
collected.
Multiple inheritance is not supported by C#, although a class can implement any
number of interfaces.
new web services protocols such as SOAP, WSDL, and UDDI, and a focus on the Internet
Information Services.
What is CLR?
CLR (Common Language Runtime) is the most important component of .Net Framework. It
manages and executes code written in .Net Languages, CLR activates objects and perform
security checks. The CLR allows programmers to ignore many details of the specific CPU
that will execute the program. It also provides other important services, including the
following:
Memory management
Thread management
Exception handling
Garbage collection
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:
describing types. Self-describing types are further split into arrays and class types. The class
types are user-defined classes, boxed value types, and delegates.
What is CLS?
The Common Language Specification (CLS) is a part of the standardized specification of
the .NET Framework originally defined by Microsoft, and later standardized by the European
Computer Manufacturers Association (ECMA). A key feature of .NET Framework is that
applications written in different languages can interoperate with one another, taking
advantage of inheritance, polymorphism, exceptions and other features.
CLS provides,
set of specification to be adhered by new language writer/compiler writer for .Net
Framework to ensure interoperability. because .net supports many languages.For example
Asp.Net application written in C#.Net language. Now we can refer any other DLL which has
been written in any other language supported by .Net Frame Work.
.Net 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
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: Converting value types to reference types is also known as boxing. As can be
seen in the example below, it is not necessary to tell the
compiler an Int32 is boxed to an object, because it takes care of this itself.
e.g.-
Int32 a = 10;
object count = a ; // Implicit boxing
Console.WriteLine("The Object count = {0}",count); // prints out 10
//However, an Int32 can always be explicitly boxed like this:
Int32 a = 10;
object count = (object) a; // Explicit boxing
Console.WriteLine("The object count = {0}",count); // prints out 10
Unboxing: The following example intends to show how to unbox a reference type back to a
value type. First an Int32 is boxed to an object, and then it is
unboxed again. Note that unboxing requires explicit cast.
Ex.
Int32 a = 5;
object count = a; // Implicit
Boxing a = (int)count; // Explicit Unboxing
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)
{
int num1, num2;
float avg;
num1 = 10;
num2 = 21;
avg = (float)(num1 + num2) / 2;
Console.WriteLine("average is : " + avg);
Console.ReadLine();
}
}
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.
namespace MyCompany.r4r
{
class MyClass
{
// some code here
}
}
namespace MyCompany.r4r
{
class MyClass1
{
// some code here
}
}
11.
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
}
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.
16. Step 2: Write the HelloWorld program, you can either type the program shown below
into notepad or just copy-paste it from here-
C#");
}
}
Step 3: Once you have finished typing your program you should Save the source code file.
In fact after making any changes to your source code, you should always save the file. To
save the file for the first time in notepad click on File menu -> Save As. In the Save As
dialog select the directory from the Save In dropdown where you want to save your files, I
generally save my files to C:\csharp, and then in the File name textbox, enter the file name
as HelloWorld.cs (although you can provide any name you want but it should have an
extension.cs). and click Save. Once you have saved the
source code, and if you make any further modifications, in notepad use the Ctrl+S keyboard
short-cut to save your source code file.
Step 4: Since you have finished writing the source code its time to compile it. Since we are
using a command-line compiler that ships with the .NET SDK, start the command prompt
from Start -> Program Files -> Accessories -> Command Prompt. Or go to Start -> Run,
type cmd and press enter. Now from the command prompt navigate to the directory where
you have stored the source code file by issuing the following DOS commands.cd\ -To
navigate to the root of the derived csharp - To navigate to the csharp directory. Once you
are in the csharp directory where you
saved the source code file earlier, its time to run the C# Compiler csc.exe. Issue the
following command to compile our HelloWorld.cs
program:csc HelloWorld.cs
Step 5: If the compilation of the source code was successful then a new executable (Exe)
file by the name HelloWorld.exe will be created in the directory you compiled the source
code. To execute the program simply type the name of the executable file at the command
prompt.
Points to Remember
1.
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.
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
11.
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.
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
13.
using System;
class NewArray
{
public static void Main()
{
int[] myInts = { 5, 10, 15 };
bool[][] myBools = new bool[2][];
myBools[0] = new bool[2];
myBools[1] = new bool[1];
double[,] myDoubles = new double[2, 2];
string[] myStrings = new string[3];
Console.WriteLine("myInts[0]: {0},
myInts[1]: {1}, myInts[2]: {2}", myInts[0], myInts[1],
myInts[2]);
myBools[0][0] = true;
myBools[0][1] = false;
myBools[1][0] = true;
Console.WriteLine("myBools[0][0]:
{0}, myBools[1][0]: {1}", myBools[0][0], myBools[1][0]);
myDoubles[0, 0] = 4.245;
myDoubles[0, 1] = 6.355;
myDoubles[1, 1] = 8.415;
myDoubles[1, 0] = 56.1148917;
Console.WriteLine("myDoubles[0, 0]:
{0}, myDoubles[1, 0]: {1}", myDoubles[0, 0],
myDoubles[1, 0]);
myStrings[0] = "An";
myStrings[1] = "App";
myStrings[2] = "Cattt";
Console.WriteLine("myStrings[0]:
{0}, myStrings[1]: {1}, myStrings[2]: {2}", myStrings[0],
myStrings[1], myStrings[2]);
}
The if Statement
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
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.
Indexer: Indexers are usually known as smart array in C#.It is used for treating object as
an array.Defining an indexer in C# is much like same as
defining properties. Or we can say that an indexer is a member that enables an object to be
indexed in the same way as an array.
Syntax<access modifier> <return type> this [argument list]
{
get
{
// Write here some code for Get
}
set
{
// Write here some code for Get
}
}
Collections: Collections are the enumerable data structure in C# that can be assessed
using indexes or keys. Types of collections in C# are given belowSystem.Collections namespace
This provides a lot of classes, methods and properties to interact with the varying data
structures that are supported by it. The interfaces
that are defined in this namespace include:
IEnumerable
IEnumerator
ICollection
IList
IDictionary
System.Collections.Stack
System.Collections.Queue Both are derived from ICollection Interface.
The collections that inherit the IDictionary interface include:
System.Collections.SortedList
System.Collections.Hashtable
The IList interface represents collections that only have value. The following are the
classes that extend this interface.
System.Array
System.Collections.ArrayList
System.Collections.Specialized.StringCollection
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 constructor");
}
public void Greet()
{
Types of Inheritance:
In Object Oriented Programming concept there are 3 types of inheritances.
1. Single Inheritance,
2. Multiple Inheritance
3. Multilevel Inheritance
Single Inheritance:
public class A
{
}
public class B:A
{
}
Multiple Inheritance:
public class A
{
}
public class B
{
}
public class C:A,B
{
}
Multilevel Inheritance:
public class A
{
}
public class B:A
{
}
public class C:B
{
}
In the above three types C# don't proved Multiple Inheritance. As there is conflict of
multiple override methods in base classes (say A, B in above example) As in Place C# give
another feature called Interfaces using interfaces you can achieve multiple Inheritance
feature.
Polymorphism
Poly means many and morph means form. Thus, polymorphism refers to being able to use
many forms of a type without regard to the details.
Creating Polymorphic Types:
For creating polymorphism there are two steps1. Create a base class with virtual methods.
2. Create derived classes that override the behavior of the base classs virtual methods.
To create a method in a base class that supports polymorphism, mark the method as
virtual.
Example.
}
public class DerivedClass : BaseClass
{
public override void DoWork()
{
}
public override int WorkProperty()
{
get {
return 0;
}
}
Properties
In C#, properties are natural extension of data fields. But C# provides a built in mechanism
called properties. Usually inside a class, we declare a data field as private and will provide a
set of public. In C#, properties are defined using the property declaration syntax. The
general form of declaring a property is as follows.
<acces_modifier> <return_type> <property_name>
{
get
{
}
set
{
}
}
SET and GET methods to access the data fields, since the data fields are not directly
accessible out side the class. We must use the set/get methods to access the data fields.
Example:
using System;
class Myproperty
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class Myprop
{
public static void Main()
{
Myproperty mc = new Myproperty();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}
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'
}
}
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()
{
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;
}
public HelpAttribute(string url) // url is a positional parameter
{
this.Url = url;
}
private string topic;
}
4. Structs
5. 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;
}
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 C# language allows us to reference a method. If we are using a C or
C++ then we would sound familiar because a delegate because it
is basically a function pointer. Delegates have other uses in addition to event
handling. Delegate maintains three important pieces of information :
1. The name of the method on which it make calls.
2. Any argument (if any) of this method.
3. The return value (if any) of this method.
Types of Delegate
Example
namespace delgnew
{
public delegate int Delg(int x, int y);
public class Math
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
}
class Fun
{
static void Main(string[] args)
{
Delg del1 = new Delg(Math.Add);
int add1 = del1(7, 7);
Console.WriteLine("7 + 7 = {0}\n",
add1);
Delg del2 = new Delg(Math.Multiply);
int multiply1 = del2(7,7);
Console.WriteLine("7 * 7 = {0}",
multiply1);
Console.ReadLine();
}
}
}
Static Delegates
Denoting static field is meaning that it will not be modified. You can invoke delegates
without declaring a local delegate instance. Just pass in the static delegate of the class.
Delegates as Properties
The problem with static delegates is that they must be instantiated whether or not they are
ever used.
Event
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.
Defining 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.
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
{
}
protected static void ThreadProcess()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
}
}
using System;
using System.Threading;
class MyThread
{
public int count;
string thrdName;
public MyThread(string name) {
count = 0;
thrdName = name;
}
public void run()
{
Console.WriteLine(thrdName + " starting.");
do {
Thread.Sleep(500);
Console.WriteLine("In " + thrdName +", count is
" + count);
count++;
} while(count < 10);
Console.WriteLine(thrdName + " terminating.");
}
}
public class MultiThread
{
public static void Main()
{
Console.WriteLine("Main thread starting.");
MyThread mt = new MyThread("Child #1");
Thread newThrd = new Thread(new
ThreadStart(mt.run));
newThrd.Start();
do {
Console.Write(".");
Thread.Sleep(100);
} while (mt.count != 10);
Console.WriteLine("Main thread ending.");
}
}
Joining Threads
To join thread1 (t1) onto thread2 (t2), write:
t2.Join( );
Joining the current thread to each thread in the collection in turn:
using System;
using System.Threading;
class MyThread
{
public int count;
public Thread thrd;
public MyThread(string name)
{
count = 0;
thrd = new Thread(new ThreadStart(this.run));
thrd.Name = name;
thrd.Start();
}
void run()
{
Console.WriteLine(thrd.Name + " starting.");
do
{
Thread.Sleep(500);
Console.WriteLine("In " + thrd.Name +", count
is " + count);
count++;
} while(count < 10);
Console.WriteLine(thrd.Name + " terminating.");
}
}
public class MoreThreads {
public static void Main() {
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.
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.
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
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-
+ textBox2.Text);
textBox1.Text = "";
textBox2.Text = "";
comboBox1.Text = "";
comboBox1.Focus();
}
When we want to allow the user to clear all fields entered into the listBox, we will
need to go back like we did above to the visual designer and double-click on the
Clear List button, this should again switch to a code view and allow you to add the
following code-
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
Anchor
Availability
Read/Write
Description
It tells how control behaves when its
container is resized.
BackColor
Bottom
Read/Write
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
Width
Read/Write
Dock
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
Availability
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
Availability
CausesValidation Read/Write
CharacterCasing Read/Write
Description
When a control that has this property set to
true is about to receive focus, two events are
fired: Validating and Validated. You can
handle these events in order to validate data
in the control that is losing focus. This may
cause the control never to receive focus. The
related events are discussed below.
A value indicating if the TextBox changes the
case of the text entered. The possible
values are:
q Lower: All text entered into the text box is
converted lower case.
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
Description
Enter
GotFocus
Leave
Validating
Validated
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
KeyDown
KeyPress
These three events are known as "Key Events". They allow you to
monitor and change what is entered into your controls.
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
Availability
Description
Read/Write
AutoCheck
Read/Write
CheckAlign
Read/Write
Checked
Read/Write
Appearance
RadioButton Events
Name
Description
Click
CheckBox Properties
Name Availability
Description
CheckStateRead/Write
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.
Example: In following image i have created a window form for saving information of
student like personal info and subjects of his/her. For this you have to drag and drop 4
textboxes, 2 radiobuttons, 5 labels and 3 buttons. Change all controls properties like in
picture.
In figure 2 if user direct click on ok button then he/she will get massage for alert to fill all
information. In Figure 3 if user fill personal information and then click on Ok button then
he/she will get alert message for choosing gender. And in figure 4 if user not choose subject
and click on ok button then he will get another alert message for choosing subject. To
making all these validation you have to write following code on Ok button Click.
Code For Ok Button Click:
}
this.textBox3.Text = output;
Now if you to give condition for user that he should must choose at least three subjects
then you can add code for this on Checklistbox Leave Event. Like following code.
Code for Leave Event on Checklist Box.
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
Availability
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
Read only
RedoActionName
SelectedRtf
SelectionType
ShowSelectionMargin Read/Write
SelectionProtected
Read only
Read/Write
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.
In following image i am making selected text Italic on clicking the italic Button. Coding for
italic button is given below.
it
if (oldFont.Italic)
newFont = new Font(oldFont, oldFont.Style &
~FontStyle.Italic);
else
newFont = new Font(oldFont, oldFont.Style |
FontStyle.Italic);
// Insert the new font
this.richTextBox1.SelectionFont = newFont;
this.richTextBox1.Focus();
}
In following image i am making selected text Underline on clicking the Underline Button.
Coding for Underline Button is given below.
Font oldFont;
Font newFont;
// Get the font that is being used in the selected text
oldFont = this.richTextBox1.SelectionFont;
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.
else if (e.KeyChar == 8)
{
MessageBox.Show("Please input valid size");
}
else if (e.KeyChar == 13)
{
// Apply size if the user hits enter
TextBox txt = (TextBox)sender;
if (txt.Text.Length > 0)
ApplyTextSize(txt.Text);
e.Handled = true;
this.richTextBox1.Focus();
}
}
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
Availability
Description
SelectedIndex
Read/Write
ColumnWidth
Read/Write
Items
Read-only
MultiColumn
Read/Write
SelectedIndices
Read-only
SelectedItem
Read/Write
SelectedItems
Read-only
SelectionMode
Read/Write
Text
CheckedIndicies
Read/Write
Read/Write
Read-only
CheckedItems
Read-only
CheckOnClick
Read/Write
ThreeDCheckBoxes Read/Write
ListBox Methods
Name
Description
ClearSelected
FindString
FindStringExact
GetSelected
SetSelected
ToString
GetItemChecked
GetItemCheckState
SetItemChecked
Name
ItemCheck
Description
(CheckedListBox only) Occurs when the check state of
one of the list items changes
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.
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
Availability
Description
A combo box can be displayed with three
different styles:
q DropDown: The user can edit the text box
part of the control, and must click the arrow
button to display the list part of the control.
DropDownStyle Read/Write
DroppedDown
Read/Write
Items
Read-only
Read/Write
MaxLength
SelectedIndex Read/Write
SelectedItem
Read/Write
the list.
SelectedText
Read/Write
SelectionStart
Read/Write
SelectionLength Read/Write
Sorted
Read/Write
Read/Write
Text
ComboBox Events
Name
Description
DropDown
SelectedIndexChanged
KeyDown, KeyPress,
KeyUp
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;
}
Availability
Description
Alignment
AllowColumn
Reorder
AutoArrange
CheckBoxes
CheckedIndices
Read-only
Columns
Read-only
FocusedItem
Read-only
FullRowSelect
GridLines
CheckedItems
HeaderStyle
Read-only
LabelEdit
Read/Write
LabelWrap
Read/Write
MultiSelect
Read/Write
Scrollable
SelectedIndices
SelectedItems
Read-only
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.
EnsureVisible
When you call this method, the list view will scroll itself to make
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.
to insert
// Files
this.lwFilesAndFolders.Items.Clear();
// Set the label with the current path
this.lblCurrentPath.Text = root;
// Lock the ListView for updates
this.lwFilesAndFolders.BeginUpdate();
them
path of the
this column
// is empty
ListViewItem
the ListView
}
// Loop through all the files in the root folder
foreach (System.IO.FileInfo fi in files)
{
// Create the main ListViewItem
lvi = new ListViewItem();
lvi.Text = fi.Name; // Filename
lvi.ImageIndex = 1; // The icon we use to
represent a folder has
// index 1
lvi.Tag = fi.FullName; // Set the tag to the qualified
path of the
// file
// Create the two sub items
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = fi.Length.ToString(); // Length of the file
lvi.SubItems.Add(lvsi); // Add to the SubItems
collection
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = fi.LastAccessTime.ToString(); // Last
Accessed Column
lvi.SubItems.Add(lvsi); // Add to the SubItems
collection
// Add the item to the Items collection of the
ListView
}
this.lwFilesAndFolders.Items.Add(lvi);
}
catch (System.Exception err)
{
MessageBox.Show("Error: " + err.Message);
}
if (lw.SelectedItems[0].ImageIndex != 0)
{
try
{
// Attempt to run the file
System.Diagnostics.Process.Start(filename);
}
catch
{
// If the attempt fails we simply exit the method
}
return;
}
else
{
// Insert the items
}
}
PaintListView(filename);
folderCol.Add(filename);
Code for making small icons view. Write below code on radio button
named small icon
private void rdoSmallIcon_CheckedChanged(object sender,
EventArgs e)
{
RadioButton rdb = (RadioButton)sender;
if (rdb.Checked)
this.lwFilesAndFolders.View = View.List;
}
Code for making large icons view. Write below code on radio button
named large icon
private void rdoLargeIcon_CheckedChanged(object sender,
EventArgs e)
{
RadioButton rdb = (RadioButton)sender;
if (rdb.Checked)
this.lwFilesAndFolders.View = View.LargeIcon;
}
StatusBar Control
A status bar is commonly used to provide hints for the selected item or information about an
action currently being performed on a dialog. Normally, the StatusBar is placed at the
bottom of the screen, as it is in MS Office applications and Paint, but it can be located
anywhere you like.
StatusBar Properties
Name
Availability
BackgroundImageRead/Write
Description
It is possible to assign an image to the
status bar that will be drawn in the
background.
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
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
}
}
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
Availability
Description
Alignment
Read/Write
Appearance
Read/Write
HotTrack
Read/Write
Multiline
Read/Write
RowCount
Read-only
SelectedIndexRead/Write
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
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)
{
}
}
}
}
this.Close();
}
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;
PrintDocument PrintDoc1 = new PrintDocument();
PrintPreviewDialog PrintPreviewDialog1 = new PrintPreviewDialog();
private void printToolStripMenuItem_Click(object sender, EventArgs
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);
}
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
This control provides a user interface that indicates to user that a control on a form has
error associated with it. In other had it works as validation upon the controls to handle the
error causes by inputting wrong by user.
Drag this control as shown in below picture -
Adding error provider control on textbox for blank not allowWrite this code on textbox validating event- Output will shown in below picture if user
leave name blank.
ValidateName();
}
private bool ValidateName()
{
bool bStatus = true;
if (textBox1.Text == "")
{
errorProvider1.SetError(textBox1, "Please enter your
Name");
bStatus = false;
}
else
errorProvider1.SetError(textBox1, "");
return bStatus;
}
Validating for age. For validating age i have covered three conditions for validate
1-If user leave this blank.
2-If entered age is less than 18.
3-If user input character value in place of numeric.
Write this code on Textbox2 validating Event-
}
private bool ValidateAge()
{
bool bStatus = true;
if (textBox2.Text == "")
{
errorProvider1.SetError(textBox2, "Please enter your Age");
bStatus = false;
}
else
{
errorProvider1.SetError(textBox2, "");
try
{
int temp = int.Parse(textBox2.Text);
errorProvider1.SetError(textBox2, "");
if (temp < 18)
{
errorProvider1.SetError(textBox2, "You must be atleast 18
years old to setup a test");
bStatus = false;
}
else
{
errorProvider1.SetError(textBox2, "");
}
}
catch
{
errorProvider1.SetError(textBox2, "Please enter your age as a
number");
bStatus = false;
}
}
return bStatus;
}
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:
Percent - The row or column should be sized as a percentage of the parent container.
// Create TableLayoutPanel
TableLayoutPanel tlp = new TableLayoutPanel();
// Set the BorderStyle to Inset
tlp.CellBorderStyle =
TableLayoutPanelCellBorderStyle.Inset;
// Grid has two columns
tlp.ColumnCount = 2;
// Create buttons
Button button1 = new Button();
button1.Text = "Click Me";
// Add buttons to
TableLayoutPanel
tlp.Controls.Add(button1);
Panel Control
The Panel control is a container for other controls, customarily used to group related
controls. Panels are used to subdivide a form by function, giving the user a logical visual cue
of control grouping.
Useful properties
AutoScroll - This property when set to true, allows scroll bars to be displayed.
BackColor - The background color of the Panel is defaulted to
System.Drawing.SystemColors.Control, but this can be set to any color you like.
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.
panel1.BorderStyle
System.Windows.Forms.BorderStyle.Fixed3D;
AutoScroll: This property when set to true, allows scroll bars to be displayed.
BackColor: The background color of the SplitContainer is defaulted to
System.Drawing.SystemColors.Control, but this can be set to any color you like. The
whole of the SplitContainer changes color, however, each Panel can have its own
background color.
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 and
Month Calendar
DateTimePicker
DateTimePicker is ideal for choosing a single date and/or time value and requires the same
amount of space as an ordinary drop-down list box. When the user clicks the drop-down
button, a month calendar appears. The operation of the control from this point is exactly the
same as the MonthCalendar control.
Useful properties
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
private void
EventArgs e)
{
dateTimePicker1_ValueChanged(object
sender,
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
ValueThis shows the current value of the control.
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
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
backgroundWorker1_DoWork event is generated when you double-click on DoWork. For
testing, let's add a Thread.Sleep command there. The Thread.Sleep method will pause the
execution of the BackgroundWorker, but does not consume the entire CPU.
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 width: Width of bounding rectangle that defines the ellipse from which the pie
section comes. width = 2*radius;
Int startAngle: Angle in degrees measured clockwise from the x-axis to the first side
of the pie section.
sum += intArray[i];
return sum;
}
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+
GDI+ is the advance evolution of GDI. Microsoft has taken care of most of the GDI
problems and have made it easy to use with GDI+.
GDI+ resides in System.Drawing.dll assembly.
All GDI+ classes are reside in the System.Drawing, System.Text, System.Printing,
System.Internal , System.Imaging, System.Drawing2D and System.Design
namespaces.
Graphics ClassesThe Graphics class encapsulates GDI+ drawing surfaces. Before drawing any object (for
example circle, or rectangle) we have to create a surface using Graphics class. Generally we
use Paint event of a Form to get the reference of the graphics. Another way is to override
OnPaint method.
DrawBezier( )
DrawBeziers ( )
DrawEllipse( )
Draws an ellipse.
DrawImage ( )
Draws an image.
DrawLine ( )
Draws a line.
DrawPath( )
DrawPie ( )
DrawPolygon( )
Draws a string.
FillEllipse ( )
FillPath( )
FillPie ( )
FillPolygon( )
an array of points.
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 belowPen
and pies.
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 AlignmentGets or sets the alignment for objects drawn with this Pen.
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.
using System;
using System.Net;
using System.Net.Sockets;
class GTest
{
public static void Main()
{
string strHost;
Console.Write("Input host : ");
strHost = Console.ReadLine();
IPHostEntry IPHost = Dns.Resolve(strHost);
Console.WriteLine(IPHost.HostName);
IPAddress[] address = IPHost.AddressList;
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
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:
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)
{
Console.WriteLine(" -----> Multiple Threads
----->");
}
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:
Controls.Add(chkBox);
How to Change The Color of Specific Word in Rich textbox using C#:
.CS Code:
using
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static void HighlightPhrase(RichTextBox box, string phrase, Color
color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; )
{
int jx = s.IndexOf(phrase, ix,
StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
HighlightPhrase(richTextBox1, "a", Color.Red);
HighlightPhrase(richTextBox1, "b", Color.Blue);
}
}
Design Output:
.Cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication53
{
public partial class Form3 : Form
{
public StringReader sr;
public StringWriter sw;
public Form3()
{
InitializeComponent();
}
private void file_write()
{
string path = "G:\\ash";
// Parent
Directory
string name = richTextBox1.Text;
string ext = ".txt";
string fname = path + name + ext;
FileInfo file1 = new FileInfo(fname);
StreamWriter sw = file1.CreateText();
sw.WriteLine("This is a demo for writing to a
text file"); //Writing a string directly to the file
sw.WriteLine(richTextBox1.Text);
// Writing content read from the textbox in
the form
sw.Close();
}
private void file_read()
{
string path = "G:\\raj";
// Parent
Directory
string name = richTextBox1.Text;
string ext = ".txt";
string fname = path + name + ext;
string readcontent;
FileInfo file1 = new FileInfo(fname);
StreamReader sr = new
StreamReader(fname);
readcontent = sr.ReadToEnd();
//
Reading content from the file and storing to a string
sr.Close();
richTextBox1.Text = readcontent;
//
Display contents in a textbox in the form
}
private void file_append()
{
string path = "G:\\raj";
// Parent
Directory
string name = richTextBox1.Text;
string ext = ".txt";
string fname = path + name + ext;
// FileInfo file1 = new FileInfo(fname);
StreamWriter sw = File.AppendText(fname);
sw.WriteLine("This is a demo for appending
text content to a file");
// Writing a string directly to the file
sw.WriteLine(richTextBox1.Text) // Writing
content read from the textbox in the form
sw.Close();
}
private void Form3_Load(object sender,
EventArgs e)
{
}
private void button2_Click(object sender,
EventArgs e)
{
file_write();
}
private void button1_Click(object sender,
EventArgs e)
{
file_read();
}
private void button3_Click(object sender,
EventArgs e)
{
file_append();
}
}
}
Output:
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)
{
}
textBox1.Text = maxY.ToString();
}
}
try
{
}
catch { }
}
textBox3.Text = maxX.ToString();
Design:
Output:
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private StringReader myReader;
//for Preview
private void Preview_Click(object sender, EventArgs e)
{
try
{
string strText = this.richTextBox1.Text; // read
string from editor window
myReader = new StringReader(strText);
PrintPreviewDialog printPreviewDialog1 = new
PrintPreviewDialog(); // instantiate
new print preview dialog
printPreviewDialog1.Document =
this.printDocument1;
//printPreviewDialog1.BorderStyle =
FormBorderStyle.Fixed3D;
printPreviewDialog1.ShowDialog(); // Show the
print preview dialog, uses print
page event to draw preview screen
}
catch (Exception exp)
{
System.Console.WriteLine(exp.Message.ToString());
}
}
// TextBoxPrinter _textBoxPrinter;
private void printDocument1_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
float linesPerPage = 0;
float yPosition = 0;
int count = 0;
float leftMargin = e.MarginBounds.Left;
float topMargin = e.MarginBounds.Top;
string line = null;
Font printFont = this.richTextBox1.Font;
SolidBrush myBrush = new SolidBrush(Color.Black);
// Work out the number of lines per page, using the
MarginBounds.
linesPerPage = e.MarginBounds.Height /
printFont.GetHeight(e.Graphics);
// Iterate over the string using the StringReader,
printing each line.
while (count < linesPerPage && ((line =
myReader.ReadLine()) != null))
{
// calculate the next line position based on the
height of the font according to
the printing device
yPosition = topMargin + (count *
printFont.GetHeight(e.Graphics));
// draw the next line in the rich edit control
e.Graphics.DrawString(line, printFont, myBrush,
leftMargin, yPosition, new StringFormat());
count++;
}
// If there are more lines, print another page.
if (line != null)
e.HasMorePages = true;
else
e.HasMorePages = false;
myBrush.Dispose();// e.HasMorePages =
TextBoxPrinter.Print(e.Graphics,
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
{
public partial class Form2 : Form
{
public Form2()
InitializeComponent();
}
private void button1_Click(object sender,
EventArgs e)
{
Font font = new Font("Tahoma", 8,
FontStyle.Regular);
richTextBox1.SelectionFont = font;
richTextBox1.SelectionColor = Color.Red;
richTextBox1.SelectedText =
Environment.NewLine + textBox1.Text;
}
private void button2_Click(object sender,
EventArgs e)
{
Font font = new Font("Tahoma", 8,
FontStyle.Regular);
richTextBox1.SelectionFont = font;
richTextBox1.SelectionColor = Color.Green;
richTextBox1.SelectedText =
Environment.NewLine + textBox1.Text;
}
}
}
Design Output:
Output:
(In the doc file insert a table at the location where you want the picture to appear.)
Than add reference to (Word 10.0 or 11.0 object library) within COM tab of Add
reference dialog box.
.Cs Code:
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
using System.Windows.Forms;
using Word;
using Microsoft.Office.Core;
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;
Word.WdSeekView.wdSeekPrimaryHeader;
///////////////////////////////////////////////////////////////////////////Header
WordApp.ActiveWindow.ActivePane.View.SeekView =
Word.WdSeekView.wdSeekCurrentPageHeader;
WordApp.ActiveWindow.Selection.Font.Name = "Verdana";
WordApp.ActiveWindow.Selection.Font.Size = 14;
Object CurrentPage = Word.WdFieldType.wdFieldPage;
WordApp.ActiveWindow.Selection.TypeText("ASP.NET Tutorials");
WordApp.ActiveWindow.Selection.TypeText("
");
WordApp.ActiveWindow.Selection.TypeText("Page ");
WordApp.ActiveWindow.Selection.Fields.Add(WordApp.Selection.Range, ref
CurrentPage,
ref missing, ref missing);
WordApp.ActiveWindow.Selection.TypeText("
");
WordApp.ActiveWindow.Selection.TypeText(DateTime.Today.ToString("MM/dd/yyyy"));
////////////////////////////////////////////////////////////////footer
WordApp.ActiveWindow.ActivePane.View.SeekView =
Word.WdSeekView.wdSeekCurrentPageFooter;
WordApp.ActiveWindow.Selection.Font.Name = "Verdana";
WordApp.ActiveWindow.Selection.Font.Size = 8;
CurrentPage = Word.WdFieldType.wdFieldPage;
WordApp.ActiveWindow.Selection.TypeText("For Logica Internal Use Only");
WordApp.ActiveWindow.Selection.TypeText("
");
WordApp.ActiveWindow.Selection.TypeText("Page ");
WordApp.ActiveWindow.Selection.Fields.Add(WordApp.Selection.Range, ref
CurrentPage,
ref missing, ref missing);
WordApp.ActiveWindow.Selection.TypeText("
");
WordApp.ActiveWindow.Selection.TypeText(DateTime.Today.ToString("MM/dd/yyyy"));
MessageBox.Show(ex.Message);
}
}
Output:
3.Than add reference to (Word 10.0 or 11.0 object library) within COM tab of Add reference
dialog box.
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 Form5 : Form
{
public Form5()
{
InitializeComponent();
}
Document adoc;
private void button1_Click(object sender, EventArgs e)
{
object missing = System.Reflection.Missing.Value;
object Visible = true;
object start1 = 0;
object end1 = 0;
ApplicationClass WordApp = new ApplicationClass();
Output:
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 Form5 : Form
{
public Form5()
{
InitializeComponent();
}
Document adoc;
private void button1_Click(object sender, EventArgs e)
{
object missing = System.Reflection.Missing.Value;
object Visible = true;
object start1 = 0;
object end1 = 0;
ApplicationClass WordApp = new ApplicationClass();
adoc = WordApp.Documents.Add(ref missing, ref missing,
ref missing, ref missing);
adoc = WordApp.Documents.Add(ref missing, ref missing,
ref missing, ref missing);
Range rng = adoc.Range(ref start1, ref missing);
Word.Table oTable;
oTable = adoc.Tables.Add(rng, 2, 2, ref missing, ref
missing);
oTable.Cell(2, 2).Range.Text = "<table><tr><td>some
text here</td></tr><tr><td>some
other text here</td></tr></table>";
object filename = @"G:\MyFile.doc";
int rowsCount = oTable.Rows.Count;
int coulmnsCount =oTable.Columns.Count;
for (int i = 0; i < 25; i++)
{
{1}", i, j);
Output:
Than add reference to (Word 10.0 or 11.0 object library) within COM tab of Add
reference dialog box.
using Microsoft.Office.Interop.Word
.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;
using 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!");
object filename = @"G:\MyWord.doc";
adoc.SaveAs(ref filename, ref missing, ref missing, ref missing,
ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref
missing, ref missing,
ref missing, ref missing, ref missing);
WordApp.Visible = true;
WordApp.ActiveWindow.ActivePane.View.SeekView =
Word.WdSeekView.wdSeekPrimaryHeader;
Design:
Output :
<appSettings>
<add key="name" value="provider=microsoft.jet.oledb.4.0;data
source=E://invent.mdb"/>
</appSettings>
</configuration>
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;
}
}
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 checkerboard : Form
{
public checkerboard()
{
InitializeComponent();
}
Output:
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;
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 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);
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);
30, 30);
Output:
Download itextsharp.dll
.CS Code:
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;
using
using
using
using
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.NoCache);
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,
.aspx Code:
Output:
When You Click On ExportGridview Button All gridview Data is bind In pdffile
Like this:
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
using
using
using
using
System.Drawing;
System.Linq;
System.Text;
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;
}
}
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)
}
/// if it is february month
/// if it's to day is less then from day
if (increment == -1)
{
if (DateTime.IsLeapYear(this.fromDate.Year))
{
// leap year february contain 29 days
increment = 29;
}
else
{
increment = 28;
}
}
if (increment != 0)
{
day = (this.toDate.Day + increment) - this.fromDate.Day;
increment = 1;
}
else
{
day = this.toDate.Day - this.fromDate.Day;
}
///
///month calculation
///
if ((this.fromDate.Month + increment) > this.toDate.Month)
{
this.month = (this.toDate.Month + 12) (this.fromDate.Month + increment);
increment = 1;
}
else
{
this.month = (this.toDate.Month) - (this.fromDate.Month +
increment);
increment = 0;
}
///
/// year calculation
///
this.year = this.toDate.Year - (this.fromDate.Year + increment);
}
public override string ToString()
//return base.ToString();
return this.year + " Year(s), " + this.month + " month(s), " +
this.day + " day(s)";
}
public int Years
{
get
{
return this.year;
}
}
public int Months
{
get
{
return this.month;
}
}
public int Days
{
get
{
return this.day;
}
}
}
.CS Code:
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Text;
System.Windows.Forms;
namespace DurationCalculatorApp
{
public partial class Form1 : Form
{
public Form1()
InitializeComponent();
}
private void Form1_FormClosed(object sender,
FormClosedEventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
DateDifference dateDifference = new
DateDifference(this.dateTimeTo.Value, this.dateTimeFrom.Value);
this.lblOutput.Text = "Difference between " +
this.dateTimeFrom.Value.ToShortDateString()
+ " and " +
this.dateTimeTo.Value.ToShortDateString() + " is :\n"
+ dateDifference.ToString();
Output:
Advantage of Remoting
Lease-Based Lifetime : Distributed garbage collection of objects is managed by a system
called 'leased based lifetime'. Each object has a
lease time, and when that time expires the object is disconnected from the .NET runtime
remoting infrastructure.
Net Remoting takes a Lease-base Lifetime of the object that is scaleable
Call Context : Additional information can be passed with every method call that is not part
of the argument with the help of SOAP
Header
Distributed Identities : If we pass a reference to a remote object, we will access the
same object using this reference.
Advantage over Web Services?
1. It works using purely Commmon Type System.
2. It supports high speed binary over tcp/ip communication.
Advantage over COM/DCOM?
1. It does not have extra interface language (IDL)
2. It Works using purely managed code
3. It's using Common Type System.. No Safearrays etc
Disadvantages
1. It is not an open standard like web services.
2. It is not as widespread and established ad DCOM.
3. Less support for transactions,load balancing compared with DCOM.
Caching in ASP.Net
Caching is one of the coolest features in Asp.net. Caching is a technique of persisting the
data in memory for immediate access to requesting program calls. Many in the developer
community consider caching as one of the features available to improve performance of Web
applications.
Output Caching
Output caching is used for pages and is also known as Page-level caching. This requires one
to specify Duration of cache and Attribute of caching.
Syntax: <%@ OutputCache Duration="60" VaryByParam="none" %>
The above syntax specifies the page be cached for duration of 60 seconds and the value
"none" for VaryByParam* attribute makes sure that there is a single cached page available
for this duration specified. if the first user requested page which contains item1 than the
second user will also see item1 even if he is requesting item2.
VaryByParam can take various "key" parameter names in query string.
Programmatic Page Caching
You can also use caching programmatically, meaning that you can change the value of cache
depending upon the tasks performed by the user. The Response.Cache class let's you access
the functionality to work with the cache object.
You can change the expiration time on the Cache
using the SetExpires method of the Response.Cache
class.Response.Cache.SetExpires(System.DateTime.Now.AddMinutes(10));
In the same way you can also use Response.Cache.VaryByParams to set the Params
programmatically.
Fragment Caching:
Fragment Caching refers to caching the sections of the page. These sections are most
commonly UserControls. Page fragment caching allows you to cache the small portion of the
page instead of caching the whole page.juuy
Let's see some examples of fragment caching and how it can be used.
@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"
In the Page directive above we have cached CategoryID and SelectedID for 120 seconds.
Both of these are the query string parameters.
This means that if the first user request CategoryID = 2 and the second user request the
same CategoryID than the second user will recieve the contents from the cache object
instead of going to the database and pulling records.
@ OutputCache Duration="120" VaryByParam="none" VaryByControl="Category"
The VaryByControl attribute can only be used in fragment caching. You can use this to cache
the value of the controls. These controls can be any server controls like dropdownlist or
datagrid.
When using fragment caching you only need to put the cache directive in the user control
and not on the page.
.CS Code:
ADD NameSpace in .CS File:
Using System.XML;
Code of Saving Data in XML File
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"));
}
Design Output:
XML namespace:
XML designer
XML Namespace
The System.Xml namespace provides a Large set of classes for processing XML data.There
Are more classes such as
in-memory structure nor validates the XML document against the DTD. You can
declare an object of the XmlTextReader class by including the System.Xml
namespace in the application. The syntax to declare an object of this class is as
follows:
XmlDataDocument: Provides support for XML and relational data in W3C XML DOM.
You can use this class with a dataset to provide relational and non-relational views of
the same set of data. This class is primarily used when you want to access the
functions of ADO.NET. The syntax to declare an object of this class is as follows:
DataSet ds=new DataSet();
XmlDataDocument doc=new XmlDocument(ds);
It gives you the freedom to work with any data by using the DOM.
There is synchronization between an XmlDatadocument and a DataSet, and any
changes in one will be reflected in the other.
3. Select XML File as the template from the right pane. Specify the name as
"Registraion.xml" and click open.
4. The XML designer is displayed. The XML designer has automatically generated a line that
notifies the browser that the document being processed is an XML document, as displayed in
the figure:
<firstname>kiran</firstname>
<mobileno>9998888785</mobileno>
<country>India</country>
<emailId>[email protected]</emailId>
<loginname>kiran</loginname>
<loginPwd>kiran222</loginPwd>
</userdata>
<userdata>
<firstname>rakesh</firstname>
<mobileno>9990512118</mobileno>
<country>India</country>
<emailId>[email protected]</emailId>
<loginname>rakesh </loginname>
<loginPwd>rak345</loginPwd>
</userdata>
<userdata>
<firstname>john</firstname>
<mobileno>9838610261</mobileno>
<country>India</country>
<emailId>[email protected]</emailId>
<loginname>john</loginname>
<loginPwd>john234</loginPwd>
</userdata>
</registration>
Output:
Remoting in ASP.NET
Remoting is one of the distributed technologies which is integrated in the .Net
framework.Remoting can be defined as a technology which facilitates communication
between Application Domains which could be on the same machine or on different machines
Remoting infrtastructure is supported by protocols such as TCP HTTP with XML or
SOAP/Binary as formatting serializers Also remoting objects can be called in 3 modes viz.
SingleCall Singleton ClientActivated Objects. It is a framework built into Common Language
Runtime (CLR) in order to provide developers classes to build distributed applications and
wide range of network services. It provides various features such as Object Passing, Proxy
Objects, Activation, Stateless and Stateful Object, Lease Based LifeTime and Hosting of
Objects in IIS. .NET Remoting is an enabler for application communication. It is a generic
system for different applications to use to communicate with one another. .NET objects are
exposed to remote processes, thus allowing inter process communication. The applications
can be located on the same computer, different computers on the same network, or even
computers across separate networks.
Architecture of Remoting
4.Sink: Sink is used for security point of view. Before sending the data, the Data will be
encrypted. Some additional bit will be added with the data to secure the data.
There are two types of sink
(1) Envoy sink
(2) Server Context Sink
SingleCall: Each in coming request from a client is serviced by a new object. The objectis
thrown away when the request has finished. This (essentiallystateless) model can be made
stateful in the ASP.NET environment by using the ASP.NET state service to store application
or session state.
Singleton: All incoming requests from clients are processed by a single server object.
Client-activated object:This is the old stateful (D)COM model whereby the client receives
areference to the remote object and holds that reference (thus keepingthe remote object
alive) until it is finished with it.
Example :
1..class Library (Of which Remote Object will be created)
using System;
using System.Collections.Generic;
using System.Text;
namespace remoteclass
{
public class xx : MarshalByRefObject
{
public int sum(int a, int b)
{
return a * b;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace remoteserver
{
class Program
{
static void Main(string[] args)
{
TcpChannel ch = new TcpChannel(8085);
ChannelServices.RegisterChannel(ch);
RemotingConfiguration.RegisterWellKnownServiceType(typeof
(remoteclass.xx), "rahul", WellKnownObjectMode.Singleton);
Console.Write("Sever is Ready........");
Console.Read();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace remoteserver
{
class Program
{
static void Main(string[] args)
{
TcpChannel ch = new TcpChannel(8085);
ChannelServices.RegisterChannel(ch);
RemotingConfiguration.RegisterWellKnownServiceType(typeof
(remoteclass.xx), "rahul", WellKnownObjectMode.Singleton);
Console.Write("Sever is Ready........");
Console.Read();
}
}
}using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
//TcpChannel ch = new TcpChannel();
remoteclass.xx obj = new remoteclass.xx();
public Form1()
{
InitializeComponent();
}
Output:
1..Firstly Build Class Library
2..After This Run Console Application
Output Look like
Transaction in ASP.NET
A transaction is a group of operations combined into a logical unit of work that is either
guaranteed to be executed as a whole or rolled back. A transaction can be described to
cover the ACID properties for mission critical applications.
What are the ACID Properties?
Example:
Design
.CS Code:
cmd.ExecuteNonQuery();
strSQL = "Update transaction1 set balance1 = balance1
+ " + txtAmt.Text +
" where accountnumber1 = '"
+ txtTo.Text + "'";
cmd.CommandText = strSQL;
cmd.ExecuteNonQuery();
Trans.Commit();
lbl.Text = "Your Transaction is successfully";
}
catch (Exception ex)
{
Trans.Rollback();
lbl.Text = "Error: " + ex.Message;
}
finally
{
Conn.Close();
}
}
Design Output: