C Sharp Full Material
C Sharp Full Material
Sardhara
(Affiliated to Saurashtra University)
Website: https://gauravprajapatidot.wordpress.com
Email : [email protected]
C#.Net
Chapter Chapter Name Topics
No.
.NET Framework :
The .NET Framework is a service or platform for building, deploying, and running
applications. The .NET Framework consists of 2 main parts: common language
runtime and class libraries
There are many features provided by .NET Framework which has made .NET
popular and reliable in software development and web development industry.
Following are features of .NET Platform / .NET Framework.
1) Multilanguage Development
C#.NET supports multiple languages. This is definitely one of the biggest
advantages of .NET Framework because programmers having ability in
their own languages, can use their skills in their languages. Another
advantage of Multilanguage is that all are developed under same basic
environment.
2) Multi-Device Development
Apart from that .NET supports multiple developments. You can create
Mobile Application, PDA Application, etc.
6) Distributed Architecture
C#.NET applications have capability to be executed on Distributed
Architecture. You can create applications which can be executed on
Distributed Architecture.
8) Security
The design is meant to address some of the vulnerabilities, such as buffer
overflows, that been exploited by malicious software. Additionally, .NET
provides a common security model for all applications.
Access to metadata
Assembly:
1) Private Assembly
2) Shared Assembly
In order to share an assembly, the assembly must be explicitly built for this
purpose by giving it a cryptographically strong name (referred to as a
strong name).
Meta Data:
Locate classes
Load classes
Generate native code
Providesecurity
Namespace:
Select Compiler
Execute Code
Step-1 :
First of all C#.NET finds that which program is being compiled. According to the
program, C#.NET selects compiler. For C#.NET it selects C#C (C#Compiler), For
C# it selects CSC (CSharpCompiler), and similar to different languages which
are supported.
Step-2 :
Step-4 :
Now as MSIL is converted into Native Code (Binary Code), it can be executed.
then with the help of JIT; MSIL compile into Native code but CLR does not
convert whole MSIL code to Native code on Load time of that application;
instead of it compiles the MSIL instructions as they are called.
There are 3 types of JIT
o Pre-JIT - It compiles complete program into native code in a single
compilation cycle. This work is done at the time of deployment of the
program.
o Econo-JIT - It compiles only those methods that are called at runtime.
o Normal-JIT - It's like Econo-JIT. The methods are compiled the 1st
time they are stored in cache. When the same methods are called
again the- compiled code from cache is used for execution.
Managed Code
Unmanaged Code
Code that does not target the CLR (Common Language Runtime) is
known as Unmanaged Code.
Unmanaged code is what you use to make before C#.NET 2003 was
released.
Using this information you can construct and use objects at runtime.
Reflection is the ability of managed code to read its own metadata for
the purpose of encapsulates the type information.
o Example :
using System.Reflection ;
class MyClass
return (a+b);
class Demo
Type t = obj.GetType( );
MethodInfo m = t.getMethod(“Add”);
o In above example GetType( ) is used to get the information of class type.
Object[ ] arr = new Object[ ]{3,5};
o So, it is possible to check whether the class is an abstract class or regular class
by :Console.WriteLine(“Type Name=”+t.FullName+”\nSum=”+ m.Invoke(obj,arr));
Console.ReadKey( ) ;
C # Data Types :
Data Types (15)
Signed
Unsigned
Double precision
Double System.Double 64-Bits No.
String System.String - -
Object System.Object - -
class Demo
int X ;
object Obj ;
X = 10 ;
o Arithmetic Operators :
Operator Meaning
+ Addition
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
Operator Meaning
== Equal to
!= Not Equal to
Operator Meaning
| Bitwise OR
Array in C# :
Arrays
One- Multi-
DimensionalArrays DimensionalArrays
J
A B C D E F G H I
Index : [0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
Multi-dimensional Array :If array has more then one row and column, its called Multi
Dimension Array. There are two kinds of Multi Dimension Array In C# :
o Rectangular Array
o Jagged Array
o A multi-dimensional array is an array that has two or more dimensions, and an
individual element is accessed through the combination of two or more indices.
o In two-dimensional array the location of any specific element is specified by two
indices (x,y).
o Two-dimensional array can be same as table, one index indicates the row, the
other index indicates the column.
o Syntax or general form to declare two-dimensional array is as follows :
0 1 2 3 4
0 [0,0[0,0] [0,1] [0,2] [0,3] [0,4]
Array-name[row-index,column-index] = value ;
Jagged Array :
o C# allows creating special type of two-dimensional array called Jagged Array.
o Jagged array is an ―array of array‖ in which the length of each array can differ.
o Thus, a jagged array can be used to create a table in which the lengths of the
rows are not same.
o Jagged array are declared by using sets of square brackets to indicate each
dimension.
o To declre two-dimensional jagged array :
type[ ][ ] array-name = new type [row-size][ ] ;
o Example :
Int [ ][ ] table = new int [3][ ] ;
table[0] = new int [3] ;
table[1] = new int [2] ;
table[2] = new int [4] ;
o This example will make a table of varing row size as shown below :
[1][0] [1][1]
Control Structure of C# :
Control Structure
Do While Loop
Nested If
For each Loop
Switch Case
o The if statement :
- If statement checks the condition, if the condition is true, the target
statement of if will be executed, otherwise if exists, and the target
statements of else will be executed.
- At no time both of them will be executed.
- Either the statements of ―if‖ or ―else‖ will be executed.
- ―else‖ clause is optional.
- The general form or syntax of ―if‖ is as follows :
o Nested ifs :
- A nested if is an if statement that is the target of another if or else.
- In general nested if is a ―if within if‖.
- The if which contains another if is called ―Outer if‖.
- The if which is inside another if is called ―Inner if‖.
- The general form or syntax is as follows :
if (condition)
{
if (condition)
{
statement;
……
}
else
{
statement;
……. statement :
o The switch
- The} swich case provides for a multiway branch.
- }It enables a program to select among several alternatives.
- else
The value of an expression is successively tested against a list of constants.
- {When match is found, the statement sequence associated with that match is
statement;
executed.
- }The general form or syntax is as follows :
switch (expression)
{
case constant1 :
Statements;
break ;
case constant2 :
Statements;
break ;
case constant3 :
Statements;
break ;
…..
…..
default :
Statements;
break ;
}
Statements;
- The ―initialization‖ portion of the for loop sets a loop control variable to an initial
value.
- The ―condition‖ is a Boolean expression that tests the loop control variable.
- If test is ―true‖, the for loop continues to iterate.
- If it is ―false‖, the loop terminates.
- The ―increment‖ expression determines how the loop control variable is
changed each time the loop iterates.
- Like other loop ―while loop‖ is also used to repeatedly execute statements.
- The general form or syntax is as follows :
while (condition)
Statements;
do
Statements;
while (condition) ;
Statements;
- The ―type‖ and ―loopvariable‖ specifies the datatype and the name of loop
variable.
- The variable receives the value of next element in the collection each time the
foreach loop iterates.
- When loop begins, the first element of the collection is obtained and assigned
to loopvariable.
- Each subsequent iteration obtains the next element from the collection.
- The loop ends when there is no more elements to obtain.
- Thus, ―foreach‖ loop cycles through the collection one element at a time, from
start to finish.
Exception Handling in C# :
o Exception means runtime errors.
o Exception handling is a technique to handle runtime errors without terminating
execution of program.
o In c#, Exception Handling is managed via four keywords : try, catch, throw and
finally.
o Program statements that are supposed to generate errors are contained within a
try block.
o If an exception occurs within the try block, it is thrown.
o Exception is catched and handled by using catch block.
o System generated exceptions are automatically thrown by the c# runtime system.
o To manually throw an exception, the keyword ―throw‖ is used.
o The general form of ―try-catch‖ is shown below.
try
…
try
{
…
//block of code to monitor for errors
}
catch
{
//handler for Exceptions
}
try
{
//block of code to monitor for errors
}
catch
{
//handler for Exceptions
}
…
…
finally
{
// finally code
}
o The nested try blocks means one try within another is also possible.
try
{
throw exception-object;
}
catch(exception-type)
{
//handler for Exceptions }
Subject: C#- BCA-4 35
Gaurav.K.Sardhara
(Affiliated to Saurashtra University)
o Commonly used exceptions are :
DivideByZeroException
IndexOutOfRangeException
OverflowException
InvalidCastException ,etc…
Class :
o Classes are the basic ingredients of Object-Oriented languages.
o It is used to define custom data and methods.
o Classes can be declared by using the ―class‖ keyword followed by the name of
class and the brackets surrounding the body of the class.
o Supports member variables and methods.
Object :
o An object is a variable or an instance of the type Class.
o It can access all the members or properties of class by using dot (.) Operator.
Structure :
o It is the user defined datatype provided by c#.
o Like classes, structures can also contain both data and method definitions.
o Also like a class, a structure can contain constructors, constants, fields, methods,
properties, indexers, operators and nested types.
Namespace :
o Namespace is used to organize classes and other types into a single hierarchical
structure.
o Namespace is the logical collection of related classes.
o The proper use of namespaces will make classes easy to use and prevent
collisions with classes written by other authors.
o The namespace can contain classes and other namespaces.
o In C# ―System‖ is the root namespace.
o All the data related classes are within System.Data namespace.
o All Input/Output related classes are within System.IO namespace, etc.
“using” Keword :
o To use the classes within the particular namespace, the namespace must be
inherited before the use.
o Fields and properties represent information that an object contains. Fields are
like variables because they can be read or set directly.
o Both C# and Visual Basic allow you either to create a private field for storing the
property value or use so-called auto-implemented properties that create this field
automatically behind the scenes and provide the basic logic for the property
procedures.
o A method is an action that an object can perform. A class can have several
implementations, or overloads, of the same method that differ in the number of
parameters or parameter types.
o Events enable a class or object to notify other classes or objects when something
of interest occurs. The class that sends (or raises) the event is called the
publisher and the classes that receive (or handle) the event are called
subscribers. For more information about events, how they are raised and
handled.
Ref
The ref keyword is used to pass an argument as a reference. This means that
when value of that parameter is changed in the method, it gets reflected in the calling
method. An argument that is passed using a ref keyword must be initialized in the
calling method before it is passed to the called method.
Out
The out keyword is also used to pass an argument like ref keyword, but the
argument can be passed without assigning any value to it. An argument that is passed
using an out keyword must be initialized in the called method before it returns back to
calling method.
Example:
Example1(ref val1);
Console.WriteLine(val1); // val1=1
Example2(out val2);
Console.WriteLine(val2); // val2=2
}
static void Example1(ref int value) //called method
{
value = 1;
}
static void Example2(out int value) //called method
{
value = 2; //must be initialized
}
}
Constructor:
o Constructors are class methods that are executed automatically when an object
of a given type is created. Constructors usually initialize the data members of the
new object. A constructor can run only once when a class is created.
Furthermore, the code in the constructor always runs before an other code in a
class. However, you can create multiple constructor overloads in the same way
as for any other method.
{
public SampleClass()
{
// Add code here
}
}
using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
Types of Inheritance :
Base Class
Derived Class
Base Class
Derived Class
Derived Class
Derived Class
Base Class
Base Class
Derived Class
Subject: C#- BCA-4 43
Gaurav.K.Sardhara
(Affiliated to Saurashtra University)
class A
class B : A
Sealed class :
o It is a powerful concept used when you want to prevent the concept of
―Inheritance‖.
o If you want to create a class which will never inherited by any derived class then
the class must be declared as ―Sealed‖ class.
o To prevent a class from being inherited, precede it declaration with ―sealed‖
keyword.
o Sealed class is totally opposite of ―Abstract‖ class.
o So it is illegal to declare a class as both ―sealed‖ and ―abstract‖.
o Sealed can also be used on virtual methods to prevent further overrides.
o The example of sealed class is :
Abstract class :
The abstract keyword enables you to create classes and class members that are
incomplete and must be implemented in a derived class
Classes can be declared as abstract by putting the keyword abstract before the
class definition. For example:
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
Overriding Methods:
Creating a method in derived class with same signature as a method in base
class is called as method overriding.
Same signature means methods must have same name, same number of
arguments and same type of arguments.
Method overriding is possible only in derived classes, but not within the same
class.
When derived class needs a method with same signature as in base class, but
wants to execute different code than provided by base class then method
overriding will be used.
To allow the derived class to override a method of the base class, C# provides
two options, virtual methods and abstract methods.
Rajkot
class MyClass
{
int add(int x, int y)
{
return (x+y);
}
float add(float x, float y)
{
return (x+y);
}
}
class Demo
{
static void Main( )
{
MyClass obj=new MyClass( );
}
Subject: C#- BCA-4 48
Gaurav.K.Sardhara
(Affiliated to Saurashtra University)
Overloading Operators :
o Operator overloading is closely related to method overloading.
o Operator overloading is a concept of polymorphism, used to expand the usage of
operator.
o To overload an operator the ―operator‖ keyword is used to define an ―operator
method‖ which defines the action of the operator.
o When operator is overloaded, none of its original meaning is lost.
o There are two forms of operator methods :
1. For ―unary‖ operators.
2. For ―binary‖ operators.
// operations
o The ―ret-type‖ in above syntax specifies the type of value returned by operation.
o ―ret-type‖ can be any type, but it is often of the same type as the class for which
the operator is being overloaded.
o For unary operator, the operand is passed in ―operand‖.
o Operand must be of the same type of class.
o Note : operator methods must be both ―public‖ and ―static‖.
// operations
o The ―ret-type‖ in above syntax specifies the type of value returned by operation.
o ―ret-type‖ can be any type, but it is often of the same type as the class for which
the operator is being overloaded.
o For binary operator, the operands are passed in ―operand1‖ and ―operand2‖.
o Atleast one of the Operands must be of the same type of its class.
o Note : operator methods must be both ―public‖ and ―static‖.
type name
{
get
{
// get accessor code
}
set
}
Indexers :
o } An indexer allows an object to be indexed like an array.
o The main use of indexers is to support the creation of specialized arrays supports
one or more constraints.
o Indexers can have one or more dimensions.
Overloading Indexers :
o An indexer can also be overloaded.
o The version of an indexer is invoked which matches the number of parameter and
type.
get {
set {
get {
set {
A pointer is a variable whose value is the address of another variable i.e., the
direct address of the memory location. Like any variable or constant, you must
declare a pointer before you can use it to store any variable address.
Unsafe keyword denotes an unsafe context, which is required for any operation
involving pointers. You can use unsafe modifier in the declaration of a type or a
member . The entire textual extent of the type or member is therefore considered
an unsafe context.
type *var-name;
The following example illustrates use of pointers in C#, using the unsafe modifier:
using System;
namespace UnsafeCodeApplication
{
class Program
{
static unsafe void Main(string[] args)
{
int var = 20;
int* p = &var;
Console.WriteLine("Data is: {0} ", var);
Console.WriteLine("Address is: {0}", (int)p);
Console.ReadKey();
}
}
}
Data is: 20
Address is: 99215364
Delegate Declaration:
Simple Delegate
Create a windows form and add one button to it and paste the following code on its
click event.
//Calling a delegate
dc.Process(ll);
}
Multicast Delegate
The Event model in C# finds its roots in the event programming model that is
popular in asynchronous programming. The basic foundation behind this
programming model is the idea of "publisher and subscribers."
In this model, you have publishers who will do some logic and publish an
"event." Publishers will then send out their event only to subscribers who have
subscribed to receive the specific event.
Conventions
Event Handlers in the .NET Framework return void and take two
parameters.
Windows Forms :
o In C# .Net it’s these Forms with which we work. They are the base on which we
build/ develop all our user interface and they come with a rich set of classes.
o Forms allow us to work visually with controls and other items from the toolbox.
o The form class is based on the Control class which allows it to share many
properties and methods with other controls.
o Forms are objects that expose properties which define their appearance, methods
which define their behavior, and events which define their interaction with the
user.
o By setting the properties of the form and writing code to respond to its events, you
customize the object to meet the requirements of your application.
MessageBox() :
o It will display message or string in another window.
o The following argument of messagebox can be given in the Msgbox().
o Properties Of Msgbox :
Name Description
Text It will display text given in this argument on the messagebox.
Caption The text in this argument is display in the titlebar of the Msgbox.
Icon The icon name even in the argument is displayed on the msgbox.
DefaultButton The value set will specify each default button is to be display in the
msgbox.
Dialog boxes interrupt users. They force users to respond before further action is
taken. This is necessary in some situations.
Strip is a relatively narrow piece of something. Dot net has three important strip
controls namely MenuStrip, StatusStrip and ToolStrip. In this article we will
start with the menustrip control.
All the strips controls accommodate some other UI elements in it. A menu strips
allows you to add Menu and Menu allows you to add menu items. Similarly the
toolstrip control allows you add one or more tool bar buttons in it. OK, let us go to
the MenuStrip. Look at the below screen shot:
A Menubar, dot net calls it Menu strip can accommodate multiple Menus. In the
above picture only File menu is added to it. Menu items are usually added to the
menu. Say for example in the above picture, the Exit and Just for Demo are
menu items. Menu items are usually linked to the command handler and when
you click the menu item the corresponding handler gets called.
If a menu item is linked with one more menu, then the resulting menu is called as
Sub-Menu. The above picture shows one such sub-menu with two menu items in
it.
The menu strip is grouped in the toolbox under the Menus & Toolbars group.
This is shown in the below picture. To use menustrip in the form drag the
menustrip from the toolbox and drop it to the form.
In the below video, a menu strip is added to the form. To add a separator in the
menu just type the hyphen (-) for the menu name.
The placement ampersand (&) in the menu item name displays underline for
letter next to it.
This under line is displayed at runtime when alt key is pressed and typing the
letter with underline (alt key is still kept down) will call the menu item handler.
The usage of ampersand in the menu item with alt key is shown below:
So in the above picture in place of clicking the Exit menu item, you can call the
handler by using keys Alt+F,X
Figure 6.4 Child forms displayed within the workspace of the MDI form
Note Your application can also include standard, non-MDI forms that are not contained
in the MDI form. A typical use of a standard form in an MDI application is to display a
modal dialog box.
An MDI form is similar to an ordinary form with one restriction. You can't place a
control directly on a MDI form unless that control has an Align property (such as
a picture box control) or has no visible interface (such as a timer control).
Use the following procedure to create an MDI form and its child forms.
Note An application can have only one MDI form. If a project already has an
MDI form, the Add MDI Form command on the Project menu is unavailable.
To create an MDI child form, create a new form (or open an existing one) and set
its MDIChild property to True.
Creating new Windows Forms by inheriting from base forms is a handy way to
duplicate your best efforts without going through the process of entirely
recreating a form every time you require it.
For more information about inheriting forms at design time using the Inheritance
Picker dialog box and how to visually distinguish between security levels of
inherited controls, see How to: Inherit Forms Using the Inheritance Picker Dialog
Box.
Note In order to inherit from a form, the file or namespace containing that form
must have been built into an executable file or DLL. To build the project, choose
Build from the Build menu. Also, a reference to the namespace must be added to
the class inheriting the form. The dialog boxes and menu commands you see
might differ from those described in Help depending on your active settings or
edition. To change your settings, choose Import and Export Settings on the Tools
menu. For more information, see Customizing Development Settings.
1. In your class, add a reference to the namespace containing the form you wish to
inherit from.
2. In the class definition, add a reference to the form to inherit from. The reference
should include the namespace that contains the form, followed by a period, then
the name of the base form itself.
Before going for specific control, here is the list of some common Properties, Methods
and Events.
o Common Properties :
Name Description
Dock Gets or sets which control borders are docked to its parent control
and determines how a control is resized with its parent.
Enabled Gets or sets a value indicating whether the control can respond to
user interaction.
Font Gets or sets the font of the text displayed by the control.
TabIndex Gets or sets the tab order of the control within its container.
TabStop Gets or sets a value indicating whether the user can give the focus
to this control using the TAB key.
Visible Gets or sets a value indicating whether the control and all its child
o Common Methods :
Name Description
o Common Events :
Name Description
MouseDown Occurs when the mouse pointer is over the control and a mouse button
is pressed.
MouseMove Occurs when the mouse pointer is moved over the control.
MouseUp Occurs when the mouse pointer is over the control and a mouse button
is released.
MouseWheel Occurs when the mouse wheel moves while the control has focus.
o Properties of Label :
Name Description
Left Gets or sets the distance, in pixels, between the left edge of the control
and the left edge of its container's client area.
o Methods of Label :
Name Description
o Events of Label :
Name Description
o Properties of TextBox :
Name Description
MaxLength Gets or sets the maximum number of characters the user can type
or paste into the text box control.
ReadOnly Gets or sets a value indicating whether text in the text box is read-
only.
ScrollBars Gets or sets which scroll bars should appear in a multiline TextBox
control.
SelectedText Gets or sets a value indicating the currently selected text in the
control.
SelectionLength Gets or sets the number of characters selected in the text box.
o Methods of TextBox :
Name Description
Copy( ) Copies the current selection in the text box to the Clipboard.
Cut( ) Moves the current selection in the text box to the Clipboard.
Paste( ) Replaces the current selection in the text box with the contents of the
Clipboard.
DeselectAll( ) Specifies that the value of the SelectionLength property is zero so that
no characters are selected in the control.
o Event of TextBox :
Name Description
KeyDown Occurs when a key is pressed while the control has focus.
KeyPress Occurs when a key is pressed while the control has focus.
KeyUp Occurs when a key is released while the control has focus.
MultilineChanged Occurs when the value of the Multiline property has changed.
RichTextBox :
o The RichTextBox control is one of the most powerful controls provided in C#.Net.
o In a nutshell, it's a text box that's able to display text stored in Rich Text Format
(RTF), a standard format recognized by virtually all word processors, including
Microsoft WordPad (not surprisingly, since WordPad internally uses the
RichTextBox control).
o This control supports multiple fonts and colors, left and right margins, bulleted
lists, and more.
o The RichTextBox control is data-aware and therefore exposes the usual Dataxxxx
properties that let you bind the control to a data source. In other words, you can
write entire TXT or RTF documents in a single field of a database.
o Changing character attributes :
o The RichTextBox control exposes many properties that affect the attributes of the
characters in the selected text: These are FontName, FontSize, Color, Bold, Italic,
Underline, etc.
o Their names are self-explanatory, so won't describe what each one does. You
might find it interesting to note that all of the properties work as they would within
a regular word processor.
o It supports the properties, events, and methods of TextBox control.
RadioButton :
The RadioButton control can display text, an Image, or both.
When the user selects one option button (also known as a radio button) within a
group, the others clear automatically. All RadioButton controls in a given
container, such as a Form, constitute a group.
To create multiple groups on one form, place each group in its own container,
such as a GroupBox or Panel control.
RadioButton and CheckBox controls have a similar function: they offer choices a
user can select or clear.
The difference is that multiple CheckBox controls can be selected at the same
time, but option buttons are mutually exclusive. Use the Checked property to get
or set the state of a RadioButton.
Properties of RadioButton :
Name Description
Enabled Gets or sets a value indicating whether the control can respond to user
interaction.
Methods of RadioButton :
o RadioButton supports all the general methods, which are already discussed in the
beginning.
o Events of RadioButton :
Name Description
CheckBox :
o Checkboxes are also familiar controls—you click a checkbox to select it, and click
it again to deselect it. When you select a checkbox, a check appears in it,
indicating that the box is indeed selected. You use a checkbox to give the user an
option, such as true/false or yes/no. The checkbox control can display an image
or text or both.
o RadioButton and CheckBox controls have a similar function: they offer choices a
user can select or clear. The difference is that multiple CheckBox controls can be
selected at the same time, but option buttons are mutually exclusive.
o Properties of CheckBox :
Name Description
Enabled Gets or sets a value indicating whether the control can respond to user
interaction.
o Methods of CheckBox :
Name Description
Enabled( ) Gets or sets a value indicating whether the control can respond to user
interaction.
o Events of CheckBox :
Name Description
ListBox :
- As you know, list boxes display a list of items from which the user can select one
or more. If there are too many items to display at once, a scroll bar automatically
appears to let the user scroll through the list.
- The items in list boxes are stored in the Items collection; the Items.Count
property holds the number of items in the list. (The value of the Items.Count
property is always one more than the largest possible SelectedIndex value
because SelectedIndex is zero-based.) To add or delete items in a ListBox
control, you can use the Items.Add, Items.Insert, Items.Clear, or Items.Remove
methods. You also can add a number of objects to a list box at once with the
AddRange method. Or you can add and remove items to the list by using the
Items property at design time.
o MultiExtended— Multiple items can be selected, and the user can use the
Shift, Ctrl, and arrow keys to make selections.
o MultiSimple— Multiple items can be selected.
o None— No items may be selected.
o One— Only one item can be selected.
o When you support multiple selections, you use the Items property to access the
items in the list box, the SelectedItems property to access the selected items,
and SelectedIndices property to access the selected indices.
o Properties of ListBox :
Name Description
DropDownStyle Gets or sets a value specifying the style of the combo box. The
DropDownStyle property specifies whether the list is always
displayed or whether the list is displayed in a drop-down. The
DropDownStyle property also specifies whether the text portion can
be edited.
SelectionMode As listboxes can be used for Multiple selection. This specified how
many list items can be selected at a time. You can set this property
to None, One, MultiSelect, or MultiExtended.
SelectedIndex Gets or sets the index specifying the currently selected item. If more
then one items are selected it gives index no. of first item.
SelectedItem Gets or sets currently selected item in the ListBox. If more then one
items are selected it gives first selected item.
SelectedText Gets or sets the text that is selected in the editable portion of a
ListBox.
SelectedItems It gives list of all selected item. By using loop of SelectedItems you
can find the selected items in ListBox.
SelectionStart Gets or sets the starting index of text selected in the combo box.
Sorted Gets or sets a value indicating whether the items in the combo box
are sorted.
o Methods of ListBox :
Name Description
FindString(String) Returns the index of the first item in the ListBox that starts with the
specified string.
Items.Add Allows you to add item to the ListBox. The added item is kept last
if sorted property is not set to true.
Name Description
CheckedListBox :
o CheckedListBox is the ordinary ListBox with checkbox for each items in the list.
o It supports all properties, methods, and events of ListBox.
o It provides the facility to check the item from the list.
ComboBox :
o The Windows forms combo box control is used to display data in a drop-down
combo box. The combo box is made up of two parts: The top part is a text box
that allows the user to type in all or part of a list item. The other part is a list box
that displays a list of items from which the user can select one or more. You can
allow the user to select an item from the list, or enter their own data.
o ComboBox is called as List Control which is used to display list of items.
o Properties of ComboBox :
Name Description
Gets or sets a value specifying the style of the combo box. The
DropDownStyle property specifies whether the list is always
DropDownStyle displayed or whether the list is displayed in a drop-down. The
DropDownStyle property also specifies whether the text portion can
be edited.
SelectedIndex Gets or sets the index specifying the currently selected item.
SelectionStart Gets or sets the starting index of text selected in the combo box.
Gets or sets a value indicating whether the items in the combo box
Sorted
are sorted.
o Methods of ComboBox :
Name Description
FindString(String) Returns the index of the first item in the ComboBox that starts with
the specified string.
Items.Add Allows you to add item to the Combobox. The added item is kept
last if sorted property is not set to true.
Name Description
ListView :
o If tree views are all about displaying node hierarchies, like the folder hierarchy on
a disk, then list views are all about displaying lists of items. You can see a list
view in the right pane in the Windows Explorer (the part that displays what files
are in a folder).
o You can add list views to a Windows form just like any other control—just drag it
from the toolbox to the form at design time. To add items to a list box, open the
Items property in the Properties window.
o There are four views you can use in a list view. You select one by assigning a
value (View.LargeIcon, View.SmallIcon, View.List, or View.Details) to the list
view's View property:
o Large icon mode—displays large icons (large icons are 32×32 pixels) next to the
item text.
o Small icon mode—is the same as the large icon mode except that it displays
items using small icons (small icons are 16×16 pixels).
o List mode—displays small icons, and always in one column.
o Report mode (also called the details mode)—displays items in multiple columns,
displaying column headers and fields.
o Properties of ListView :
Name Description
CheckBoxes Gets/sets if every item should show a checkbox.
CheckedIndices Gets the indices of currently checked items.
CheckedItems Gets the currently checked items.
Columns Gets a collection of columns.
FullRowSelect Gets/sets whether selecting an item will select the entire row.
GridLines Gets/sets whether grid lines are drawn between items and their
subitems.
Items Gets the list items.
LargeImageList Gets/sets the ImageList for large icon view.
MultiSelect Gets/sets whether multiple items can be selected.
SelectedIndices Gets the indices of the selected items.
SelectedItems Gets the selected items.
SmallImageList Gets/sets the small icon image list.
Sorting Gets/sets the sort order for the items.
View Gets/sets the current view mode.
o Methods of ListView :
Name Description
ArrangeIcons Arranges the displayed items in Large Icon or Small Icon view.
Clear Removes all items from the list view.
GetItemAt Gets the item corresponding to the given X,Y coordinate.
Events of ListView :
Name Descrption
ColumnClick Occurs when a column is clicked.
ItemCheck Occurs when an item is checked.
SelectedIndexChanged Occurs when the selected index changes.
TreeView :
o A TreeView control displays a hierarchical list of Node objects, each of which
consists of a label and an optional bitmap. A TreeView is typically used to display
the headings in a document, the entries in an index, the files and directories on a
disk, or any other kind of information that might usefully be displayed as a
hierarchy.
o You use a tree view to display a hierarchy of nodes. Each node is not only
displayed visually, but also can have child nodes. An example of this is the
Windows Explorer, which uses a tree view in its left pane to display the hierarchy
o Properties of TreeView :
Name Description
HasChildren Gets a value indicating whether the control contains one or more
child controls.
CheckBoxes Gets/sets whether checkboxes should be displayed next to tree
nodes.
ImageList Gets or sets the ImageList that contains the Image objects that
are used by the tree nodes.
Nodes Gets the collection of tree nodes that are assigned to the tree
view control.
PathSeparator Gets or sets the delimiter string that the tree node path uses.
SelectedNode Gets or sets the tree node that is currently selected in the tree
view control.
ShowLines Gets or sets a value indicating whether lines are drawn between
tree nodes in the tree view control.
ShowPlusMinus Gets or sets a value indicating whether plus-sign (+) and minus-
sign (-) buttons are displayed next to tree nodes that contain child
tree nodes.
ShowRootLines Gets or sets a value indicating whether lines are drawn between
the tree nodes that are at the root of the tree view.
TopNode Gets or sets the first fully-visible tree node in the tree view
control.
VisibleCount Gets the number of tree nodes that can be fully visible in the tree
view control.
o Methods of TreeView
Name Description
BeginUpdate Disables redrawing of the tree view.
CollapseAll Collapses all nodes.
EndUpdate Enables redrawing of the tree view.
ExpandAll Expands all the nodes.
GetNodeAt Gets the node that is at the given location.
GetNodeCount Gets the number of nodes.
Name Description
Nodes.Add Used to add a node in tree view. The new node is added at
last.
Nodes.Insert Used to add a node at specific position.
Nodes.Remove Used to remove node from tree view
Nodes.IndexOf Used to know index no. of specific node. If specific node does
not exist it returns -1.
o Events of TreeView
Name Description
AfterCheck Occurs when a node checkbox is checked.
AfterCollapse Occurs when a tree node is collapsed.
AfterExpand Occurs when a tree node is expanded.
AfterLabelEdit Occurs when a tree node label text is edited.
AfterSelect Occurs when a tree node is selected.
BeforeCheck Occurs before a node checkbox is checked.
BeforeCollapse Occurs before a node is collapsed.
BeforeExpand Occurs before a node is expanded.
BeforeLabelEdit Occurs before a node label text is edited.
o The Nodes collection for a node holds the node's child TreeNode objects. You
can add, remove, or clone a TreeNode, and when you do, all child tree nodes are
added, removed, or cloned at the same time. Each TreeNode can contain a
collection of other TreeNode objects, which means you can use expressions like
this: MyNode.Nodes(3).Nodes(5) to refer to child nodes (in this case, actually
grandchild nodes). You also can use the FullPath property to specify nodes in
terms of their absolute, not relative, locations. And you can use the Nodes
collection's Add or Remove methods to add or remove nodes in code.
PictureBox :
o Picture boxes are used to display graphics from a bitmap, icon, JPEG, GIF or
other image file type.
o To display an image in a picture box, you can set the Image property to the image
you want to display, either at design time or at run time. You can clip and position
an image with the SizeMode property, which you set to values from the
PictureBoxSizeMode enumeration:
o Normal— Standard picture box behavior (the upper-left corner of the image is
placed at upper left in the picture box).
o StretchImage— Allows you to stretch the image in code.
o AutoSize— Fits the picture box to the image.
o CenterImage— Centers the image in the picture box.
o You also can change the size of the image at run time with the ClientSize
property, stretching an image as you want. By default, a PictureBox control is
displayed without any borders, but you can add a standard or three-dimensional
border using the BorderStyle property. And you can even handle events such as
Click and MouseDown to convert an image into an image map.
o Properties of PictureBox :
Name Description
o Methods of PictureBox :
(There are no specific methods for PictureBox apart from common methods)
o Events of PictureBox :
Name Description
Panel :
o Panels are those controls which contain other controls, for example, a set of radio
buttons, checkboxes, etc. Panels are similar to Groupboxes but the difference,
Panels cannot display captions where as GroupBoxes can and Panels can have
scrollbars where as GroupBoxes can't.
o If the Panel's Enabled property is set to False then the controls which the Panel
contains are also disabled. Panels are based on the ScrollableControl class.
o Notable property of the Panel control in the appearance section is the BorderStyle
property. The default value of the BorderStyle property is set to None. You can
select from the predefined list to change a Panels BorderStyle.
o Notable property in the layout section is the AutoScroll property. Default value is
set to False. Set it to True if you want a scrollbar with the Panel.
Panel GroupBox
Name Description
AutoScroll Gets or sets a value indicating whether the container enables the
user to scroll to any controls placed outside of its visible
boundaries.
Enabled Gets or sets a value indicating whether the control can respond to
user interaction.
o Methods of Panel :
(Apart from general methods Panel control does not have any special methods)
o Events of Panel :
(Apart from Scroll event all other events are common to Panel control)
Name Description
Scroll Occurs when the user or code scrolls through the Panel.
ScrollBar :
o Windows Forms ScrollBar controls are used to provide easy navigation through a
long list of items or a large amount of information by scrolling either horizontally or
vertically within an application or control. Scroll bars are a common element of the
Windows interface, so the ScrollBar control is often used with controls that do not
derive from the ScrollableControl class. Similarly, many developers choose to
incorporate the ScrollBar control when authoring their own user controls.
o The HScrollBar (horizontal) and VScrollBar (vertical) controls operate
independently from other controls and have their own set of events, properties,
and methods. ScrollBar controls are not the same as the built-in scroll bars that
are attached to text boxes, list boxes, combo boxes, or MDI forms (the TextBox
control has a ScrollBars property to show or hide scroll bars that are attached to
the control).
o When the user presses the PAGE UP or PAGE DOWN key or clicks in the scroll-
bar track on either side of the scroll box, the Value property changes according to
the value set in the LargeChange property. When the user presses one of the
arrow keys or clicks one of the scroll-bar buttons, the Value property changes
according to the value set in the SmallChange property.
Name Description
Maximum Gets or sets the upper limit of values of the scrollable range.
Minimum Gets or sets the lower limit of values of the scrollable range.
SmallChange Gets or sets the value to be added to or subtracted from the Value
property when the scroll box is moved a small distance.
Value Gets or sets a numeric value that represents the current position of the
scroll box on the scroll bar control.
Name Description
Scroll Occurs when the scroll box has been moved by either a mouse or
keyboard action.
Tooltip :
o A ToolStrip is a container for ToolStripItem elements. Each individual element on
the ToolStrip is a ToolStripItem that manages the layout and event model for the
type it contains. For example, elements visible on the toolbar, such as buttons,
text boxes, labels, or combo boxes, or visible on the menu bar.
o ToolStrip is a container for ToolStripItem elements. Each individual element on
the ToolStrip is a ToolStripItem that manages the layout and event model for the
type it contains. . The ToolStrip controls provide a common interface for Menus
and Strips in Windows Forms.
o Following is a list of ToolStripItem controls you can place within a ToolStrip.
ToolStripMenuItem A special menu control built specifically for use with the
MenuStrip and ContextMenuStrip controls.
o All these controls are usual controls which you use in developing Windows Forms.
The only difference is they appear under ToolStrip. ToopStrip is just a container of
all these controls. All the related properties, methods and events are used as we
use in programming.
o Toolstrip has got one important property called ―Items‖ which is collection of all the
items (toolbar items) which are placed under.
DialogBox:
o There are a number of built-in dialog boxes in Visual Basic, which is great,
because developing your own file open, file save, and other dialog boxes not only
takes a lot of work, but gives your program a different look from what Windows
users are already used to. They are listed as follows
o There are also other built-in dialog boxes like Print Preview Dialog Box, Page
Setup Dialog Box, etc. which are used as per requirement.
o You use the ShowDialog method to display the dialog at run time and can check
its return value (such as DialogResult.OK or DialogResult.Cancel) to see which
Name Description
Abort The dialog box return value is Abort (usually from a button labeled
Abort).
Cancel The dialog box return value is Cancel (usually from a button labeled
Cancel).
Ignore The dialog box return value is Ignore (usually from a button labeled
Ignore).
No The dialog box return value is No (usually from a button labeled No).
None Nothing is returned from the dialog box. This means that the modal
dialog
Continues running.
OK The dialog box return value is OK (usually from a button labeled OK).
Retry The dialog box return value is Retry (usually from a button labeled
Retry).
Yes The dialog box return value is Yes (usually from a button labeled Yes).
o Color dialogs let the user select a color in an easy way. The principal property you
use of these dialogs is the Color property, which returns a Color object, ready for
use.
o If you set the AllowFullOpen property to False, on the other hand, the Define
Custom Colors button is disabled and the user can select colors only from the
predefined colors in the palette. Note also that if you set the SolidColorOnly
property to True, the user can select only solid (not dithered) colors.
o Properties of ColorDialog :
Property Description
AllowFullOpen Gets/sets whether the user can use the dialog box to define
custom colors.
AnyColor Gets/sets whether the dialog box displays all available colors in
the set of basic colors.
Color Gets/sets the color selected by the user.
CustomColors Gets/sets the set of custom colors shown in the dialog box.
FullOpen Gets/sets whether the controls used to create custom colors are
visible when the dialog box is opened
ShowHelp Gets/sets whether a Help button appears in the color dialog box.
SolidColorOnly Gets/sets whether the dialog box will restrict users to selecting
solid colors only.
o Methods of ColorDialog :
Method Means
Reset Resets all dialog options to their default values.
ShowDialog Shows the dialog.
o Event of ColorDialog :
Event Means
HelpRequest Occurs when the user clicks the Help button.
Open File Dialog Box(OpenFileDialog) and Save File Dialog Box (SaveFileDialog)
o As you'd expect from its name, the Open File dialog and Save File dialog lets the
user select a file to open or save. In fact, it's the same Open File dialog and Save
File dialog used by Windows itself.
o There is no difference between OpenFileDialog and SaveFileDialog except
OpenFileDialog is used to open a file and SaveFileDialog is used to save a file.
o Open File dialogs are supported with the OpenFileDialog class. And Save File
dialogs are supported with the SaveFileDialog class. You can let users select
multiple files with the Multiselect property. You can use the ShowReadOnly
property to determine if a read-only checkbox appears in the dialog box. The
ReadOnlyChecked property indicates whether the read-only checkbox is
selected.
o The Filter property sets the current file name filter string, which determines the
choices that appear in the "Files of type" box in the dialog box. The name and
path the user selected is stored in the FileName property of the OpenFileDialog
Property Means
CheckFileExists Gets/sets if the dialog box displays a warning if the user
specifies a nonexistent file.
CheckPathExists Gets/sets whether the dialog box displays a warning if the
user gives a path that does not exist.
DefaultExt Gets/sets the default file extension.
FileName Gets/sets the file name selected in the file dialog box.
FileNames Gets the file names of all selected files.
Filter Gets/sets the current file name filter string, which sets the
choices that appear in the "Save as file type" or "Files of type"
box.
FilterIndex Gets/sets the index of the filter selected in the file dialog box.
InitialDirectory Gets/sets the initial directory used in the file dialog box.
Multiselect Gets/sets whether the dialog box allows multiple file
selections.
ShowHelp Gets/sets whether the Help button should be displayed.
ShowReadOnly Gets/sets whether the dialog displays a read-only check box.
Title Gets/sets the file dialog box title.
o Methods of OpenFileDialog / SaveFileDialog :
Method Means
OpenFile Opens the file selected by the user, with read-only permission. The
file is specified by the FileName property.
Reset Resets all options to their default values.
ShowDialog Shows the dialog box.
o Events of OpenFileDialog / SaveFileDialog :
Event Means
FileOk Occurs when the user clicks the Open or Save button.
HelpRequest Occurs when the user clicks the Help button.
o Font dialogs let the user select a font size, face, color, and so on. To display the
font dialog box, call the ShowDialog method. This dialog shows list boxes for
Font, Style, and Size, checkboxes for effects like Strikeout and Underline, and
a sample of how the font will appear. You can recover these settings using
properties of the same names of the Font object returned by the Font property.
o The FontDialog class displays a dialog box that lets the user select a font. It
returns a Font object in the Font property, and a Color object in the Color
property. Font dialogs are supported by the FontDialog class.
o Properties of FontDialog :
Property Description
Color Gets/sets the selected font color.
FixedPitchOnly Gets/sets whether the dialog box allows only the selection of
fixed-pitch fonts.
Font Gets/sets the selected font.
FontMustExist Gets/sets whether the dialog box specifies an error condition if
the user attempts to select a font or style that does not exist.
MaxSize Gets/sets the maximum point size a user can select.
MinSize Gets/sets the minimum point size a user can select.
ShowApply Gets/sets whether the dialog box contains an Apply button.
ShowColor Gets/sets whether the dialog box displays the color choice.
ShowEffects Gets/sets whether the dialog box contains controls that allow the
user to specify strikethrough, underline, and text color options.
ShowHelp Gets/sets whether the dialog box displays a Help button.
o Methods of FontDialog :
Method Description
Reset Resets all dialog options to default values.
ShowDialog Shows the dialog.
o Events of FontDialog :
Event Description
Apply Occurs when the user clicks the Apply button.
HelpRequest Occurs when the user clicks the Help button.
o Print dialogs let the user print documents, and these dialogs are supported with
the PrintDialog class. Before displaying a Print dialog, you set the Document
property of a PrintDialog object to a PrintDocument object, and the
PrinterSettings property to a PrinterSettings object of the kind set by Page
Setup dialogs.
o When the dialog is closed, you can print the document by assigning the
PrintDialog object's PrinterSettings property (which returns a PrinterSettings
object as configured by the user, indicating the number of copies to print, the
printer to use, and so on) to the PrinterSettings property of the PrintDocument
object and use the PrintDocument object's Print method to actually print the
document.
o Properties of PrintDialog :
Property Means
AllowPrintToFile Gets/sets whether the Print to file checkbox is enabled.
AllowSelection Gets/sets whether the Selection radio button is enabled.
AllowSomePages Gets/sets whether the From... To... Page radio button is
enabled.
Document Gets/sets the PrintDocument used to obtain
PrinterSettings.
PrinterSettings Gets/sets the PrinterSettings dialog box to modify.
PrintToFile Gets/sets whether the Print to file checkbox is checked.
ShowHelp Gets/sets whether the Help button is displayed.
ShowNetwork Gets/sets whether the Network button is displayed.
Method Means
Reset Resets all dialog options.
ShowDialog Shows the dialog.
MDI Concept:
Any windows can become an MDI parent, if you set the IsMdiContainer property to
True.
IsMdiContainer = true;
The following C# program shows a MDI form with two child forms. Create a new C#
project, then you will get a default form Form1 . Then add two mnore forms in the
project (Form2 , Form 3) . Create a Menu on your form and call these two forms on
menu click event. Click here to see how to create a Menu on your form How to Menu
Control C#.
NOTE: If you want the MDI parent to auto-size the child form you can code like this.
form.MdiParent = this;
form.Dock=DockStyle.Fill;
form.Show();
o The MDI NotePad sample application is a simple text editor similar to the
NotePad application included with Microsoft Windows.
o The MDI NotePad application, however, uses a multiple-document interface
(MDI). At run time, when the user requests a new document (implemented with
the New command on the application's File menu), the application creates a new
instance of the child form.
o This allows the user to create as many child forms, or documents, as necessary.
To create a document-centered application in Visual Basic, you need at least two forms
— an MDI form and a child form.
At design time, you create an MDI form to contain the application and a single child
form to serve as a template for the application's document.
To create your own MDI NotePad application
2. From the Project menu, choose Add MDI Form to create the container form.
The project should now contain an MDI form (MDIForm1) and a standard form
(Form1).
4. Set properties for the two forms and the text box as follows.
5.
6. Using the Menu Editor (from the Tools menu), create a File menu for
MDIForm1.
&File mnuFile No
7.
8. Add the following code to the mnuFileNew_Click procedure:
9. Private Sub mnuFileNew_Click ()
10. ' Create a new instance of Form1, called NewDoc.
11. Dim NewDoc As New Form1
12. ' Display the new form.
13. NewDoc.Show
14. End Sub
This procedure creates and then displays a new instance (or copy) of Form1,
called NewDoc. Each time the user chooses New from the File menu, an exact
duplicate (instance) of Form1 is created, including all the controls and code that it
contains.
Timer :
o Timers are very useful controls, because they let you create periodic events.
Strictly speaking, timers are no longer controls but components, and they do not
appear in a window at run time. At design time, they appear in the component tray
under the form you've added them.
o Windows timers are designed for a single-threaded (as opposed to multithreaded)
environment; you set how often you want the timer to generate Tick events by
setting the Interval property (in milliseconds, one thousandths of a second). Each
time a Tick event happens, you can execute code in a handler for this event, just
as you would for any other event.
o Properties of Timer :
Name Description
Name Description
o Event of Timer
Name Description
Tick Occurs when the timer interval has elapsed (and the timer is
enabled).
3. MouseHover/MouseDown/MouseWheel 4. MouseUp
5. MouseLeave
Property Purpose
Clicks Tells you how many times the mouse button was pressed and
released
Property Purpose
Handled Retrieves or returns a value to the property indicating whether the
KeyPress event was handled
KeyChar Retrieves the KeyChar (character pressed) value corresponding to
the key pressed Key events occur in the following order:
Link Label:
A Link Label control is a label control that can display a hyperlink. A Link
Label control is inherited from the Label Class so it has all the functionality
provided by the windows form label control.
Link Label control does not participate in user input or capture mouse or
keyboard events.
ADO.NET is a large set of .NET classes that enable us to retrieve and manipulate data,
and update data sources, in very many different ways.
Connected Architecture
Disconnected Architecture
1) Connected Architecture :
Connected Architecture simply means, you are connected with the database
throughout your operations.
Although connected architecture is faster then disconnected architecture, It has
one main problem of creating more traffic at database end.
Because you are constantly connected to database. And so do all other users.
DataReader is used to fetch the data DataSet or DataTable is used to fetch the
in Connected Architecture. data in Disconnected Architecture.
SQL Server Provider : This is special data provider which gives access to only
SQL Server database. It supports connection to SQL Server 7.0 or later. The
benefit of using this provider is it is faster as it directly deals with SQL Server.
Oracle Provider : This is special data provider which gives access to only
Oracle Server or client. It supports connection to Oracle 8i or later. The benefit of
using this provider is it is faster as it directly deals with Oracle database.
OLEDB Provider : This provider gives access to any database that has OLEDB
driver. The benefit of using OLEDB provider is you can connect with any
database using this.
ODBC Provider : This provider gives access to any database that has ODBC
(Open DataBase Connectivity) driver.
Use of Namespaces depends on which provider you choose. Some of the classes
are obtained from some common namespaces. But in order to use specific provider
you need to import specific namespace. Following table shows list of some
namespaces used in ADO.NET
Namespace Description
System.Data Contains fundamental classes with the core ADO.NET
functionality. This includes DataSet and DataRelation,
which allow you to manipulate structured relational
data. These classes are totally independent of any
specific type of database or the way you use to
connect to it.
System.Data.SqlClient Contains the classes you use to connect to a Microsoft
SQL Server database (version 7.0 or later). These
classes, such as SqlCommand and SqlConnection,
provide all the same roperties and methods as their
counterparts in the System.Data.OleDb namespace.
The only difference is that they are optimized for SQL
Server and provide better performance by eliminating
the extra OLE DB layer (and by connecting directly to
the optimized TDS interface).
System.Data.OracleClient Contains the classes you use to connect to an Oracle
database, such as OracleCommand and
OracleConnection.
System.Data.OLEDB Contains the classes you use to connect to an OLE DB
data source, including OleDbCommand and
OleDbConnection.
System.Data.ODBC Contains the classes you use to connect to a data
source through an ODBC driver. These classes
include OdbcCommand and OdbcConnection.
Depending on the namespace which you have imported, you can use provider
specific classes in order to use ADO.NET. Consider following table for provider
specific classes.
Connection :
o The first thing we need to do with a database application is establish a connection
to the database. ADO.NET handles this by using connection classes. In this article,
Michael Youssef shows you how to start using connection classes, with examples.
o When developing database applications using .NET, the very first thing that we
need is a connection to the database. ADO.NET provides us with connection
classes like the SqlConnection class and OleDbConnection class. The
SqlConnection class is part of the SQL Server .NET Data Provider. This data
provider has been designed for performance optimization with SQL Server 7.0 and
later.
o The OleDbConnection is part of the OLEDB .NET Data Provider, which is used to
access a data source that has an OLEDB Provider. In this article (and actually most
of my articles on ADO.NET) I use the SQL Server .NET Data Provider. So let's talk
a little about the SqlConnection class before we write code.
Property Description
Method Description
RollbackTrans Cancels any changes in the current transaction and ends the
transaction
Event Description
Command :
Property Description
Method Description
Event Description
DataReader :
o The DataReader object defines a lightweight yet powerful object that is used to
read information from a database.
o This is used under Connected Architecture. DataReader is used with Command
object in order to read (fetch) the data. But remember that DataReader can be
used to only read the data in sequential manner (forward only manner). You can
not go back or go on particular record directly.
Property Description
Method Description
Reads the next result in the result set into memory . The Read
method of the DataReader object is used to obtain a row from
the results of the query.
Read()
Each column of the returned row may be accessed by passing
the name or ordinal reference of the column to the
DataReader,
DataAdapter :
o DataAdapter is used under Disconnected Architecture. It plays an important role
in disconnected architecture. It allows you to fetch the data from database to
local memory of client and also to save the updated data back to database.
o In Disconnected Architecture we use DataSet or DataTable to fill the data which
resides in local memory. DataAdapter object does two important tasks as follows
o Fill data from Database to DataSet or DataTable
o Update the data back to Database
o DataAdapter fills the specified data into DataSet or DataTable which is in our
(client’s) local memory. After filling the data connection is automatically
terminated (closed) with DataAdapter. But now the data has been loaded into
DataSet or DataTable. All types of operations like INSERT, UPDATE, DELETE,
SELECT, etc. are performed locally in DataSet or DataTable.
o Properties of DataAdapter Object
Property Description
Method Description
Fill The Fill method is probably the DataAdapter method you will use most
frequently. Simply stated, the Fill method adds data from your data
source to a dataset. The Fill method accepts a variety of parameters
including the DataSet object to fill, a string representing the alias for the
newly created DataSet object, an integer representing the lower bound
of records to retrieve, and an integer representing the upper bound of
records to retrieve from our data source.
A DataSet object
Event Description
This event is raised while changes are being made in Row. When
you call Update() method, DataAdapter makes changes to actual
RowUpdating
database table. At that time, while being updating each row this
event is raised.
This event is raised after changes are done in Row. When you call
RowUpdated Update() method, DataAdapter makes changes to actual database
table. After changes have been done, this event is raised.
Property Description
Get the collection of relations that link tables and allow navigation
Relations
from parent tables to child tables.
Method Description
Commits all the changes made to this dataset since the last time
AcceptChanges()
AcceptChanges was called.
Method Description
Rolls back all changes that have been made to the dataset since
RejectChanges
it was loaded, or the last time AcceptChanges was called.
Method Description
DataTable :
o The DataTable object represents an in-memory database table. You can add
rows to a DataTable with a DataAdapter.
o A DataTable is defined in the ―System.Data‖ namespace and represents a single
table of memory-resident data. It contains a collection of columns represented by
Property Description
Method Description
Commits all the changes made to this table since the last time
AcceptChanges()
AcceptChanges was called.
NewRow() Creates a new DataRow with the same schema as the table.
Reads XML schema and data into the DataTable using the
ReadXml()
specified Stream or File
Rolls back all changes that have been made to the table since it
RejectChanges
was loaded, or the last time AcceptChanges was called.
Select Allows you to select group of data from table. It has different
methods to select the data. This is overloaded method which
Method Description
Event Description
o DataRow can contain any single row of any table. Whenever you store any
DataTables single row into object of DataRow, it automatically creates its column
as per source table.
o For example, your DataTable object has 6 columns, when you copy one row of
DataTable into DataRow object, DataRow object automatically creates 6 columns
for itself as per DataTable object.
o To populate a DataTable we add new DataRow objects to the DataTable.Rows
collection. Each DataRow can reference each DataColumn in the DataTable
schema. To create a new row in the DataTable, we invoke the
DataTable.NewRow method, which returns a DataRow using the DataTable's
current schema.
o DataRow objects represent rows in a DataTable object. You use DataRow
objects to get access to, insert, delete, and update the records in a table.
o To create a new DataRow object, you usually use the NewRow method of a
DataTable object, and after configuring the row with data, you can use the Add
method to add the new DataRow to the table. In addition, you also can call the
AcceptChanges method of the DataTable object to make that table treat the
new row as it would its original data.
o You can delete a DataRow from the Rows collection in a data table by calling
the Remove method, or by calling the Delete method of the DataRow object
itself. Note that the Remove removes the row from the collection, and the Delete
method simply marks the DataRow for deletion. (The actual deletion occurs
when you use the AcceptChanges method.)
Property Description
Method Description
DataColumn :
o DataColumn objects represent the columns, that is, the fields, in a data table. In
ADO.NET terms, the columns in a table specify its XML schema. When you
create a table and add columns to it, you specify the name of the column and the
type of data it stores.
o DataRow is collection of DataColumns. One DataRow can have multiple columns
within it because always a row contains multiple columns.
Property Description
Method Description
ToString Gets the Expression value for this column, if there is one.
DataView :
o When you bind to a DataTable, you actually use another object called the
DataView. The DataView sits between the ASP.NET web page binding and your
DataTable. Usually it does little aside from providing the information from the
associated DataTable. However, you can customize the DataView so it applies
its own sort order. That way, you can customize the data that appears in the web
page, without needing to actually modify your data.
o You can create a new DataView object by hand and bind the DataView directly to
a data control.
o Data views are much like read-only mini-datasets; you typically load only a
subset of a dataset into a data view.
o Data views represent a customized view of a single table that can be filtered,
searched, or sorted. In other words, a data view, supported by the DataView
class, is a data "snapshot" that takes up few resources.
o To create a filtered and sorted view of data, set the RowFilter and Sort
properties. Then use the Item property to return a single DataRowView.
o Properties of DataView Object
Property Description
AllowDelete Sets or gets a value that indicates whether deletes are allowed.
AllowEdit Gets or sets a value that indicates whether edits are allowed.
Gets or sets a value that indicates whether the new rows can be
AllowNew
added by using the AddNew method.
Count Gets the number of records in the DataView after RowFilter and
RowStateFilter have been applied.
IsOpen Gets a value that indicates whether the data source is currently
open and projecting views of data on the DataTable.
Item Gets a row of data from a specified table.
RowFilter Gets or sets the expression used to filter which rows are viewed in
the DataView.
Sort Gets or sets the sort column or columns, and sort order for the
DataView.
Table Gets or sets the source DataTable.
Method Description
Events Description
GridView :
o The GridView is an extremely flexible grid control that displays a multicolumn
table. Each
Property Description
Method Description
UpdateRow( )
Updates specified row from GridView.
:
Event Description
The next screen is the SQL Server authentication screen for connecting to
the database - crystalDB. Select your Sql Server name , enter userid ,
password and select your Database Name .
Click next , Then the screen shows OLE DB Property values , leave it as it
is , and then click finish button.
After you click the finish button , the next window you will get your
Server name under OLEDB Connection, from there selected database
name (Crystaldb) and click the tables , then you can see all your tables
from your database.
From the tables list double click the Product table then you can see the
Product table will come in the right side list.
Now the designing part is over and the next step is to call the Crystal
Reports in your C# application and view it through Crystal Reports Viewer
control in C#.
Select the default form (Form1.cs) you created in C# and drag a button
and a CrystalReportViewer control to your form .
After you drag the CrystalReportViewer to your form , it will look like the
following picture.
Report Sections:-
Sections are the design areas which you use to build your report.
Crystal Reports by default provides five main sections:
Report Header – fields placed in this section are printed once, at the
beginning of the report
Page Header - fields placed in this section are printed at the beginning of
each new page
Details – fields in this section are printed with each new record
Report Footer - fields placed in this section are printed once, at the end of the
report
Page Footer - fields placed in this section are printed at the bottom of each
new page
More sections will appear if you add groups or simply insert new one.
Click Section Expert button in the top menu. Section Expert contains a list
of all sections in the report
To delete a section:
To split sections:
Click on the on the boundary of the section you want to split. Horizontal
line that splits section will appear
Drag-and-drop it to the place where you want to split section
Formula Field:
The following C# - Crystal Reports section describes how to add a formula field
in the Crystal Reports .
Next step is to create a Formula Field for showing the result of Qty X Price .
Right Click the Formula Field in the Field Explorer and click New. Then you will
get an Input Message Box , type Total in textbox and click Use Editor.
Now you can see the Formula Editor screen . Here you can enter which formula
you want . Here we want the result of Qty X Price . For that we select
Now you can see Total Under the Formula Field . Drag the field in to the Crystal
Reports where you want to display Total.
Summary Field:
The following C# - Crystal Reports section describes how to add a summary field
in the Crystal Reports.
In the Crystal Reports designer view window, right click on the Report Footer ,
just below the Total field and select Insert -> Summary .
Then you will get a screen , select the Total from the combo box and select Sum
from next Combo Box , and summary location Grand Total (Report Footer) . Click
Ok button
Now you can see @Total is just below the Total field in the report Footer.
Setup projects are used to create Windows Installer (.msi) files, which are used
to distribute your application for installation on another computer or Web server.
There are two types of setup projects. Standard setup projects create installers
that install Windows applications on a target computer; Web setup projects
create installers that install Web applications on a Web server.
Note:
The dialog boxes and menu commands you see might differ from those described in
Help depending on your active settings or edition. To change your settings, choose
Import and Export Settings on the Tools menu. For more information, see Working with
Settings.
The File System editor presents a graphic representation of the files, folders,
and shortcuts your product installation creates or modifies on the target machine.
Use this editor to:
Add and delete files, folders, and shortcuts in the installer project.
–or–
As you work in the File System editor, you can add, modify, or delete folders,
files, and shortcuts with:
Note : You can display the context menu by right-clicking in the File System
editor. Context menu activated options differ depending on what is selected when
you right-click.
Note Actions menu active options differ depending on your current file or folder
selection.
The left pane of the File System editor shows a folder view of the target machine. You
can add and delete folders your product installs by setting them up here. You can also
establish contents of target machine folders. Microsoft® Visual Studio® Installer provides
these initial folders for you to work with:
Application Folder. Sets the root directory for your application on the target
machine.
User's Desktop. Place items (such as files or shortcuts) you want to install to the
user's desktop in this folder.
User's Start Menu. Place items (such as files or shortcuts) you want to install to
the user's Start menu in this folder.
Note If the installer project contains a Microsoft® Visual Basic® project with
dependencies that can't be mapped to merge modules, a fourth folder labeled
Windows System Folder is displayed in the left pane of the File System editor.
Here it is..
First of all we're creating a Resource File that will help us storing the skins:
After that open the resource file and "Add Resource->Add Existing File..."
Then add 4 sample skins(you can create your own skins named 'disabled','down','over'
and 'up'):
2. A Structure that will help us export the control List as an XML File
We are taking advantage of XML for the structure we will be building on GUI Editor & as
you can see we added elements as they are already properties of the controls.Actually it
would be a big mistake not to use XML in this kind of applications.
4. For Communication of Windows & XNA, creating a class where we will declare
"public static" variables