You are on page 1of 258

Windows Forms Applications

 C# supports two kinds of User Interfaces.


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

o G.U.I (Graphical User Interface)


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

Page 243 of 553


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

Windows Forms Application:

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


 It‘s a collection of windows forms.

A Windows Application

Login Form Registration Form

Data Entry Form Report Form

Page 244 of 553


Form:

 The graphical container, which


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

Creating a “Windows Forms Application” project:


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

Page 245 of 553


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

Page 246 of 553


Development of a Form

 It includes with two stages:


o Designing
o Coding

1) Designing the Form:

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

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

Page 247 of 553


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

Page 248 of 553


 Then the screen looks like this:

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

2) Coding the Form:

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

private void button1_Click(object sender, EventArgs e)


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

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

Page 249 of 553


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

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

 Every Form is a Class:

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


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

 The Automatic Generated Code:

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

Form1.Designer.cs:

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

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

.NET 4.0 and Visual Studio 2010 Page 250250 of


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

#region Windows Form Designer generated code


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

.NET 4.0 and Visual Studio 2010 Page 251 of 548


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

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

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

.NET 4.0 and Visual Studio 2010 Page 252 of 548


}

#endregion

private System.Windows.Forms.TextBox textBox1;


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

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

Class Definition Syntax of a Windows Form:

Form1.cs

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

.NET 4.0 and Visual Studio 2010 Page 253 of 548


Rules for the Form class definition:

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

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

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

.NET 4.0 and Visual Studio 2010 Page 254 of 548


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

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

.NET 4.0 and Visual Studio 2010 Page 255 of 548


Controls Handling Windows Applications
Common Properties for all the controls:

 The following properties commonly available for all the controls:

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

Common Events for all the controls:

 The following events commonly available for all the controls:

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

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

.NET 4.0 and Visual Studio 2010 Page 256 of 548


Application 80: Demo on Buttons

 Take a new Windows Forms Application project.


 Design the form as follows:

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

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

.NET 4.0 and Visual Studio 2010 Page 257 of 548


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

private void button1_Click(object sender, EventArgs e)


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

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

private void button2_Click(object sender, EventArgs e)


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

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

private void button3_Click(object sender, EventArgs e)


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

 Then finally run the application.

Changing Property Values at run time


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

.NET 4.0 and Visual Studio 2010 Page 258 of 548


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

Assign Property Values at Run Time


Property Statement to assign the value at run time

Name Not possible to change at run time.

Text controlname.Text = ―xxxxx‖;

Enabled controlname.Enabled = true / false;

Visible controlname.Visible = true / false;

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

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


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

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

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

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


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

TabIndex controlname.TabIndex = n;

ContextMenuStrip controlname.ContextMenuStrip = xxxxx;

.NET 4.0 and Visual Studio 2010 Page 259 of 548


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

Application 81: Demo on Changing Property Values at Run Time

.NET 4.0 and Visual Studio 2010 Page 260 of 548


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

private void button3_Click(object sender, EventArgs e)


{
button1.Enabled = false;
}

private void button4_Click(object sender, EventArgs e)


{
button1.Enabled = true;
}

private void button5_Click(object sender, EventArgs e)


{
button1.Visible = false;
}

private void button6_Click(object sender, EventArgs e)


{
button1.Visible = true;
}

private void button7_Click(object sender, EventArgs e)


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

private void button8_Click(object sender, EventArgs e)


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

private void button9_Click(object sender, EventArgs e)


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

private void button10_Click(object sender, EventArgs e)


{
button1.BackColor = Color.LightCoral;
}

private void button11_Click(object sender, EventArgs e)


{
button1.ForeColor = Color.Green;
}

private void button12_Click(object sender, EventArgs e)


{

.NET 4.0 and Visual Studio 2010 Page 261 of 548


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

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

Event Handler:

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

private void controlname_eventname(object sender, EventArgs e)


{
//some code
}

 In the above syntax, there are two arguments:


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

.NET 4.0 and Visual Studio 2010 Page 262 of 548


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

Implementation of Event Handler:

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

.NET 4.0 and Visual Studio 2010 Page 263 of 548


Application 82: Demo on Event Handling

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

private void button1_Click(object sender, EventArgs e)


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

private void button1_MouseEnter(object sender, EventArgs e)


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

private void button1_MouseLeave(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 264 of 548


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

Deleting a Form from the Project:


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

Changing Startup Form:


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

Invoke Forms at Run Time (Programmatically):


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

Application 83: Multiple Forms Handling

.NET 4.0 and Visual Studio 2010 Page 265 of 548


Form1.cs

private void Form1_DoubleClick(object sender, EventArgs e)


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

Controls in Windows Applications

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

.NET 4.0 and Visual Studio 2010 Page 266 of 548


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

.NET 4.0 and Visual Studio 2010 Page 267 of 548


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

.NET 4.0 and Visual Studio 2010 Page 268 of 548


The “System.Windows.Forms.Form” Class

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

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


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

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

.NET 4.0 and Visual Studio 2010 Page 269 of 548


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

Assign Form Property Values at Run Time


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

Text this.Text = ―xxxxxxxxxx‖;

ShowIcon this.ShowIcon = true / false;

ShowInTaskbar this.ShowInTaskbar = true / false;

MinimizeBox this.MinimizeBox = true / false;

MaximizeBox this.MaximizeBox = true / false;

HelpButton this.HelpButton = true / false;

ControlBox this.ControlBox = true / false;

Enabled this.Enabled = true / false;

AutoScroll this.AutoScroll = true / false;

TopMost this.TopMost = true / false;

IsMdiContainer this.IsMdiContainer = true / false;

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

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

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


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

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

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

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

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

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

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

Opacity this.Opacity = n;

.NET 4.0 and Visual Studio 2010 Page 270 of 548


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

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

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


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

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


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

.NET 4.0 and Visual Studio 2010 Page 271 of 548


Application 84: Demo on Form Events

private void Form1_Load(object sender, EventArgs e)


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

private void Form1_Move(object sender, EventArgs e)


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

private void Form1_Click(object sender, EventArgs e)


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

private void Form1_DoubleClick(object sender, EventArgs e)


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

private void Form1_FormClosed(object sender, FormClosedEventArgs e)


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

private void Form1_Resize(object sender, EventArgs e)


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

private void Form1_KeyPress(object sender, KeyPressEventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 272 of 548


Application 85: A Simple Demo on Form Properties

Design
Form1:
Text: Click the form

private void Form1_Click(object sender, EventArgs e)


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

Application 86: Demo on Form Properties

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

.NET 4.0 and Visual Studio 2010 Page 273 of 548


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

private void btnGreen_Click(object sender, EventArgs e)


{
this.BackColor = Color.Green;
}

private void btnBlue_Click(object sender, EventArgs e)


{
this.BackColor = Color.Blue;
}

Application 87: Demo on Form Properties

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

private void btnNormal_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Normal;
}

private void btnMinimize_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Minimized;
}

private void btnMaximize_Click(object sender, EventArgs e)


{

.NET 4.0 and Visual Studio 2010 Page 274 of 548


this.WindowState = FormWindowState.Maximized;
}

private void btnExit_Click(object sender, EventArgs e)


{
this.Close();
}

Application 88: Demo on Form Properties

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

private void btnShowBackgroundImage_Click(object sender, EventArgs e)


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

private void btnClearBackgroundImage_Click(object sender, EventArgs e)


{
this.BackgroundImage = null;
}

.NET 4.0 and Visual Studio 2010 Page 275 of 548


1) Button

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


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

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

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

.NET 4.0 and Visual Studio 2010 Page 276 of 548


2) Label

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


user.

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

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

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

.NET 4.0 and Visual Studio 2010 Page 277 of 548


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

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

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

.NET 4.0 and Visual Studio 2010 Page 278 of 548


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

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

Application 89: Demo on TextBox Design


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

private void btnOK_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 279 of 548


Application 90: Demo on TextBox

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

.NET 4.0 and Visual Studio 2010 Page 280


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

private void btnSubtract_Click(object sender, EventArgs e)


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

private void btnMultiply_Click(object sender, EventArgs e)


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

private void btnDivide_Click(object sender, EventArgs e)


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

Application 91: Demo on TextBox

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

.NET 4.0 and Visual Studio 2010 Page 281


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

Application 92: Demo on TextBox


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

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

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

private void btnGO_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 282


4) CheckBox

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

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

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

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

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

Application 93: Demo on CheckBox

.NET 4.0 and Visual Studio 2010 Page 283


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

5) RadioButton

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

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

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

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

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

.NET 4.0 and Visual Studio 2010 Page 284


Application 94: Demo on RadioButton

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

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

private void rbBeige_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.Beige;
}

private void rbLightGreen_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.LightGreen;
}

private void rbLightYellow_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.LightYellow;
}

private void rbBisque_CheckedChanged(object sender, EventArgs e)


{
this.BackColor = Color.Bisque;
}

.NET 4.0 and Visual Studio 2010 Page 285


6) LinkLabel
Used to create hyperlinks.

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

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

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

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

Application 95: Demo on LinkLabel

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

.NET 4.0 and Visual Studio 2010 Page 286


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

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

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

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

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

Application 96: Demo on PictureBox

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

.NET 4.0 and Visual Studio 2010 Page 287


using System.IO;

private void btnShow_Click(object sender, EventArgs e)


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

private void btnClearImage_Click(object sender, EventArgs e)


{
picBoxImage.Image = null;
}

private void rbNormal_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.Normal;
}

.NET 4.0 and Visual Studio 2010 Page 288


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

private void rbAutoSize_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.AutoSize;
}

private void rbCenter_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.CenterImage;
}

private void rbZoom_CheckedChanged(object sender, EventArgs e)


{
picBoxImage.SizeMode = PictureBoxSizeMode.Zoom;
}

.NET 4.0 and Visual Studio 2010 Page 289


8) Panel

This acts as container, which can contain other type


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

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

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

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

Application 97: Demo on Panel

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

.NET 4.0 and Visual Studio 2010 Page 290of 548


9) GroupBox

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


contains text also.

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

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

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

Application 98: Demo on GroupBox

.NET 4.0 and Visual Studio 2010 Page 291of 548


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

private void rbWhite_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.BackColor = Color.White;
}

private void rbRed_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.BackColor = Color.Red;
}

private void rbYellow_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.BackColor = Color.Yellow;
}

private void rbBlue_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.ForeColor = Color.Blue;
}

private void rbGreen_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.ForeColor = Color.Green;
}

private void rbOrange_CheckedChanged(object sender, EventArgs e)


{
txtMyTextBox.ForeColor = Color.Orange;
}

.NET 4.0 and Visual Studio 2010 Page 292of 548


10) ListBox

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

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

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

Sorted Enables / disables automatic sorting of items


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

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

Run Time Properties of ListBox


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

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

.NET 4.0 and Visual Studio 2010 Page 293of 548


Application 99: Demo on Single item Selection ListBox

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

private void lstCourses_SelectedIndexChanged(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 294of 548


Application 100: Demo on Single item Selection ListBox

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

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

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

textBox1:
Name: txtNewCity

.NET 4.0 and Visual Studio 2010 Page 295of 548


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

private void btnRemoveCity_Click(object sender, EventArgs e)


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

private void btnClearAll_Click(object sender, EventArgs e)


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

private void btnShowCount_Click(object sender, EventArgs e)


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

label1:

.NET 4.0 and Visual Studio 2010 Page 296of 548


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

.NET 4.0 and Visual Studio 2010 Page 297of 548


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

11) ComboBox

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


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

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

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

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

Run Time Properties of ComboBox


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

.NET 4.0 and Visual Studio 2010 Page 298of 548


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

Application 102: Demo on ComboBox

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

.NET 4.0 and Visual Studio 2010 Page 299of 548


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

12) NumericUpDown

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

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

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

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

.NET 4.0 and Visual Studio 2010 Page 300of 548


13) DomainUpDown

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

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

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

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

Run Time Properties of DomainUpDown


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

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

Application 103: Demo on NumericUpDown and DomainUpDown

.NET 4.0 and Visual Studio 2010 Page 301of 548


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

private void ChangeFont()


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

private void domFont_SelectedItemChanged(object sender, EventArgs e)


{
ChangeFont();
}

.NET 4.0 and Visual Studio 2010 Page 302of 548


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

14) DateTimePicker

This control enables the user, to select a date


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

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

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

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

Application 104: Demo on DateTimePicker

.NET 4.0 and Visual Studio 2010 Page 303of 548


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

private void Form1_Load(object sender, EventArgs e)


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

private void dtPickerDOB_ValueChanged(object sender, EventArgs e)


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

15) MonthCalendar

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


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

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

.NET 4.0 and Visual Studio 2010 Page 304of 548


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

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

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

Application 105: Demo on MonthCalendar

.NET 4.0 and Visual Studio 2010 Page 305of 548


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

private void monCalMyDate_DateChanged(object sender, DateRangeEventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 306of 548


16) TrackBar

Similar to numericupdown, but it offers


visualization for the value selection.

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

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

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

Application 106: Demo on TrackBar

.NET 4.0 and Visual Studio 2010 Page 307of 548


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

private void trkFontSize_Scroll(object sender, EventArgs e)


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

17) Timer

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


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

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

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

Application 107: Demo on Timer

.NET 4.0 and Visual Studio 2010 Page 308of 548


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

private void Form1_Load(object sender, EventArgs e)


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

private void tmrTime_Tick(object sender, EventArgs e)


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

Application 108: Demo on Timer

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

.NET 4.0 and Visual Studio 2010 Page 309of 548


int n = 0;

private void tmrBackColor_Tick(object sender, EventArgs e)


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

18) ProgressBar

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


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

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

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

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

.NET 4.0 and Visual Studio 2010 Page 310 of 548


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

Application 109: Demo on Progress Bar

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

.NET 4.0 and Visual Studio 2010 Page 311 of 548


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

using System.IO;

private void OpenFile()


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

private void btnOpen_Click(object sender, EventArgs e)


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

private void tmrFileOpen_Tick(object sender, EventArgs e)


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

19) MenuStrip

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


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

.NET 4.0 and Visual Studio 2010 Page 312 of 548


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

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

Each menu item will be created as a control for


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

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

Properties of Menu Item


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

Application 110: Demo on MenuStrip

.NET 4.0 and Visual Studio 2010 Page 313 of 548


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

private void showToolStripMenuItem_Click(object sender, EventArgs e)


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

private void clearToolStripMenuItem_Click(object sender, EventArgs e)


{
this.BackgroundImage = null;
}

private void normalToolStripMenuItem_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Normal;
}

private void minimizedToolStripMenuItem_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Minimized;
}

private void maximizedToolStripMenuItem_Click(object sender, EventArgs e)


{
this.WindowState = FormWindowState.Maximized;
}

.NET 4.0 and Visual Studio 2010 Page 314 of 548


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

private void form2ToolStripMenuItem_Click(object sender, EventArgs e)


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

private void form3ToolStripMenuItem_Click(object sender, EventArgs e)


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

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

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

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

Application 111: Demo on ContextMenuStrip

Design the following two context menus in Form1.

.NET 4.0 and Visual Studio 2010 Page 315 of 548


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

.NET 4.0 and Visual Studio 2010 Page 316 of 548


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

private void displayIconToolStripMenuItem_Click(object sender, EventArgs e)


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

private void redToolStripMenuItem_Click(object sender, EventArgs e)


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

private void greenToolStripMenuItem_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 317of 548


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

private void showInTaskBarToolStripMenuItem_Click(object sender, EventArgs e)


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

private void upperCaseToolStripMenuItem_Click(object sender, EventArgs e)


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

private void lowerCaseToolStripMenuItem_Click(object sender, EventArgs e)


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

private void clearToolStripMenuItem_Click(object sender, EventArgs e)


{
txtMyText.Clear();
}

.NET 4.0 and Visual Studio 2010 Page 318of 548


Dialog Controls

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


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

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

21) ColorDialog

Displays a dialog box, for a color selection.

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

 To invoke the dialog box at run time:


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

.NET 4.0 and Visual Studio 2010 Page 319of 548


Application 112: Demo on ColorDialog

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

private void btnBackColor_Click(object sender, EventArgs e)


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

22) FontDialog

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

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

 To invoke the dialog box at run time:


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

.NET 4.0 and Visual Studio 2010 Page 320of 548


Application 113: Demo on FontDialog

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

private void btnFont_Click(object sender, EventArgs e)


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

23) FolderBrowserDialog

Displays a dialog box, for a folder selection.

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

 To invoke the dialog box at run time:


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

.NET 4.0 and Visual Studio 2010 Page 321of 548


Application 114: Demo on FolderBrowserDialog

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

.NET 4.0 and Visual Studio 2010 Page 322of 548


using System.IO;

private void btnBrowseFolder_Click(object sender, EventArgs e)


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

24) OpenFileDialog

Displays a dialog box, for a file selection for


opening of a file.

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

 To invoke the dialog box at run time:


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

Application 115: Demo on OpenFileDialog

.NET 4.0 and Visual Studio 2010 Page 323of 548


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

.NET 4.0 and Visual Studio 2010 Page 324of 548


using System.IO;

private void btnOpen_Click(object sender, EventArgs e)


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

private void btnBrowse_Click(object sender, EventArgs e)


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

25) SaveFileDialog

Displays a dialog box, for a file selection for


saving a file.

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

 To invoke the dialog box at run


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

Application 116: Demo on SaveFileDialog

.NET 4.0 and Visual Studio 2010 Page 325of 548


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

.NET 4.0 and Visual Studio 2010 Page 326of 548


using System.IO;

private void btnBrowse_Click(object sender, EventArgs e)


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

private void btnSave_Click(object sender, EventArgs e)


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

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

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

 To invoke the dialog box at run time:


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

.NET 4.0 and Visual Studio 2010 Page 327of 548


Application 117: Demo on PrintDialog

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

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

private void btnBrowse_Click(object sender, EventArgs e)


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

private void btnPrint_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 328of 548


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

27) RichTextBox

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

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

Run Time Properties of RichTextBox


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

.NET 4.0 and Visual Studio 2010 Page 329of 548


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

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

Application 118: Demo on RichTextBox

.NET 4.0 and Visual Studio 2010 Page 330of 548


bool IsFileSaved = true;

private void newToolStripMenuItem_Click(object sender, EventArgs e)


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

private void openToolStripMenuItem_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 331of 548


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

private void saveToolStripMenuItem_Click(object sender, EventArgs e)


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

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)


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

private void printToolStripMenuItem_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 332of 548


}
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)


{
Application.Exit();
}

private void undoToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Undo();
}

private void redoToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Redo();
}

private void cutToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Cut();
}

private void copyToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Copy();
}

private void pasteToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.Paste();
}

private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.SelectAll();
}

private void clearToolStripMenuItem_Click(object sender, EventArgs e)


{
rtbMyText.SelectedText = "";
}

private void fontToolStripMenuItem_Click(object sender, EventArgs e)


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

private void backgroudColorToolStripMenuItem_Click(object sender, EventArgs e)


{

.NET 4.0 and Visual Studio 2010 Page 333of 548


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

private void foregroundColorToolStripMenuItem_Click(object sender, EventArgs e)


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

private void rtbMyText_TextChanged(object sender, EventArgs e)


{
IsFileSaved = false;
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 334of 548


28) NotifyIcon

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

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

 Set the “Icon” Property:


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

Application 119: Demo on NotifyIcon

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

private void Form1_Load(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 335of 548


29) TabControl

Displays multiple tab pages. Each tab page contains other


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

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

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

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

Application 120: Demo on TabControl

Design the form with the following 3 tabs.

.NET 4.0 and Visual Studio 2010 Page 336of 548


Design
tabPage1:
Text: Enter Numbers

tabPage2:
Text: Choose Action

tabPage3:
Text: Get Result

label1:
Name: lblFirstValue
Text: Enter First Value:

label2:
Name: lblSecondValue
Text: Enter Second Value:

textBox1:
Name: txtFirstValue

textBox2:
Name: txtSecondValue

button1:
Name: btnAdd
Text: +

button2:
Name: btnMultiply
Text: *

label3:
Name: lblResult
Text: Result:

textBox3:
Name: txtResult
ReadOnly: True

private void btnAdd_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 337of 548


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

30) TreeView

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


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

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

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

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

Run Time Properties of TreeView


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

.NET 4.0 and Visual Studio 2010 Page 338of 548


Application 121: Demo on TreeView

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

button1:
Name: btnExpandAll
Text: Expand All

button2:
Name: btnCollapseAll
Text: Collapse All

label1:
Name: lblSelectedNode
Text: Selected Node:

label2:
Name: lblSelectedNodePath
Text: Selected Node Path:

private void treeMyTree_AfterSelect(object sender, TreeViewEventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 339of 548


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

private void btnCollapseAll_Click(object sender, EventArgs e)


{
treeMyTree.CollapseAll();
}

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

.NET 4.0 and Visual Studio 2010 Page 340of 548


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

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

Features of MDI Applications:

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

Implementation of MDI Applications in C#:


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

.NET 4.0 and Visual Studio 2010 Page 341of 548


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

Application 122: Demo on MDI Applications

Design
Form1:
IsMdiContainer: True

Form1.cs

private void Form1_Load(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 342of 548


Application 123: Demo on MDI Applications (with Menu)

.NET 4.0 and Visual Studio 2010 Page 343of 548


Form1.cs

private void form2ToolStripMenuItem_Click(object sender, EventArgs e)


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

private void form3ToolStripMenuItem_Click(object sender, EventArgs e)


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

private void form4ToolStripMenuItem_Click(object sender, EventArgs e)


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

private void closeToolStripMenuItem_Click(object sender, EventArgs e)


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

private void exitToolStripMenuItem_Click(object sender, EventArgs e)


{
this.Close();
}

private void pinkToolStripMenuItem_Click(object sender, EventArgs e)


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

private void cyanToolStripMenuItem_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 344of 548


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

The “MessageBox” class


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

 Library: System.Windows.Forms.MessageBox

 Syntax:

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

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

MessageBoxButtons.xxxxxx);

Possible MessageBoxButton Models:

1) MessageBoxButtons.OK

2) MessageBoxButtons.OKCancel

3) MessageBoxButtons.YesNo

4) MessageBoxButtons.YesNoCancel

5) MessageBoxButtons.RetryCancel

6) MessageBoxButtons.AbortRetryIgnore

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

.NET 4.0 and Visual Studio 2010 Page 345of 548


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

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

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

 Create the control objectL

 ControlClassname obj = new ControlClassname();

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

 obj.property = value;

 Add the controls to the container:

 containername.Add(value);

Application 124: Demo on Adding Controls at run Time

Design
button1:
Text: Add Exit Button

.NET 4.0 and Visual Studio 2010 Page 346of 548


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

private void Exit_Click(object sender, EventArgs e)


{
Application.Exit();
}

Output:

.NET 4.0 and Visual Studio 2010 Page 347of 548


Application 125: Demo on Adding Controls at run Time

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

.NET 4.0 and Visual Studio 2010 Page 348of 548


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

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


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

private void Number_Click(object sender, EventArgs e)


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

Output:

.NET 4.0 and Visual Studio 2010 Page 349of 548


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

User Control (vs) Form


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

Implementation of User Controls

 Create the User Control:


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

 Design and Develop the User Control:


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

.NET 4.0 and Visual Studio 2010 Page 350of 548


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

Application 126: Demo on User Controls

 Create the Windows Application Project.


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

.NET 4.0 and Visual Studio 2010 Page 351of 548


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

private void Title_Load(object sender, EventArgs e)


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

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

private void timer1_Tick(object sender, EventArgs e)


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

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


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

.NET 4.0 and Visual Studio 2010 Page 352of 548


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

Windows Forms Control Library


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

Implementation Steps of “Windows Forms Control Library”

 Create the “Windows Forms Control Library”:


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

.NET 4.0 and Visual Studio 2010 Page 353of 548


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

 Design and Develop the User Control:


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

 Invoke the User Control from other Windows Application Project:


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

Application 127: Demo on WindowsFormsControlLibrary

Windows Forms Control Library Project Name: GlobalControlsLibrary


Windows Application Project Name: GlobalControlsTest

.NET 4.0 and Visual Studio 2010 Page 354of 548


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

 Set the properties of ―Timer1‖


 Enabled: True
 Interval: 1000

.NET 4.0 and Visual Studio 2010 Page 355of 548


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

private void Title_Load(object sender, EventArgs e)


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

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

private void timer1_Tick(object sender, EventArgs e)


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

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


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

II) Client Application Development:

 Create a new windows application project.


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

.NET 4.0 and Visual Studio 2010 Page 356of 548


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

.NET 4.0 and Visual Studio 2010 Page 357 of 548


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

.NET 4.0 and Visual Studio 2010 Page 358 of 548


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

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

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

Implementation:

private void Form1_Paint(object sender, PaintEventArgs e)


{
Graphics g = this.CreateGraphics();
}

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

Drawing the GDI Graphics

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

.NET 4.0 and Visual Studio 2010 Page 359 of 548


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

3) Drawing Circles / Elipses


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

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

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

.NET 4.0 and Visual Studio 2010 Page 360 of 548


Application 128: Demo on GDI (Drawing Lines)

private void Form1_Paint(object sender, PaintEventArgs e)


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

Application 129: Demo on GDI (Drawing Lines)

.NET 4.0 and Visual Studio 2010 Page 361 of 548


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

Application 130: Demo on GDI (Drawing Lines)

private void Form1_Paint(object sender, PaintEventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 362 of 548


Application 131: Demo on GDI (Drawing Lines)

private void Form1_MouseMove(object sender, MouseEventArgs e)


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

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

.NET 4.0 and Visual Studio 2010 Page 363 of 548


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

Application 133: Demo on GDI (Drawing Circles)

.NET 4.0 and Visual Studio 2010 Page 364 of 548


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

Application 134: Demo on GDI (Drawing Filled Objects)

private void Form1_Paint(object sender, PaintEventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 365 of 548


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

Application 135: Demo on GDI (Drawing Filled Objects)

private void Form1_Paint(object sender, PaintEventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 366 of 548


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

 Enter the following values:


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

.NET 4.0 and Visual Studio 2010 Page 367 of 548


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

.NET 4.0 and Visual Studio 2010 Page 368 of 548


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

.NET 4.0 and Visual Studio 2010 Page 369 of 548


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

.NET 4.0 and Visual Studio 2010 Page 370 of 548


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

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

 Close the window finally.

.NET 4.0 and Visual Studio 2010 Page 371 of 548


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

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

.NET 4.0 and Visual Studio 2010 Page 372 of 548


 Then the SQL statement will be executed.

7. IMP SQL Statements:


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

2. DROP
 drop table tablename;

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

.NET 4.0 and Visual Studio 2010 Page 373 of 548


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

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

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

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

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

Some exercise on SQL:

use master
drop database test
GO

create database test


GO

use test
GO

create table Products


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

.NET 4.0 and Visual Studio 2010 Page 374 of 548


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

select * from products

select ProductID,ProductName from Products

select Price*10/100 Tax from Products

select * from Products where Productid=104

select * from Products order by price desc

select * from Products where price between 2000 and 8000

select * from Products where price not between 2000 and 8000

select * from Products where price like '%0.00'

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

update products set price=price+1000

select * from products

delete from products where price<1500

select * from products

.NET 4.0 and Visual Studio 2010 Page 375 of 548


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

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

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

.NET 4.0 and Visual Studio 2010 Page 376 of 548


Some exercise on T-SQL:

Procedure:

create procedure ShowSquare(@a int)


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

GO
execute ShowSquare 5

Function:

create function GetCube(@a int) returns int


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

GO

select dbo.GetCube(5)

.NET 4.0 and Visual Studio 2010 Page 377 of 548


ADO.NET
(ActiveX Data Objects.NET)

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


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

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


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

.NET 4.0 and Visual Studio 2010 Page 378 of 548


What we can do using ADO.NET:

 Insert some data into the database table.


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

ADO.NET Database Connection Architecture

Driver .NET Application


db

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

For various databases, we have respective providers.


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

.NET 4.0 and Visual Studio 2010 Page 379 of 548


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

Syntax of Connection String:


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

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

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

.NET 4.0 and Visual Studio 2010 Page 380 of 548


Data

DataSet

DataTable

DataRow

DataColumn

SqlClient OleDb

SqlConnection OleDbConnection

SqlCommand OleDbCommand

SqlDataReader OleDbDataReader

SqlDataAdapter OleDbDataAdapter

SqlParameter OleDbParameter

ADO.NET NameSpaces:

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

.NET 4.0 and Visual Studio 2010 Page 381 of 548


ADO.NET Classes:

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

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

.NET 4.0 and Visual Studio 2010 Page 382 of 548


Connecting the Database

 Library: SqlConnection / OleDbConnection

Connection
 ConnectionString
 Open()
 Close()

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

Connecting with SQL Server:


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

.NET 4.0 and Visual Studio 2010 Page 383 of 548


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

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


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

 Open the connection:


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

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

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


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

.NET 4.0 and Visual Studio 2010 Page 384 of 548


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

private void databaseConnectionDemoToolStripMenuItem_Click(object sender,


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

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


shown:

.NET 4.0 and Visual Studio 2010 Page 385 of 548


 Write the code:

.NET 4.0 and Visual Studio 2010 Page 386 of 548


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

private void button1_Click(object sender, EventArgs e)


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

private void button2_Click(object sender, EventArgs e)


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

private void button3_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 387 of 548


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

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

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

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

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

5) Stored Procedure / Function Command:


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

.NET 4.0 and Visual Studio 2010 Page 388 of 548


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

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

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


/ deletion statement / updation statement / select statement)

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


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

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

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


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

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


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

.NET 4.0 and Visual Studio 2010 Page 389 of 548


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

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


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

Implementation Code for SQL Server:


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

.NET 4.0 and Visual Studio 2010 Page 390 of 548


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

.NET 4.0 and Visual Studio 2010 Page 391 of 548


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

 Open the previous demo application.


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

.NET 4.0 and Visual Studio 2010 Page 392 of 548


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

Form1.cs

private void insertionToolStripMenuItem_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 393 of 548


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

private void updationToolStripMenuItem_Click(object sender, EventArgs e)


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

 Design the ―Insertion‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 394 of 548


 Write the code:

Insertion.cs

using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(5,'Arun','Male',8000)";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");

cn.Close();
}

private void button2_Click(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(" + textBox1.Text + ",' " +
textBox2.Text + " ',' " + gen + " '," + textBox3.Text + ")";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();

.NET 4.0 and Visual Studio 2010 Page 395 of 548


if (n > 0)
MessageBox.Show(n + " Row Inserted.");
else
MessageBox.Show("Insertion failed.");

cn.Close();
}

Note: While you are preparing the CommandText with user-entered values, to remember the
concatenation syntax in the above example, remember the following syntax:

" + textBox1.Text + "

 Design the ―Deletion‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 396 of 548


 Write the code:

Deletion.cs

using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from customers where customerid=" + textBox1.Text
+ " ";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();

//presentation logic
if (n > 0)
MessageBox.Show(n + " Row Deleted.");
else
MessageBox.Show("Deletion failed.");

cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 397 of 548


 Design the ―Updation‖ form as follows:

 Write the code:

Updation.cs

using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";

.NET 4.0 and Visual Studio 2010 Page 398 of 548


//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "update customers set customername= ' " + textBox2.Text +
" ' ,gender= ' " + gen + " ' ,amount=" + textBox3.Text + " where customerid=" +
textBox1.Text + " ";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();

//presentation logic
if (n > 0)
MessageBox.Show(n + " Row Updated.");
else
MessageBox.Show("Updation failed.");

cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 399 of 548


Retrieving Data from the Database
 For retrieving the table data from the database, you write a select statement (query
statement) in the frontend code.
 Next, you need to pass it to backend using ―Command‖ class object.
 Then your select statement will be executed at backend. Then the DBMS (Oracle / SQL
Server / My SQL etc.), returns the result data, based on the executed query. For
example, if your statement is ―select * from departments‖, then the entire departments
table data will be returned as it is.
 Then frontend, you have to receive the data into a temporary memory location (buffer).
To create a buffer in your code, you can use ―DataReader‖ class.
 After that, you can present the data on the screen for the user.
 This is the flow of data. You can observe this flow in the following diagram.

Connection

(provider, data Command


db source, user id,
DataReader
(select stmt, cn)
password)

.NET
Application

.NET 4.0 and Visual Studio 2010 Page 400 of 548


Library:
 Connection: Maintains the connection with database.
 Command: Sends a SQL statement and executes it at backend.
 DataReader: Acts as a buffer. It holds the data, which is received from database.

Note: Here, to execute the select statement, you have to use ―ExecuteReader()‖ method of
command class. After execution of the statement, it returns the entire data, i.e. retrieved from
the database, in the form of ―DataReader‖ class object. So that we have to receive it into an
instance of ―DataReader‖ class.

Classes, to be used in this concept:

Connection
 ConnectionString
 Open()
 Close()

Command
 CommandText
 Connection
 CommandType
 Parameters
 ExecuteNonQuery()
 ExecuteReader()

DataReader
 Read()
 [“column_name”]
 [index]
 Close()

Understanding the “DataReader” class:


 It‘s known as buffer. It‘s not visible; it stores the data in the memory.
 It contains the data in the form of a table itself.

.NET 4.0 and Visual Studio 2010 Page 401 of 548


Ex:

 Library: SqlDataReader / OleDbDataReader

a) Read(): This method moves the record pointer, to the next record. For the first
time call of this method, the record pointer point-outs the first record. After that,
for every call it jumps to next record. If the next record is found, then it returns
―true‖; if the next record is not found, that means whenever it is reached end of
the data, then it returns ―False‖.
Ex:

dr.Read();

(true)

.NET 4.0 and Visual Studio 2010 Page 402 of 548


dr.Read();

(true)

dr.Read();

(true)

dr.Read();

(true)

dr.Read();

(false)

.NET 4.0 and Visual Studio 2010 Page 403 of 548


b) [“column name”]: This indexer gets the value, at the specified column name,
in the current row, which is currently pointed-out by the record pointer.

c) [index]: This indexer gets the value, at the specified column index, in the
current row, which is currently pointed-out by the record pointer. The column
index always starts from ―0‖.

d) Close(): This method closes the buffer. At the end of your code, you can close
it.

Implementation Code for SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―select statement‖;
 Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
 Construct the “DataReader” class object:
SqlDataReader dr;
 Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();

.NET 4.0 and Visual Studio 2010 Page 404 of 548


 Read the next row.
dr.Read();
 Get the value at specific column:
dr[column index];
(or)
dr[―column_name‖];
 Close the buffer:
dr.Close();
 Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
 Assign the SQL statement, which is to be executed:
cmd.CommandText = ―select statement‖;
 Assign the reference of connection object, based which the command is to
be executed:
cmd.Connection = cn;
 Construct the “DataReader” class object:
OleDbDataReader dr;
 Execute the command and receive the data into the buffer:
dr = cmd.ExecuteReader();

.NET 4.0 and Visual Studio 2010 Page 405 of 548


 Read the next row.
dr.Read();
 Get the value at specific column:
dr[column index];
(or)
dr[―column_name‖];
 Close the buffer:
dr.Close();
 Close the connection:
cn.Close();

.NET 4.0 and Visual Studio 2010 Page 406 of 548


Demo:

 Open the previous demo application.


 Add the menu item ―Retrievals‖ and design the menu as shown below:

 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as
―DataReaderDemo‖. Click on ―Add‖.
 Double click on the ―View Data using Data Reader‖ menu item and write the code:

Form1.cs

private void viewDataUsingDataReaderToolStripMenuItem_Click(object sender,


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

.NET 4.0 and Visual Studio 2010 Page 407 of 548


 Design the ―DataReaderDemo‖ form as follows:

 Write the Code:

DataReaderDemo.cs

using System.Data.SqlClient;

private void DataReaderDemo_Load(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;

//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();

.NET 4.0 and Visual Studio 2010 Page 408 of 548


//presentation / buffer logic
while (dr.Read() == true)
{
listBox1.Items.Add(dr[0] + " -- " + dr[1] + " -- " + dr[2] + " -- " + dr[3]);
}

dr.Close();
cn.Close();
}

 Sometimes, you may need to display the records one-by-one, when the user clicks ―Next‖
button. We take a demonstration like that:

 Add the menu item ―View Data using Data Reader – Record-by-Record‖ as shown below:

.NET 4.0 and Visual Studio 2010 Page 409 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as
―DataReaderDemo_RecordByRecord‖. Click on ―Add‖.
 Double click on the ―View Data using Data Reader – Record-by-Record‖ menu item and
write the code:

Form1.cs

private void viewDataUsingDataReaderRecordbyRecordToolStripMenuItem_Click(object


sender, EventArgs e)
{
DataReaderDemo_RecordByRecord f = new DataReaderDemo_RecordByRecord();
f.MdiParent = this;
f.Show();
}

 Design the ―DataReaderDemo_RecordByRecord‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 410 of 548


 Write the Code:

DataReaderDemo_RecordByRecord.cs

using System.Data.SqlClient;

public partial class DataReaderDemo_RecordByRecord : Form


{
public DataReaderDemo_RecordByRecord()
{
InitializeComponent();
}

SqlDataReader dr;
SqlConnection cn = new SqlConnection();

private void DataReaderDemo_RecordByRecord_Load(object sender, EventArgs e)


{
//Connection impl
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;

//DataReader impl
dr = cmd.ExecuteReader();

//presentation / buffer logic


if (dr.Read() == true)
{
textBox1.Text = Convert.ToString(dr[0]);
textBox2.Text = Convert.ToString(dr[1]);
if (Convert.ToString(dr[2]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(dr[3]);
}
else
MessageBox.Show("No Data Found...");
}

private void button1_Click(object sender, EventArgs e)


{
if (dr.Read() == true)

.NET 4.0 and Visual Studio 2010 Page 411 of 548


{
textBox1.Text = Convert.ToString(dr[0]);
textBox2.Text = Convert.ToString(dr[1]);
if (Convert.ToString(dr[2]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(dr[3]);
}
else
MessageBox.Show("No Data Found...");
}

private void DataReaderDemo_RecordByRecord_FormClosing(object sender,


FormClosingEventArgs e)
{
dr.Close();
cn.Close();
}
}

 Sometimes, you may need to display the records based on the user-entered value. For
example, when the user enters the customer id, then you need to display the respective
customer details. We take a demonstration like that:

 Add the menu item ―View Data using Data Reader - Conditional Data‖ as shown below:

.NET 4.0 and Visual Studio 2010 Page 412 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as
―DataReaderDemo_ConditionalData‖. Click on ―Add‖.
 Double click on the ―View Data using Data Reader - Conditional Data‖ menu item and
write the code:

Form1.cs

private void viewDataUsingDataReaderConditionalDataToolStripMenuItem_Click(object


sender, EventArgs e)
{
DataReaderDemo_ConditionalData f = new DataReaderDemo_ConditionalData();
f.MdiParent = this;
f.Show();
}

 Design the ―DataReaderDemo_ConditionalData‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 413 of 548


 Write the Code:

DataReaderDemo_ConditionalData.cs

using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select customername,gender,amount from customers where
customerid=" + textBox1.Text + "";
cmd.Connection = cn;

//DataReader impl
SqlDataReader dr;

.NET 4.0 and Visual Studio 2010 Page 414 of 548


dr = cmd.ExecuteReader();

//presentation / buffer logic


if (dr.Read() == true)
{
textBox2.Text = Convert.ToString(dr[0]);
if (Convert.ToString(dr[1]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(dr[2]);
}
else
MessageBox.Show("No Data Found...");

dr.Close();
cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 415 of 548


ADO.NET Disconnected Model
 ADO.NET database connection is of two types:
1. Connected Model:
 Implemented with ―DataReader‖ buffer.
2. Disconnected Model:
 Implemented with ―DataSet‖, ―DataTable‖, ―DataRow‖ buffers.

 To overcome the limitations of ―Connected Model‖, ADO.NET introduces ―Disconnected


Model‖.
 The main advantage of ―Disconnected Model‖ is, even though the connected is not
opened, it works. That means, when you execute any statement, the connected will be
opened, then the statement will be executed and then finally the connected will be
closed.
 But the connected model is not like that. If you take the buffer called ―data reader‖
which is used in the connected model, it works when the connection is opened only. But
the ―disconnected model‖ buffers work even though the connection is opened or not.
 In the connected model, we were using only one buffer.
1. DataReader
 In the disconnected model, three buffers are used.
1. DataSet
2. DataTable
3. DataRow

Library:
 Connection: Maintains the connection with database.

 DataAdapter: Sends a sql statement and executes it at backend. It‘s just like Command
class, in the connection oriented model. The difference between Command class and
DataAdapter class is, the ―Command‖ class is used to execute any type of statement
(insert statement, delete statement, update statement and select statement). But
adapter executes select statement only.

.NET 4.0 and Visual Studio 2010 Page 416 of 548


 DataSet: Holds the data that is received from database, after execution of DataAdapter.
It can hold multiple tables data at-a-time. In other words, it contains an array of tables.

 DataTable: Holds a single table, from the DataSet.

 DataRow: Holds a single row, from the DataTable.

Limitations of Connection Oriented Model


(or)

Advantages of Disconnected Model

 The ―DataReader‖ works only when the connection is closed. But the ―DataTable‖ works
even though the database is disconnected.
 The ―DataReader‖ buffer supports record travelling only once in its lifetime. But the
―DataTable‖ buffer supports record travelling any no. of times in its life time.
 The ―DataReader‖ buffer supports only forward record travelling. It doesn‘t supports
backward or random record travels. But ―DataTable‖ supports forward, backward and
random record travels.
 ―DataReader‖ supports sequential records travels only. It doesn‘t supports to pick-up a
record directly with its index. But ―DataTable‖ supports to pick-up a record directly with
its index.
 ―DataReader‖ supports only column indexing. ―DataTable‖ supports both column and row
indexing.
 ―DataReader‖ data can‘t be assigned to ―DataGridView‖ control. But the ―DataTable‖ data
can be assigned to the ―DataGridView‖ control.

.NET 4.0 and Visual Studio 2010 Page 417 of 548


Diagrammatical View of Disconnected Model:

Connection

(provider, data DataAdapter Fill()


db source, user id, (select stmt, cn)
password)

DataSet

DataTable
0
1
2
3

.NET DataRow
Application 0 1 2

.NET 4.0 and Visual Studio 2010 Page 418 of 548


Classes, to be used in this concept:

Connection
 ConnectionString
 Open()
 Close()

DataAdapter
 DataAdapter(“select statement”, connection_object)
 Fill(dataset_object)

DataSet
 Tables[table_index]
 Clear()

DataTable
 Rows.Count
 Rows[row_index]
 Columns.Count
 Columns[column_index]

DataRow
 [column_index]
 [“column name”]

Understanding the “DataAdapter” class:


 Tables[table_index]: Gets the entire table, from the ―Tables‖ array, based on the
given index. So, ―Tables‖ is an array here.

 Clear(): Clears all the tables, and makes the dataset empty.

.NET 4.0 and Visual Studio 2010 Page 419 of 548


Understanding the “DataTable” class:
 Rows.Count: Gets the no. of rows that exist in the current table.
 Rows[row_index]: Gets the single row at the specified index.
 Columns.Count: Gets the no. of columns that exist in the current table.
 Columns[column_index]: Gets the single column at the specified index.

Understanding the “DataRow” class:


 [column_index]: This indexer gets the value at the given column, based on the given
index.
 [“column_name”]: This indexer gets the value at the given column, based on the
given column.

Implementation Code for SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
 Construct the “DataAdapter” class object:
SqlDataAdapter adp = new SqlDataAdapter(―select statement‖,cn);
 Construct the “DataSet” class object:
DataSet ds = new DataSet();
 Construct the “DataTable” class object:
DataTable dt;
 Construct the “DataRow” class object:
DataRow drow;
 Execute the adapter and receive the data into DataSet:
adp.Fill(ds);

.NET 4.0 and Visual Studio 2010 Page 420 of 548


 Assign the particular table from “DataSet” into “DataTable” object:
dt = ds.Tables[table index];
 Get the total no. of rows in the table:
dt.Rows.Count;
 Get the total no. of columns in the table:
dt.Columns.Count;
 Assign the particular row from “DataTable” into “DataRow” object:
drow = dt.Rows[row index];
 Get the particular value in the “DataRow”:
 drow[column index];
(or)
drow[―column_name‖];

Implementation Code for Oracle (or any other database):


 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>‖;
 Construct the “DataAdapter” class object:
OleDbDataAdapter adp = new OleDbDataAdapter(―select statement‖,cn);
 Construct the “DataSet” class object:
DataSet ds = new DataSet();
 Construct the “DataTable” class object:
DataTable dt;
 Construct the “DataRow” class object:
DataRow drow;
 Execute the adapter and receive the data into DataSet:
adp.Fill(ds);
 Assign the particular table from “DataSet” into “DataTable” object:
dt = ds.Tables[table index];

.NET 4.0 and Visual Studio 2010 Page 421 of 548


 Get the total no. of rows in the table:
dt.Rows.Count;
 Get the total no. of columns in the table:
dt.Columns.Count;
 Assign the particular row from “DataTable” into “DataRow” object:
drow = dt.Rows[row index];
 Get the particular value in the “DataRow”:
 drow[column index];
(or)
drow[―column_name‖];

.NET 4.0 and Visual Studio 2010 Page 422 of 548


Demo:

 Open the previous demo application.


 Add the menu item ―View Data using Data Set‖ as shown below:

 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as ―DataSetDemo‖.
Click on ―Add‖.
 Double click on the ―View Data using Data Set‖ menu item and write the code:

Form1.cs

private void viewDataUsingDataSetToolStripMenuItem_Click(object sender, EventArgs e)


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

.NET 4.0 and Visual Studio 2010 Page 423 of 548


 Design the ―DataSetDemo‖ form as follows:

 Write the Code:

DataSetDemo.cs

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

private void DataSetDemo_Load(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);

.NET 4.0 and Visual Studio 2010 Page 424 of 548


//DataTable impl
DataTable dt;
dt = ds.Tables[0];

//presentation / buffer logic


for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow drow;
drow = dt.Rows[i];
listBox1.Items.Add(drow["customerid"] + " -- " + drow["customername"] + " -- "
+ drow["gender"] + " -- " + drow["amount"]);
}
}

 Sometimes, you may need to display the records one-by-one in flexible manner, depending on
the clicked buttons like ―First‖, ―Previous‖, ―Next‖, ―Last‖. We take a demonstration like that:

 Add the menu item ―View Data using Data Set – Flexible Records Presentation‖ as shown
below:

.NET 4.0 and Visual Studio 2010 Page 425 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as
―DataSetDemo_FlexibleRecords‖. Click on ―Add‖.
 Double click on the ―View Data using Data Set – Flexible Records Presentation‖ menu
item and write the code:

Form1.cs

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

 Design the ―DataSetDemo_FlexibleRecords‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 426 of 548


 Write the Code:

DataSetDemo_FlexibleRecords.cs

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

public partial class DataSetDemo_FlexibleRecords : Form


{
public DataSetDemo_FlexibleRecords()
{
InitializeComponent();
}

DataTable dt;
int RowIndex;
DataRow drow;

private void Display()


{
drow = dt.Rows[RowIndex];
textBox1.Text = Convert.ToString(drow[0]);
textBox2.Text = Convert.ToString(drow[1]);
if (Convert.ToString(drow[2]) == "Male")
radioButton1.Checked = true;
else
radioButton2.Checked = true;
textBox3.Text = Convert.ToString(drow[3]);
}

private void DataSetDemo_FlexibleRecords_Load(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);

//DataTable impl
dt = ds.Tables[0];

//display first record


RowIndex = 0;
Display();

.NET 4.0 and Visual Studio 2010 Page 427 of 548


}

private void button1_Click(object sender, EventArgs e)


{
//display first record
RowIndex = 0;
Display();
}

private void button2_Click(object sender, EventArgs e)


{
//display previous record
RowIndex--;
if (RowIndex < 0)
{
RowIndex++;
MessageBox.Show("Already at first record.");
}
Display();
}

private void button3_Click(object sender, EventArgs e)


{
//display previous record
RowIndex++;
if (RowIndex == dt.Rows.Count)
{
RowIndex--;
MessageBox.Show("Already at last record.");
}
Display();
}

private void button4_Click(object sender, EventArgs e)


{
//display last record
RowIndex = dt.Rows.Count - 1;
Display();
}
}

 Using with the DataSet buffer, it is possible to display the data in the ―DataGridView‖ control.
In other words, the dataset data can be assigned into ―DataGridView‖ control programmatically.

.NET 4.0 and Visual Studio 2010 Page 428 of 548


The ―DataGridView‖ control is one of the major famous controls, which displays the data in a
table format. It is easy to use it. To assign the data into this ―DataGridView‖ control, write the
following statement:
dataGridView1.DataSource = dataset_obj;
(or)
dataGridView1.DataSource = datatable_obj;

Sample Output:

We take a demonstration like that:

 Add the menu item ―View Data using Data Set - DataGridView‖ as shown below:

.NET 4.0 and Visual Studio 2010 Page 429 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as
―DataSetDemo_DataGridView‖. Click on ―Add‖.
 Double click on the ―View Data using Data Set - DataGridView‖ menu item and write the
code:

Form1.cs

private void viewDataUsingDataSetDataGridViewToolStripMenuItem_Click(object sender,


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

 Design the ―DataSetDemo_DataGridView‖ form as follows:

[Drag and drop the ―DataGridView‖ control from the toolbox].

.NET 4.0 and Visual Studio 2010 Page 430 of 548


 Write the Code:

DataSetDemo_DataGridView.cs

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

private void DataSetDemo_DataGridView_Load(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);

//DataTable impl
DataTable dt;
dt = ds.Tables[0];

//grid logic
dataGridView1.DataSource = dt;
}

.NET 4.0 and Visual Studio 2010 Page 431 of 548


Working with Stored Procedures / Functions
 This is to call a procedure / function from the frontend application.
 This includes with:
1. First, create the procedure / function at backend using PL SQL.
2. Call it with its name, from the frontend code.
 Note: PL SQL is supported by SQL Server, Oracle and My SQL.

Purpose / Advantages of Stored Procedures / Functions:


 To perform multiple database transactions (insert / delete / update / select) at-a-time,
with a single database call.
 To retrieve multiple tables data at-a-time, with a single database call.
 To implement complex database logics, which is a collection of multiple if conditions,
loops etc.
 To hide query / non-query statements in the code.
 To have a faster execution, because the stored procedure is basically a pre-compiled
object.

For example, in your project you want to perform 2 insertions, 3 deletions at various
tables. If you implement the code with previous concepts, you require large code and moreover
at run time 5 database calls will be sent. That means the execution flow goes to the backend,
executes one statement and comes back. For all of these, it takes much time. So the application
will be executed slower. If the application is running multiple client systems simultaneously, it will
be slower. It that time, this ―Stored Procedure Calling‖ concept is recommended. As an
advantage of this, those 5 transactions would be performed with a single database call.

.NET 4.0 and Visual Studio 2010 Page 432 of 548


Library:
 Connection: Maintains the connection with database.
 Command: Calls a database procedure / function.
 Parameter: Represents the argument value for the procedure / function.

Connection
Command
(provider, data (procedure / .NET
db Source, user id, function name,
parameters) Application
password)

Implementation Code for SQL Server:


 Import the Library (at the top):
using System.Data.SqlClient;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection();
 Assign the Connection string:
cn.ConnectionString = ―data source=<name of the server>;user id=<user
name>;password=<password>;initial catalog=<database name>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
SqlCommand cmd = new SqlCommand();
 Assign the reference of “Connection” class object to “Command” class object:
cmd.Connection = cn;
 Assign the procedure / function name that is to be executed:
cmd.CommandText = ―xxxxx‖;
 Assign the command type to “Command” class object:
cmd.CommandType = CommandType.StoredProcedure;

.NET 4.0 and Visual Studio 2010 Page 433 of 548


 Assign the parameters (if any) to the “Command” class object:
cmd.Parameters.AddWithValue(―parameter_name‖, value);
………………….;
………………….;
 Execute the procedure / function:
cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

Implementation Code for Oracle (or any other database):


 Import the Library (at the top):
using System.Data.OleDb;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection();
 Assign the Connection string:
cn.ConnectionString = ―provider=<provider name>;data source=<name of the
server>;user id=<user name>;password=<password>‖;
 Open the connection:
cn.Open();
 Construct the “Command” class object:
OleDbCommand cmd = new OleDbCommand();
 Assign the reference of “Connection” class object to “Command” class object:
cmd.Connection = cn;
 Assign the procedure / function name that is to be executed:
cmd.CommandText = ―xxxxx‖;
 Assign the command type to “Command” class object:
cmd.CommandType = CommandType.StoredProcedure;
 Assign the parameters (if any) to the “Command” class object:
cmd.Parameters.AddWithValue(―parameter_name‖, value);
………………….;
………………….;

.NET 4.0 and Visual Studio 2010 Page 434 of 548


 Execute the procedure / function:
cmd.ExecuteNonQuery();
 Close the connection:
cn.Close();

Demo:

 Open SQL Server 2005.


 Already you have created ―demo‖ database. Confirm, whether it is exist or not.
 In that database, create a table named ―Students‖, as shown below.

 Click on ―New Query‖ option in the toolbar.

.NET 4.0 and Visual Studio 2010 Page 435 of 548


 Then type the following code:

 Then Press ―F5‖.


 It displays the following message:
Command(s) completed successfully.
 Enter some sample data as follows:

.NET 4.0 and Visual Studio 2010 Page 436 of 548


 Open the previous demo application in Visual Studio.
 Add the menu item ―Stored Procedure Demo‖ as shown below:

.NET 4.0 and Visual Studio 2010 Page 437 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as
―StoredProcedureDemo‖. Click on ―Add‖.
 Double click on the ―Stored Procedure Demo‖ menu item and write the code:

Form1.cs

private void storedProcedureDemoToolStripMenuItem_Click(object sender, EventArgs e)


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

 Design the ―StoredProcedureDemo‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 438 of 548


 Write the Code:

StoredProcedureDemo.cs

using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();

//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "calculategrades";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
//presentation logic
MessageBox.Show("Procedure Executed..");
cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 439 of 548


Demo on Retrieving Multiple Tables Data using Stored
Procedure:

 Open SQL Server 2005.


 Click on ―New Query‖ option in the toolbar.
 In the ―demo‖ database, create the stored procedure as follows.

 Then Press ―F5‖.


 It displays the following message:
Command(s) completed successfully.

 Open the previous demo application in Visual Studio.


 Add the menu item ―Stored Procedure Demo – Multiple Tables‖ as shown below:

.NET 4.0 and Visual Studio 2010 Page 440 of 548


 Click on ―Project‖ menu – ―Add Windows Form‖. Enter the form name as
―StoredProcedureDemo_MultipleTables‖. Click on ―Add‖.
 Double click on the ―Stored Procedure Demo – Multiple Tables‖ menu item and write the
code:

Form1.cs

private void storedProcedureDemoMultipleTablesToolStripMenuItem_Click(object


sender, EventArgs e)
{
StoredProcedureDemo_MultipleTables f = new
StoredProcedureDemo_MultipleTables();
f.MdiParent = this;
f.Show();
}

 Design the ―StoredProcedureDemo_MultipleTables‖ form as follows:

.NET 4.0 and Visual Studio 2010 Page 441 of 548


[Drag and drop two ―DataGridView‖ controls into the form]

 Write the Code:

StoredProcedureDemo_MultipleTables.cs

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

private void StoredProcedureDemo_MultipleTables_Load(object sender, EventArgs e)


{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";

//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("getdata", cn);

//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);

.NET 4.0 and Visual Studio 2010 Page 442 of 548


//DataTable impl
DataTable dt1, dt2;
dt1 = ds.Tables[0];
dt2 = ds.Tables[1];

//grid logic
dataGridView1.DataSource = dt1;
dataGridView2.DataSource = dt2;
}

.NET 4.0 and Visual Studio 2010 Page 443 of 548


StoringtheConnectionStringin“App.config”file

 In the live projects development, we may require to offer one or more customizable
values in the code.
 For example, you can take a db server name. At the development time, we use the db
server in the s/w company. But when the project is issued to the customer, the project
should work under the db server, which is in the customer‘s company.
 At that, there should a facility to customize the server name, after installing the project in
the customer‘s company.
 But, we don‘t give the source code to the customer, so that the customer can‘t change
the db server name.
 To solve this problem, this kind of application settings like this, would be maintained in
another file separately, which can be modified on the client system, even after installing
the project in the customer‘s work station.
 In .NET Framework, the application settings can be saved in a config file.
 A config file contains “.config” extension.
 In Console and Windows Applications, it is called as ―App.Config‖.
 In Web Sites, it is called as ―Web.Config‖.
 The config file is written is “xml language”.

Implementation of “Config File”


 Add the configuration file.
 Click on ―Project‖ menu – ―Add New Item‖.
 Select ―Application Configuration File‖.
 Click on OK.
 Then ―App.config‖ file will be created.
 In the <config> tag, add the <appSettings> tag as follows.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>

</appSettings>
</configuration>

 In the ―<appSettings>‖ tag, use ―<add>‖ tag to declare the actual application
configuration setting values.

.NET 4.0 and Visual Studio 2010 Page 444 of 548


Syn: <add key=”name of the key” value=”actual value”>
Ex: <add key=‖servername‖ value=‖myserver‖>

Note: The ―key‖ is used to access the configuration setting value in the code.

 Access the configuration setting value with the help of ―key‖.


System.Configuration.ConfigurationSettings.AppSettings["key"];
It returns the value of the configuration setting, based on the given key in string mode.

Application 138: Demo on “App.Config”

App.Config

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


<configuration>
<appSettings>
<add key="SqlServerConnection" value="user id=sa;password=123;data
source=localhost;initial catalog=demo"/>
</appSettings>
</configuration>

.NET 4.0 and Visual Studio 2010 Page 445 of 548


Form1.cs

using System.Configuration;
using System.Data.SqlClient;

private void button1_Click(object sender, EventArgs e)


{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = ConfigurationSettings.AppSettings["SqlServerConnection"];
cn.Open();
MessageBox.Show("Successfully Connected.");
cn.Close();
}

.NET 4.0 and Visual Studio 2010 Page 446 of 548


Crystal Reports
 ―Crystal Reports‖ is known as a reporting tool.
 This is used for development of database reports in the projects.
 A database report displays the database data, in a summary manner.
 A database report is ready to print. The report file extension is ―.rpt‖.
 That can be exported to ―Excel‖ / ―HTML‖ etc., formats.
 Generally, in every live project, the data entered by the data entry operators, should be
displayed to the administrator in a ―Report‖ format. That can be calledas a ―Database
Report‖.
 ―Crystal Reports‖ are developed by ―Seagate Corporation‖, and has a strong integration
with Visual Studio.
 Note: In Visual Studio 2010, the crystal reports are not available by default; we need to
install it separately. In the older versions (Visual Studio 2005 and 2008), Crystal reports
are in-built.

Application 149: Demo on Crystal Reports

Implementation of Crystal Reports

1. Create a Crystal Report.

 Click on ―Project‖ menu – ―Add New


Item‖.
 Select ―Reporting‖ – ―Crystal Report‖.
 Enter the name of the new report. Ex:
StudentsReport.rpt.
 Click on ―Add‖.
 A wizard will be displayed.
 Select the report type as ―Standard‖ and
click on OK.
 The ―Standard Report Creation Wizard‖
dialog box will be appeared.

.NET 4.0 and Visual Studio 2010 Page 447 of 548


 There, expand the option ―Create New Connection‖ and expand ―OLE DB (ADO)‖
 Then ―OLE DB (ADO)‖ dialog box will be appeared.
 There, select the appropriate driver / provider name, based on the database which
you want to connect.
 Sql Server  Microsoft OLE DB Provider for Sql Server
 Oracle  Microsoft OLE DB Provider for Oracle
 MS Access  Microsoft Jet OLE DB 4.0 Provider

 After selecting the provider (Ex: Microsoft OLE DB Provider for Sql Server), click on
―Next‖ button.
 Enter the server name (name of the system), user id, password and select database
name.
(Ex: classroom, sa, 123 and sample)

.NET 4.0 and Visual Studio 2010 Page 448 of 548


 Click on ―Finish‖.
 Then the ―OLE
DB (ADO)‖ dialog
box will be closed
and the focus will
be come back to
―Standard Report
Creation Wizard‖
dialog box. And
now, the ―OLE
DB (ADO)‖ option
will be expanded.
 Expand the
database name
and select the
table name,
which you want.

.NET 4.0 and Visual Studio 2010 Page 449 of 548


(Ex: students).
 Click on ―>‖ button to add the selected table into the right side list.
 Click on ―Next‖.
 Expand the table name. Then the list of columns will be displayed.
 Now you have to add the require column(s), into the right side list, which you want to
display in the crystal report.
 To add all the columns, click on ―>>‖ button. To add the columns one-by-one, select
the column first and click on ―>‖ button.
 Click on ―Next‖.
 Select the grouping column, based on which you want to group-up the data
(optional). If you don‘t want to group the data, simply leave it blank.
 Click on ―Finish‖.
 Then the report wizard will be completed and the report will be generated
automatically.
 The report will be displayed in the design view. This can be called as ―Report Design
View‖.
 Then the report file will be added into the ―Solution Explorer‖. Ex: studentsreport.rpt

2. Design the Crystal Report.


 The ―Report Design View‖ offers to change the design of the report.
 The report design view contains 5 sections like:
 Report Header: This section contains the objects that are to be displayed
only at the top of the report.
 Page Header: This section contains the objects that are to be displayed at
the top of each page.
 Details: This section contains the objects that are to be repeated for each
row of the database table. Generally, it displays the actual data values.
 Report Footer: This section contains the objects that are to be displayed at
the bottom of the report.
 Page Footer: This section contains the objects that are to be displayed at
the bottom of each page.

.NET 4.0 and Visual Studio 2010 Page 450 of 548


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

.NET 4.0 and Visual Studio 2010 Page 451 of 548


 To change any font / border / alignment / colors / paragraph of the objects, right click
on the require object and choose the ―Format Object‖ option.

 To add new objects, right click on the empty area and choose ―Insert‖, where you can
select ―Special Field‖ / ―Text Object‖ / ―Summary‖ / ―Line‖ / ―Box‖ / ―Chart‖ /
―Picture‖. After selecting any one of these options, click anywhere, where you want to
insert that object.

3. Invoke it in the Form.


 The crystal report file can‘t be executed individually, it requires a form.
 In other words, the crystal report can be executed on a windows form.
 To contain the crystal report in the form, a control is required, that is called as
―CrystalReportViewer‖.
 This contains is able to display a crystal report on the form.
 To implement this, come back to the form and drag ―CrystalReportViewer‖ control
under ―Report‖ category from the toolbox into the form.
 For the control, set the following property.
 ReportSource: Name of the report. (Ex: StudentReport)
 Run the application. At run time, it asks for run-time authentication for security
purpose. Then you have to enter the password (Ex: 123) and click on ―Finish‖.
 The ―CrystalReportViewer‖ control offers the following features at run time.
 Exporting the report to other formats like excel, pdf, doc etc.
 Printing the report through a printer.
 Refresh the report data.
 Show/Hide the Group Tree.
 Navigating the First / Previous / Next / Last Pages in the report.
 Find the required text.
 Change the Zoom of the data.

.NET 4.0 and Visual Studio 2010 Page 452 of 548


Output:

.NET 4.0 and Visual Studio 2010 Page 453 of 548


The Application Logic

 While you are developing some applications you write some application logic (some
code).
 That application logic can be divided as 3 types.
1. Presentation Logic
2. Business Logic
3. Database Logic

1. Presentation Logic:
 This includes with reading the input values from the controls, updating the
UI by changing the properties, displaying some output messages etc.
 For example, you take ―login‖ form.

 In that login form, after clicking on OK button, getting the user name and
password from the textboxes is called as ―Presentation Logic‖. In the similar
way, displaying the result message also called as ―Presentation Logic‖ in this
example.

2. Business Logic:
 This includes with validating the input values, performing some calculations,
implementing some formulas or algorithms etc.
 In this login example, checking the username and password whether those
are entered properly or not is called as ―Business Logic‖.

.NET 4.0 and Visual Studio 2010 Page 454 of 548


3. Database Logic:
 This includes with getting some data from the database or insert / modifying
some data in the database.
 In this login example, getting the users data from the database is called as
―Database Logic‖.

The Application Development Architectures

Based on the way, that you are implementing the presentation logic, business logic and
database logic in your application, there are 4 development architectures.
1) One-Tier Architecture / Monolithic Architecture
2) Two-Tier Architecture
3) Three-Tier Architecture
4) Multi-Tier Architecture / Distributed Architecture

1) One-Tier Architecture:
 All types of logics (presentation logic, business logic and database logic) will be
implemented directly within the form.
 That means there is no separation of presentation logic, business logic and database
logic.
 This type of applications are not in the professional style.
 There is no re-usability of business code and database code.

UI

Presentation Logic
Business Logic
Database Logic

.NET 4.0 and Visual Studio 2010 Page 455 of 548


2) Two-Tier Architecture:
 The Presentation Logic and Business Logics are maintained separately.
 The presentation logic is written in ―Presentation Layer‖ and the business logic is
written in ―Business Layer‖ / ―Business Access Layer‖.

UI

Business Access
Presentation Layer
Layer

 Note: Here, the database logic also can be written in the ―Business Layer‖ only,
even though it‘s not a good manner.

3) Three-Tier Architecture:
 The Presentation Logic, Business Logic and Database Logics are maintained
separately.
 This is recommended for the professional projects in the software companies.

UI

Data
Business Access Access
Presentation Layer
Layer Layer

db

.NET 4.0 and Visual Studio 2010 Page 456 of 548


4) N-Tier Architecture / Distributed Architecture:
 In the 3-tier architecture, the ―UI and presentation layer‖ will be located in the client
system; and ―business access layer and data access layer‖ will be maintained in the
server system.

Client System Server System

UI

Data
Business Access Access
Presentation Layer
Layer Layer

db

 Here, there is the requirement of a technology that allows us to connect ―Business


Layer‖ with ―Presentation Layer‖. That technology is called as ―Distributed
Technology‖.
 The following are the well-known and important distributed technologies:
 DCOM (Distributed Component Object Model)
 .NET Remoting
 Web Services
 WCF (Windows Communication Foundation)

A. DCOM:
 It is in usage, before .NET.
 It is platform dependent.

.NET 4.0 and Visual Studio 2010 Page 457 of 548


B. .NET Remoting:
 It is introduced in .NET Framework.
 It is platform independent.
 It is suitable for the windows applications that run on LAN or intranet.
 It supports TCP and HTTP protocols.

C. Web Services:
 It is available in ASP.NET.
 It is also platform independent.
 It is supported for web only.
 It is language independent (any .NET language).
 It is supported for ASP.NET web sites only.
 It supports SOAP and HTTP protocols.

D. WCF:
 It is introduced in .NET 3.5.
 It is platform independent.
 It is language independent (any .NET language).
 It is supported for other language applications also (java applications, php
applications etc.)
 It is supported for any type of network (LAN, intranet and internet also).
 It is supported in any type of applications (windows applications, web sites, WPF
applications etc.)

Application 150: Demo on 3-Tier Architecture

 Create a new windows forms application.


Name: 3TierArchitectureDemo
 It will create ―Form1‖ automatically.
 Open solution explorer, right click on ―Form1‖ and rename it as ―LoginForm.cs‖.
 Right click on the solution, select ―Add‖ – ―New Project‖.

.NET 4.0 and Visual Studio 2010 Page 458 of 548


Project Type: Class Library
Name: BusinessAccessLayer
 Click on OK.
 Right click on the solution, select ―Add‖ – ―New Project‖.
Project Type: Class Library
Name: DataAccessLayer
 Click on OK.
 Right click on ―3TierArchitectureDemo‖ project and choose ―Add Reference‖.
 Select ―Project‖ – ―BusinessAccessLayer‖.
 Click on OK.
 Right click on ―BusinessAccessLayer‖ project and choose ―Add Reference‖.
 Select ―Project‖ – ―DataAccessLayer‖.
 Click on OK.
 Then the application framework is ready.

 Now, we need to create the database.


 Open Sql Server 2005.

.NET 4.0 and Visual Studio 2010 Page 459 of 548


 Right click on ―Databases‖ – ―New Database‖ – Enter the database name as
―RemotingTest‖ – Click OK.
 Expand ―RemotingTest‖ database – Right click on ―Tables‖ – Select ―New Table‖.
 Create the table as follows:

 Save the table name as ―Users‖.


 Expand ―RemotingTest‖ – ―Tables‖.
 Right click on the ―Users‖ table and choose ―Open Table‖.
 Enter some sample data.

.NET 4.0 and Visual Studio 2010 Page 460 of 548


 Come back to Visual Studio.
 Now, we have to configure the connection string in ―App.config‖ file.
 Right click on ―3TierArchitectureDemo‖ – ―Add New Item‖ – ―Application Configuration
File‖ – ―Add‖.
 Then ―App.config‖ file will be added. Then type the code as follows:

App.Config

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


<configuration>
<appSettings>
<add key ="RemoteDatabase" value="user id=sa;password=123;data
source=localhost;initial catalog=RemotingTest"/>
</appSettings>
</configuration>

 Now, we have to implement the code in ―DataAccessLayer‖.


 In the ―DataAccessLayer‖ project, right click on ―Class1.cs‖ and rename it as
―DatabaseLogic.cs‖.

.NET 4.0 and Visual Studio 2010 Page 461 of 548


 Then type the code in ―DatabaseLogic.cs‖.

DataAccessLayer  DatabaseLogic.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace DataAccessLayer
{
public class DatabaseLogic
{
public DataTable GetUsers(string Username, string Password)
{
//connection logic
string cnstr = ConfigurationSettings.AppSettings["RemoteDatabase"];
SqlConnection cn = new SqlConnection(cnstr);

//stmt logic
string sqlstr = "select * from users where username= ' " + Username + " ' and
password= ' " + Password + " ' ";

//adapter logic
SqlDataAdapter adp = new SqlDataAdapter(sqlstr, cn);
DataSet ds = new DataSet();
adp.Fill(ds);

//datatable logic
DataTable dt;
dt = ds.Tables[0];

return (dt);
}
}
}

 Now, we have to implement the code in ―BusinessAccessLayer‖.


 In the ―BusinessAccessLayer‖ project, right click on ―Class1.cs‖ and rename it as
―BusinessLogic.cs‖.
 Then type the code in ―BusinessLogic.cs‖.

.NET 4.0 and Visual Studio 2010 Page 462 of 548


BusinessAccessLayer  BusinessLogic.cs

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

namespace BusinessAccessLayer
{
public class BusinessLogic
{
public bool IsValidUser(string Username, string Password)
{
DataTable dt;
DataAccessLayer.DatabaseLogic dbl = new DataAccessLayer.DatabaseLogic();
dt = dbl.GetUsers(Username, Password);
if (dt.Rows.Count > 0)
return true;
else
return false;
}
}
}

 Open ―LoginForm.cs‖ and design it as follows.

 Write the code in ―LoginForm.cs‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 463 of 548


3TierArchitectureDemo  LoginForm.cs

private void button1_Click(object sender, EventArgs e)


{
BusinessAccessLayer.BusinessLogic bl = new BusinessAccessLayer.BusinessLogic();
bool result;
result = bl.IsValidUser(textBox1.Text, textBox2.Text);
if (result == true)
MessageBox.Show("Successfully Logged in!");
else
MessageBox.Show("Invalid Login");
}

private void button2_Click(object sender, EventArgs e)


{
Application.Exit();
}

 Finally run the application.

.NET 4.0 and Visual Studio 2010 Page 464 of 548


.NET Remoting
 It is introduced in .NET Framework.
 It is platform independent.
 It is suitable for the non-web applications (windows applications).
 It is supported in LAN or intranet.
 Def: A technology that makes an object accessible across application domains.
 In other words, it implement the communication between one .NET application and .NET
application.

.NET Application .NET Application


Network

Understanding .NET Remoting:


 To understand .NET Remoting completely, you should understand the following things:
1. .NET Remoting Architecture
2. Channels
3. Server Activated Object
4. Client Activated Object

i. .NET Remoting Architecture

Client Application Server Application

Channels (TCP/HTTP)
.NET Assembly
.NET Assembly Send a Request
Class

Channels (TCP/HTTP)
Proxy Object
(Client Activated Object) (Server Activated Object)
Send the Reference

.NET 4.0 and Visual Studio 2010 Page 465 of 548


 In the above architecture, there is the communication between one .NET
assembly (Client application) and another .NET assembly (Server application).
 At first the client application sends a request to the server application.
 The server application receives the request.
 In the server application, we have a class (for writing the business code). For an
object will be created for that class.
 That object is called as ―Server Activated Object‖.
 The reference of the ―Server Object‖ will be given to the client application.
 That reference is received and stored in a dummy object (The object, which acts
as reference of another object). That dummy object is called as ―Proxy‖.
 Finally, the client application can utilize the proxy, to access the methods of the
server object.
 In fact, the communication is possible using some communicators called as
―Channels‖.

ii. Channels
 It is the physical communication media used by the .NET Remoting System for
its communication between the client application and server application.
 For example, if you want to move some goods from one place to another place
physically. Then we require to transport those goods, through some roads.
 In the similar way, in Remoting also, we have to use some channels for
transportation of the object, across application domains (application boundaries).
 .NET Remoting Technology supports two channels.
1. TCP Channel (Transfer Control Protocol)
2. HTTP (Hyper Text Transfer Protocol)

Sl. No TCP Channel HTTP Channel


It is used for LAN / intranet It is used for LAN / intranet /
1
based application. internet applications.
It is mandatory to define a It can use the default port of the
2 port explicitly for using the web server and also it supports to
TCP channel. create the port explicitly.
Performance will be slower, when
3 Performance will be very fast.
compared with TCP channel.

.NET 4.0 and Visual Studio 2010 Page 466 of 548


 Note: In the client application and server application, we have to register any
one of the channels compulsory.

To register the channel:


ChannelServices.RegisterChannel(channel_object);

To unregister the channel:


ChannelServices.UnregisterChannel(channel_object);

iii. Server Activated Object


 The object, which is ready to be transmittable across the application domains,
using the channels.
 To expose it to the client application:

RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteClass), "alias_name",
WellKnownObjectMode.SingleCall / SingleTon);

 In the above syntax, ―RemoteClass‖ means, the class name for which you want
to create the remote object.
 On receiving the request from the client, an object will be created for the
RemoteClass and it will be served to the client application. Before serving it will
be converted in binary mode, because the binary format data only is supported
y the channels. The process of converting the object into binary format is called
as ―Marshalling‖.
 That remote class should be sub class of ―System.MarshalByRefObject‖
class; because the reference is to be passed to the client, instead of copying the
object into the client.
 Server Object Modes:
1. SingleCall: A new object will be created for every client request.
2. SingleTon: The object will be created for the first client request; and
the same object will be served for all other client requests.

.NET 4.0 and Visual Studio 2010 Page 467 of 548


iv. Client Activated Object
 The object reference, which acts as reference to the server object.
 It can also be called as ―Proxy‖.
 It is nothing but the variable, created for the remote interface.
 To get the reference of server object into a proxy:

IRemote irem;
irem = (IRemote)Activator.GetObject(typeof(IRemote), ―tcp://server:port/alias_name‖);

 In the above syntax, ―irem‖ is the proxy.


 Based on the given url, the server activated object reference will be received and
it will be assigned into ―irem‖.
 The ―irem‖ can call the methods of the server object.
 Note: The port no is a 4 digit number, which should be greater than 1024.
 We have to use a common port no in the client application and server
application.

.NET 4.0 and Visual Studio 2010 Page 468 of 548


.NET Remoting

Application 151: Demo on .NET Remoting

First, we have to create the database first.


 Open SQL Server 2005.
 Right click on ―Databases‖ – ―New Database‖ – Enter the database name as
―RemotingTest‖ – Click OK.
 Expand ―RemotingTest‖ database – Right click on ―Tables‖ – Select ―New Table‖.
 Create the table as follows:

 Save the table name as ―Users‖.


 Expand ―RemotingTest‖ – ―Tables‖.
 Right click on the ―Users‖ table and choose ―Open Table‖.
 Enter some sample data.

.NET 4.0 and Visual Studio 2010 Page 469 of 548


 Open Visual Studio 2010.
 Create a new Console Application.
Name: RemoteServer
Location: E:\C#Apps
 Open the solution explorer.
 Right click on the solution; click ―Add‖ – ―New Project‖.
 Select ―Visual C#‖ – ―Class Library‖.
Name: RemoteLibrary
 Click on OK.
 Right click on ―Class1.cs‖ and delete it. Click on OK for confirmation.
 Right click on ―RemoteLibrary‖ and choose ―Add‖ – ―New Item‖.
 Select ―Interface‖.
 Enter the name as ―IRemote‖.
 Click on Add.
 Type the code in ―IRemote.cs‖.

.NET 4.0 and Visual Studio 2010 Page 470 of 548


IRemote.cs:

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

namespace RemoteLibrary
{
public interface IRemote
{
bool CheckUserAvailability(string UserName);
}
}

 Right click on ―RemoteServer‖ and select ―Add Reference‖.


 Select ―Projects‖ – ―RemoteLibrary‖.
 Click on OK.
 Then the reference of RemoteLibrary will be added to the RemoteServer console
application.
 Now, we have to configure the connection string in ―App.config‖ file.
 Right click on ―3TierArchitectureDemo‖ – ―Add New Item‖ – ―Application Configuration
File‖ – ―Add‖.
 Then ―App.config‖ file will be added. Then type the code as follows:

App.config:

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


<configuration>
<appSettings>
<add key ="RemoteDatabase" value="user id=sa;password=123;data
source=localhost;initial catalog=RemotingTest"/>
</appSettings>
</configuration>

 Right click on ―RemoteServer‖ and select ―Add‖ – ―Class‖.


 Enter the class name as ―DatabaseLogic‖ and click on ―Add‖.
 Then type the code in ―DatabaseLogic.cs‖ file.

.NET 4.0 and Visual Studio 2010 Page 471 of 548


Datab
baseLogic.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace RemoteServer
{
class DatabaseLogic
{
public DataTable GetUsers(string Username)
{
//connection logic
string cnstr = ConfigurationSettings.AppSettings["RemoteDatabase"];
SqlConnection cn = new SqlConnection(cnstr);

//stmt logic
string sqlstr = "select * from users where username= ' " + Username + " ' ";

//adapter logic
SqlDataAdapter adp = new SqlDataAdapter(sqlstr, cn);
DataSet ds = new DataSet();
adp.Fill(ds);

//datatable logic
DataTable dt;
dt = ds.Tables[0];

return (dt);
}
}
}

 Right clck on ―RemoteServer‖ and select ―Add‖ – ―Class‖.


 Enter the cass name as ―RemoteClass‖ and click on ―Add‖.
 Then type the code in ―RemoteClass.cs‖ file.

.NET 4.0 and Visual Studio 2010 Page 472 of 548


RemoteClass.cs:

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

namespace RemoteServer
{
class RemoteClass: MarshalByRefObject, RemoteLibrary.IRemote
{
public bool CheckUserAvailability(string UserName)
{
DatabaseLogic dbl = new DatabaseLogic();
DataTable dt = dbl.GetUsers(UserName);
bool b;
if (dt.Rows.Count > 0)
{
//user data found.
b = false;
}
else
{
//user data not found.
b = true;
}
return (b);
}
}
}

 In the solution explorer, right click on ―RemoteServer‖ and choose ―Add Reference‖.
 Select ―.NET‖ – ―System.Runtime.Remoting‖.
 Click on OK.
 Open the ―Program.cs‖ from Solution Explorer.
 Type the following code in ―Program.cs‖.

.NET 4.0 and Visual Studio 2010 Page 473 of 548


Program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
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)
{
TcpServerChannel tsc = new TcpServerChannel(1234);
ChannelServices.RegisterChannel(tsc);
RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteClass),
"MyRemoteTest", WellKnownObjectMode.Singleton);
Console.WriteLine("Server started...\nPress Enter to stop!");
Console.Read();
ChannelServices.UnregisterChannel(tsc);
}
}
}

 Note: The port no should be same for server and client application.
 Run the application. Now, the server application is ready.
 Now, we need to continue with client application development.

Client Application Development:


 Create a new Windows Application Project.
Name: RemoteClient
 Go to ―Project‖ menu – ―Add Reference‖. Select ―.NET‖ – ―System.Runtime.Remoting‖ –
Click on OK.
 Again go to ―Project‖ menu – ―Add Reference‖. Select ―Browse‖ – Then select the
―E:\C#Apps\RemoteServer\RemoteLibrary\bin\Debug\RemoLibrary.dll‖ file – Click on OK.
 Design the form as shown:

.NET 4.0 and Visual Studio 2010 Page 474 of 548


 Write the code in the form:

Form1.cs:

using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteLibrary;

private void button1_Click(object sender, EventArgs e)


{
TcpClientChannel tcc = new TcpClientChannel();
ChannelServices.RegisterChannel(tcc);
string url = "tcp://localhost:1234/MyRemoteTest";
IRemote irem;
irem = (IRemote)Activator.GetObject(typeof(IRemote), url);
bool result = irem.CheckUserAvailability(textBox1.Text);
if (result == true)
{
label3.Visible = true;
label3.Text = "Available!";
label3.ForeColor = Color.Green;
}
else
{
label3.Visible = true;

.NET 4.0 and Visual Studio 2010 Page 475 of 548


label3.Text = "Not Available!";
label3.ForeColor = Color.Red;
}
ChannelServices.UnregisterChannel(tcc);
}

 Then finally run the server application first. While it is running, then run the client
application.
 Note: Without running the server application, client application will not work.

.NET 4.0 and Visual Studio 2010 Page 476 of 548


Network Programming using Sockets

 It includes with sending / receiving messages from server-to-client or client-to-sever on a


network, using ―Sockets‖ technology.
 The Socket Programming uses ―TCP‖ protocol.
 This is meant for ―Chatting Applications‖.

Library:
1) System.Net.Sockets
2) Some classes from ―System.IO‖

Implementation of Network Programming

i) Sending Messages to a System:


A chatting application includes with sending / receiving messages on the network. This
topic includes with sending a message to the specified host on the network. The host can
be recognized with the ―host name‖ or ―IP address‖. The default IP address for
standalone systems is, ―127.0.0.1‖. This requires to use a port no also. The port no is a 4
digit number, which should be greater than 1024.

Library: 1) System.Net.Sockets.TcpClient
This class object represents a client system on the network.
2) System.Net.Sockets.NetworkStream
This class object represents a stream on the network, which is able to
send the messages.

Implementation:
 Import the API:
using System.Net.Sockets;
 Construct ―TcpClient‖ class object:
TcpClient tc = new TcpClient(―host name‖, port no);

.NET 4.0 and Visual Studio 2010 Page 477 of 548


Note: Here you have to give target system (receiver system)
name. That means, the ―tc‖ object represents the receiver
system here.
 Get the network stream from ―TcpClient‖ class object:
NetworkStream ns = tc.GetStream();
 Write a byte on the network stream (send the byte to the target host):
ns.WriteByte(byte value);
 Close the network stream:
ns.Close();
 Close the tcp client:
tc.Close();

ii) Receiving Messages from a System:


This topic includes with receiving a message, sent for a specified host.

Library: 1) System.Net.Sockets.TcpListener
This class object is used to listen the message that is sent to the host.
2) System.Net.Sockets.TcpClient
This class object represents a client system on the network.
3) System.Net.Sockets.NetworkStream
This class object represents a stream on the network, which is able to
receive the messages.
4) System.IO.StreamReader
This class object represents a stream, which is able to receive the
messages.

Implementation:
 Import the API:
using System.Net.Sockets;
using System.IO;
 Construct ―TcpListener‖ class object:
TcpListener tl = new TcpListener(ip address, port no);

.NET 4.0 and Visual Studio 2010 Page 478 of 548


Note: Here, you have to give the self system IP address
(receiver system IP address); and the same port no,
which you are using in the server application.

 Start the listener:


tl.Start();
 Accept the connected client and construct ―TcpClient‖ class object:
TcpClient tc = tl.AcceptTcpClient();
Note: The above method will be executed after sending the
message from the sender system. Then the
―AcceptTcpClient‖ method returns the reference of the
sender system. That reference will be assigned into
―TcpClient‖ class object. That means, the ―tc‖ object
represents the sender system.

 Get the network stream from ―TcpClient‖ class object:


NetworkStream ns = tc.GetStream();
 Construct the ―StreamReader‖ class object:
StreamReader sr = new StreamReader(ns);
Note: Here, you are using ―StreamReader‖; because
―NetworkStream‖ class doesn‘t support ―ReadToEnd()‖
method. So that if you are using ―NetworkStream‖, you
have to read the message byte-by-byte.
 Write a byte on the network stream (send the byte to the target host):
string message = sr.ReadToEnd();
 Close the network stream:
ns.Close();
 Close the tcp client:
tc.Close();
 Stop the listener:
tl.Stop();

.NET 4.0 and Visual Studio 2010 Page 479 of 548


Application 152: Demo on Message Passing between Client and Server using Sockets

Message Sender Application:

using System.Net.Sockets;

private void btnSend_Click(object sender, EventArgs e)


{
string host = txtHost.Text;
string message = txtMessage.Text;
TcpClient tc = new TcpClient(host, 2025);
NetworkStream ns = tc.GetStream();
byte[] bytesarray = Encoding.ASCII.GetBytes(message);
foreach (byte b in bytesarray)
ns.WriteByte(b);
ns.Close();
tc.Close();
}

Note: In this code, the ―ASCII.GetBytes()‖ method converts the given string value as an array of
bytes. This is required because, using WriteByte() method, you can pass the byte values
only.

.NET 4.0 and Visual Studio 2010 Page 480 of 548


Message Receiver Application:

using System.Net.Sockets;
using System.IO;
using System.Net;

private void btnStartListener_Click(object sender, EventArgs e)


{
TcpListener tl = new TcpListener(IPAddress.Parse("127.0.0.1"), 2025);
tl.Start();
TcpClient tc = tl.AcceptTcpClient();
NetworkStream ns = tc.GetStream();
StreamReader sr = new StreamReader(ns);
string receivedmessage = sr.ReadToEnd();
txtMessage.Text = receivedmessage;
ns.Close();
tc.Close();
tl.Stop();
}

.NET 4.0 and Visual Studio 2010 Page 481 of 548


Execution Steps:
1) First, run the ―Receiver‖ application.
2) Click on ―Start Listener‖ button.
3) Then run the ―Sender‖ application.
4) Enter the host name as ―localhost‖ / any system name on the network / IP address of
any system on the network / or the default IP address ―127.0.0.1‖
5) Enter any message in the textbox.
6) Click on ―Send‖ button.
7) Then the message will be appeared in the receiver application.

Note: ** Try to implement chatting application, with two-way interaction **

.NET 4.0 and Visual Studio 2010 Page 482 of 548


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

Windows Services
 A windows service like a background-processed application.
 It will be installed on the ―Services‖, and will be registered on the windows registry.
 To open the list of currently installed services on your system, click on ―Start‖ – ―Control
Panel‖ – ―Administrative Tools‖ – ―Services‖.
 Ex: Windows Time, Windows Audio, Plug and Play, Chatting services, anti-virus services,
database services etc.

Features of Windows Services

 The windows service is configured to run on windows o/s only.


 Most of the windows services will be started automatically, at system logon and will be
shut-down at system logoff.
 Some other windows services can be configured to be started manually. To start / stop
the services, open ―Services‖ window as shown above. Then right click on the required
service and choose ―Start‖ / ―Stop‖ option.
 The windows services are best compatible with ―Threading‖; so that you are
recommended to write your code in ―threading‖.
 The windows service can‘t contain any windows forms.
 It is able to show a tray icon on the system tray (at windows taskbar).
 It can‘t be run directly on your Visual Studio.
 It is able to interact with ―Event Log‖ service on the Windows operating system.
 After the development of your application code in the windows service, you need a utility
software, called ―installutil.exe‖, which is used to install your windows service on the
system.
 Before installing the service, it requires ―ProjectInstaller‖ class, which provides additional
information, i.e. required for installing your service with ―installutil.exe‖.

.NET 4.0 and Visual Studio 2010 Page 483 of 548


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

Development of Windows Services

 For a better demonstration, we start with a demo application on this.

Application 153: A Simple Demo on Windows Services

Stage 1: Creating a Windows Service

 Open Visual Studio 2008.


 Click on ―File‖ – ―New‖ – ―Project‖.
 Select ―Windows‖ – ―Windows Service‖.
Name: MyWindowsService
Location: D:\
 Click on OK.
 Then windows service project will be created with the specified name and specified
location.
 Then screen will be displayed like this:
 You can‘t design anything, but you can add a ―notify icon‖, and that will be displayed in
the system tray, while the service is running.
 To do this, open ―ToolBox‖ and drag and drop the ―NotifyIcon‖ control into the gray
colored area.
 Set the following properties for ―NotifyIcon‖ control.
 Icon: any icon file. (Ex: system.ico)
 Text: any text (Ex: My Windows Service)

.NET 4.0 and Visual Studio 2010 Page 484 of 548


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

 But especially when you set th ―Icon‖ property, you can‘t compile your project
successfully, because it requires the ―System.Drawing‖ assembly reference. But the
problem is, by default the ―System.Drawing‖ assembly will not be added to the windows
services.
 So that, simply you have to add the reference of ―System.Drawing‖ assembly, by clicking
on ―Project‖ menu – ―Add Reference‖ – ―System.Drawing‖ – and clicking on OK.
 Enter into the code window by pressing ―F7‖ (or) by right clicking and selecting ―View
Code‖ option.
 Write the following code, which writes an event log message at every 3 seconds.

using System.Threading;

namespace MyWindowsService
{
public partial class Service1 : ServiceBase
{
public Service1()
{

.NET 4.0 and Visual Studio 2010 Page 485 of 548


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

InitializeComponent();
}

Thread th1;

protected override void OnStart(string[] args)


{
th1 = new Thread(WriteMessage);
th1.Start();
}

protected override void OnStop()


{
th1.Abort();
}

private void WriteMessage()


{
while (true)
{
string msg = "This message is generated using Windows Service!! Now, the
time is " + DateTime.Now.ToString();
System.Diagnostics.EventLog.WriteEntry("My Windows Service", msg);
Thread.Sleep(3000);
}
}
}
}

 Note: The event handlers for ―OnStart‖ and ―OnStop‖ events will be created
automatically. The ―OnStart‖ event will be executed on starting the windows service; and
the ―OnStop‖ event will be executed on stopping the windows
service.
 Set the following properties for ―Service1‖:
 ServiceName: My Windows Service
 Up to this, windows service coding is over.
 Then you need to add ―Installer‖ for your windows service.
 To do this, simply come back to the Design view and right click and then choose ―Add
Installer‖ option.
 Then you will have ―ProjectInstaller‖ class in your project, along with two components
called ―serviceProcessInstaller1‖ and
―serviceInstaller1‖.
 Set the following properties for

.NET 4.0 and Visual Studio 2010 Page 486 of 548


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

―serviceProcessInstaller1‖:
 Account: LocalSystem
 Set the following properties for ―serviceInstaller1‖:
 ServiceName: My Windows Service
 Description: This is for demo purpose.
 StartType: Automatic
 Finally, ―Build‖ the project. Then the ―MyWindowsService.exe‖ file will be created in the
―bin\Debug‖ folder.

Stage 2: Installing the Windows Service

 To install your windows service, you require to use ―installutil.exe‖ utility software, which
will be loaded into your system along with Visual Studio.
 To do this, simply open ―Visual Studio Command Prompt‖ by clicking on ―Start‖ –
―Programs‖ – ―Microsoft Visual Studio 2010‖ – ―Visual Studio Tools‖ – ―Visual Studio
Command Prompt (2010)‖.
 Then enter the following command.

installutil D:\MyWindowsService\MyWindowsService\bin\Debug\MyWindowsService.exe

 On successful installation of your service, you will have the following messages at last:
The Commit phase completed successfully.
The transacted install has completed.
 To confirm the service installation, open the ―Services‖ window, by clicking on ―Start‖ –
―Control Panel‖ – ―Administrative Tools‖ – ―Services‖.

.NET 4.0 and Visual Studio 2010 Page 487 of 548


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

 You can see the service name called ―My Windows Service‖. It will be started
automatically, at system startup, because you already set the ―Startup Type‖ as
―Automatic‖.
 To enable your service to be interacted with the desktop and create visual actions on
your system (Ex: displaying tray icons, displaying windows etc.), right click n the service
and choose ―Properties‖. Then click on ―Log on‖ tab. There, select ―Allow service to
interact with desktop‖ option; and finally click on OK.

Stage 3: Starting the Windows Service

 To start the windows service now, simply right click on the service in the ―Services‖
window, and choose ―Start‖ option.
 Then the service will be started and it will be executed.
Output: (Control Panel – Administrative Tools – Event Viewer)

Stage 4: Stopping the Windows Service

 To stop the windows service now, simply right click on the service in the ―Services‖
window, and choose ―Stop‖ option.
 Then the service will be stopped.

.NET 4.0 and Visual Studio 2010 Page 488 of 548


Stage 5: Un-installing the Windows Service

 To un-install your windows service, simply open ―Visual Studio Command Prompt‖ again,
by clicking on ―Start‖ – ―Programs‖ – ―Microsoft Visual Studio 2010‖ – ―Visual Studio
Tools‖ – ―Visual Studio Command Prompt (2010)‖.
 Then enter the following command.

installutil/u D:\MyWindowsService\MyWindowsService\bin\Debug\MyWindowsService.exe

 On successful installation of your service, you will have the following messages at last:

Service My Windows Service was successfully removed from the system.


The uninstall has completed.

.NET 4.0 and Visual Studio 2010 Page490 of 548


Application 154: Chat Service Application

Stage 1: Creating the Windows Service

 Create the windows service.


o Name: ChatService
o Location: D:\
 Drag and drop the ―NotifyIcon‖ control and set the following properties:
 Icon: satellite.ico
 Text: Chat Service
 Add the reference of ―System.Drawing‖ to the project.
 Write the following code in the code window.

using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ChatService
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}

Thread th1;

protected override void OnStart(string[] args)


{
th1 = new Thread(StartListener);
th1.Start();
}

protected override void OnStop()


{
th1.Abort();
}

private void StartListener()


{

.NET 4.0 and Visual Studio 2010 Page491 of 548


while (true)
{
//start listener
TcpListener tl = new TcpListener(IPAddress.Parse("127.0.0.1"), 2025);
tl.Start();
TcpClient tc = tl.AcceptTcpClient();
//get the message
NetworkStream ns = tc.GetStream();
StreamReader sr = new StreamReader(ns);
string receivedmessage = sr.ReadToEnd();
//stop listener
ns.Close();
tc.Close();
tl.Stop();
//write the message to a file
string filename = "d:\\message.txt";
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
fobj.Delete();
StreamWriter sw = new StreamWriter(filename);
sw.WriteLine(receivedmessage);
sw.Close();
//open message receiver application
System.Diagnostics.Process.Start("D:\\MessageReceiver\\MessageReceiver\\bin\\Debug\\M
essageReceiver.exe");
}
}
}
}

 Set the following properties for ―Service1‖:


 Serviceame: Chat Service
 Right click and then choose ―Add Installer‖ option.
 Then you will have ―ProjectInstaller‖ class in your project, along with two components
called ―serviceProcessInstaller1‖ and ―serviceInstaller1‖.
 Set the following properties for ―serviceProcessInstaller1‖:
 Account: LocalSystem
 Set the following properties for ―serviceInstaller1‖:
 ServiceName: Chat Service
 Description: This is for chatting.
 StartType: Automatic
 Finally, ―Build‖ the project. Then the ―ChatService.exe‖ file will be created in the
―bin\Debug‖ folder.

.NET 4.0 and Visual Studio 2010 Page492 of 548


Creating Windows Forms Application
Now, you need to create a windows application, which is associated with this application.
Name: MessageReceiver
Location: D:\

using System.IO;

private void Form1_Load(object sender, EventArgs e)


{
string filename = "d:\\message.txt";
FileInfo fobj = new FileInfo(filename);
if (fobj.Exists)
{
StreamReader sr = new StreamReader(filename);
string msg = sr.ReadToEnd();
sr.Close();
txtMessage.Text = msg;
}
}

Stage 2: Installing the Windows Service

 Open ―Visual Studio Command Prompt‖ by clicking on ―Start‖ – ―Programs‖ – ―Microsoft


Visual Studio 2010‖ – ―Visual Studio Tools‖ – ―Visual Studio Command Prompt (2010)‖.
 Then enter the following command.

installutil D:\ChatService\ChatService\bin\Debug\ChatService.exe

.NET 4.0 and Visual Studio 2010 Page493 of 548


 To confirm the service installation, open the ―Services‖ window, by clicking on ―Start‖ –
―Control Panel‖ – ―Administrative Tools‖ – ―Services‖.
 You can see the service name called ―Chat Service‖. It will be started automatically, at
system startup, because you already set the ―Startup Type‖ as ―Automatic‖.
 Right click on the service and choose ―Properties‖. Then click on ―Log on‖ tab. There,
select ―Allow service to interact with desktop‖ option; and finally click on OK.

Stage 3: Starting the Windows Service

 To start the windows service now, simply right click on the service in the ―Services‖
window, and choose ―Start‖ option.
 Then the service will be started and it will be executed.
Running the Application:
 Open the ―TcpSender‖ application (you have already developed it in the previous
chapter).
 Enter the host name and message and click on ―Send‖ button.
 Then the given message will be appeared in the ―MessageReceier‖ application
automatically.

Stage 4: Stopping the Windows Service

 To stop the windows service now, simply right click on the service in the ―Services‖
window, and choose ―Stop‖ option.
 Then the service will be stopped.

.NET 4.0 and Visual Studio 2010 Page494 of 548


Stage 5: Un-installing the Windows Service

 To un-install your windows service, simply open ―Visual Studio Command Prompt‖ again,
by clicking on ―Start‖ – ―Programs‖ – ―Microsoft Visual Studio 2010‖ – ―Visual Studio
Tools‖ – ―Visual Studio Command Prompt (2010)‖. Then enter the following command.

installutil/u D:\ChatService\ChatService\bin\Debug\ChatService.exe

.NET 4.0 and Visual Studio 2010 Page495 of 548


Package and Deployment
 After development of your application, finally you have to generate the ―Setup‖ program, and
it can be given to the client.
 The user (client) has to install the project, simply by double clicking on the ―Setup.exe‖ file.
 On installing the project in the client system, the following changes will be made in that
system:
 Then the necessary files (such as exe files, dll files, images, configuration files) will be
copied in the ―c:\Program Files‖ folder in that client system.
 The necessary shortcuts to run the application will be created at the user‘s desktop and
programs menu.

Application 155: Demo on Package and Deployment

Development of “Setup Project”:


 Create a new Windows Forms Application.
Name: DeploymentTest
 Design the form as follows.

.NET 4.0 and Visual Studio 2010 Page496 of 548


private void timer1_Tick(object sender, EventArgs e)
{
if (label1.Visible == true)
label1.Visible = false;
else
label1.Visible = true;
}

 Right click on the solution and choose ―Add‖ – ―New Project‖.


 Select ―Other Project Types‖ – ―Setup and Deployment‖ - ―Visual Studio Installer‖ -
―Setup Project‖.
 Enter the name of the project. Ex: Deployment Test 1.0

.NET 4.0 and Visual Studio 2010 Page497 of 548


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

.NET 4.0 and Visual Studio 2010 Page 498 of 548


 Then the following screen will be displayed.

 Right click on ―Application


Folder‖ option in the left side
panel and choose ―Add‖ –
―Project Output‖.
 Select the project name.
Ex: DeploymentTest.
 Select ―Primary output‖.
 Click on OK.
 Right click on ―Primary output
from DeploymentTest (Active)‖
and select ―Create shortcut to
Primary output from
DeploymentTest (Active)‖
option.

.NET 4.0 and Visual Studio 2010 Page 499 of 548


 Then the shortcut will be created in the same folder.
 Rename the shortcut as your wish. Ex: Deployment Test 1.0
 Set the ―Icon‖ property if required.
 Drag and drop the shortcut into ―User‘s Desktop‖ folder.
 Create another shortcut (same as above). Rename it as your wish. Ex: Deployment Test
1.0. Then set the ―Icon‖ property for the shortcut.
 Drag and drop that shortcut into ―User‘s Programs Menu‖ folder.
 In the ―Solution Explorer‖, right click on the ―Deployment Test 1.0‖ and choose ―Rebuild‖.
 Then the setup files will be generated in the ―Debug‖ folder of the project. To open the
folder, right click on ―DeployementTest‖ and select ―Open Folder is Windows Explorer‖.

Installing the Project:

 To install the application, simply double click on the ―Setup‖ file and complete the wizard
steps.

.NET 4.0 and Visual Studio 2010 Page 500 of 548


Un-Installing the Project:

 To un-install the project, go to ―Add/Remove Programs‖ option in the Control Panel.


(or)
 Double click on ―setup.exe‖ file again and select ―Remove‖ option.

Issuing the Project to the Client:

 To issue the project to the client, simply issue the following two files.
1. setup.exe
2. Deployment Test 1.0.msi

Known Limitation: The above ―setup.exe‖ file carries all the necessary executable files, dll files,
images, icons, App.config files etc., but can‘t carry the database tables and stored procedures.
You have to use ―Import / Export‖ given by the DBMS software (SQL Server / Oracle).

.NET 4.0 and Visual Studio 2010 Page 501 of 548

You might also like