Professional Documents
Culture Documents
A Windows Application
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:
And then, double click on ―Cancel‖ button and write the following 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>
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();
#endregion
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).
Form1.cs
importing section;
namespace ProjectName
{
public partial class FormName : Form
{
public FormName()
{
InitializeComponent();
}
}
}
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.
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.
Application.Run(new Form1());
This statement creates a new Form1 class object and that object will be
shown on the screen.
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
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.
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
TabIndex controlname.TabIndex = n;
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:
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.
Design
button1:
Text: Click Me
BackColor: DarkRed
ForeColor: Yellow
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
The ―System.Windows.Forms.Form‖ class offers few properties, methods and events for each
user-defined form class.
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;
Opacity this.Opacity = n;
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
Design
Form1:
Text: Click the form
Design
button1:
Text: Red
Name: btnRed
button2:
Text: Green
Name: btnGreen
button3:
Text: Blue
Name: btnBlue
Design
button1:
Text: Normal
Name: btnNormal
button2:
Text: Minimize
Name: btnMinimize
button3:
Text: Maximize
Name: btnMaximize
button3:
Text: Exit
Name: btnExit
Design
button1:
Text: Show Background Image
Name: btnShowBackgroundImage
button2:
Text: Clear Background Image
Name: btnClearBackgroundImage
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.
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.
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.
Methods of TextBox
Method Description
Clear() Clears all the contents of the textbox and makes it empty.
Focus() Moves the focus to the control.
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
Design
label1:
Text: Enter your text here:
Name: lblSourceText
textBox1:
Name: txtSourceText
label2:
Text: Copied Text:
Name: lblDestinationText
button1:
Name: txtDestinationText
ReadOnly: True
label3:
Text: To:
Name: lblTo
textBox2:
Name: txtTo
button1:
Name: btnGo
Text: GO
textBox3:
Name: txtNumbers
ReadOnly: True
MultiLine: True
ScollBars: Vertical
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.
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.
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
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.
Design
linkLabel1:
Text: My Link Label:
Name: linkLabel1
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
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
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
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.
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
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.
Events of ListBox
Event Description
SelectedIndexChanged, Click, DoubleClick, MouseMove, MouseEnter, MouseLeave, KeyPress, Leave
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.
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:
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
label1:
11) ComboBox
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
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
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
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
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.
14) DateTimePicker
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
15) MonthCalendar
API: System.Windows.Forms.MonthCalendar
Naming Convension: monCalxxxxxx
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.
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
17) Timer
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.
Design
timer1:
Name: tmrBackColor
Interval: 500
Enabled: True
18) ProgressBar
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
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
using System.IO;
19) MenuStrip
API: System.Windows.Forms.MenuStrip
Naming Convension: mnuxxxxxx
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
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
Note: All the dialog box controls are known as ―invisible controls‖.
21) ColorDialog
API: System.Windows.Forms.ColorDialog
Naming Convension: colorDlgxxxxxx
Design
button1:
Name: btnBackColor
Text: Back Color
colorDialog1:
Name: colorDlgBackColor
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
Design
textBox1:
Name: txtMyText
button1:
Name: btnFont
Text: Font
fontDialog1:
Name: fontDialogMyText
23) FolderBrowserDialog
API: System.Windows.Forms.FolderBrowserDialog
Naming Convension: folderBrowserDlgxxxxxx
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
24) OpenFileDialog
API: System.Windows.Forms.OpenFileDialog
Naming Convension: openFileDlgxxxxxx
25) SaveFileDialog
API: System.Windows.Forms.SaveFileDialog
Naming Convension: saveFileDlgxxxxxx
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
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;
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
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.
Creates an icon at the system‘s notification area (on the windows task bar).
API: System.Windows.Forms.NotifyIcon
Naming Convension: notifyxxxxxx
Design
notifyIcon1:
Name: notifyIcon1
Text: My Application
Icon: laptop.ico
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
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
30) TreeView
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
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:
MDI Applications
The windows applications are of two types.
1) SDI Applications (Single Document Interface)
2) MDI Applications (Multiple Document Interface)
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.
Design
Form1:
IsMdiContainer: True
Form1.cs
Library: System.Windows.Forms.MessageBox
Syntax:
MessageBox.Show(“message”); MessageBox.Show(“message”,
MessageBoxButtons.xxxxxx);
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);
Sometimes, you may need to add the controls programmatically at run time.
obj.property = value;
containername.Add(value);
Design
button1:
Text: Add Exit Button
Output:
Design
button1:
Name: btnShowNumbers
Text: Show Numbers
textBox1:
ReadOnly: True
TextAlign: Right
Output:
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.
Implementation:
In the above code, the ―CreateGraphics()‖ method creates a graphics object, that is able to write
the GDI graphics in the container (form).
1) Drawing Lines
g.DrawLine(Pens.xxxx, x1, y1, x2, y2);
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);
Application 132: Demo on GDI (Drawing Lines, Rectangles, Circles, Triangles, Curves)
Click on ―Save‖ button to save the table. Then it asks for the table name. Enter
the desired table name.
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.
2. DROP
drop table tablename;
3. ALTER
alter table tablename add columnname datatype(width);
alter table tablename drop column columnname;
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;
use master
drop database test
GO
use test
GO
select * from Products where price not between 2000 and 8000
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.
Procedure:
GO
execute ShowSquare 5
Function:
GO
select dbo.GetCube(5)
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.
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
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.
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.
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.
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
Connection Command
ConnectionString CommandText
Open() Connection
Close() CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
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.
Form1.cs
Insertion.cs
using System.Data.SqlClient;
//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();
}
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();
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:
Deletion.cs
using System.Data.SqlClient;
//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();
}
Updation.cs
using System.Data.SqlClient;
string gen;
if (radioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
//presentation logic
if (n > 0)
MessageBox.Show(n + " Row Updated.");
else
MessageBox.Show("Updation failed.");
cn.Close();
}
Connection
.NET
Application
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.
Connection
ConnectionString
Open()
Close()
Command
CommandText
Connection
CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
DataReader
Read()
[“column_name”]
[index]
Close()
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)
(true)
dr.Read();
(true)
dr.Read();
(true)
dr.Read();
(false)
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.
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
DataReaderDemo.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();
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:
Form1.cs
DataReaderDemo_RecordByRecord.cs
using System.Data.SqlClient;
SqlDataReader dr;
SqlConnection cn = new SqlConnection();
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
//DataReader impl
dr = cmd.ExecuteReader();
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:
Form1.cs
DataReaderDemo_ConditionalData.cs
using System.Data.SqlClient;
//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;
dr.Close();
cn.Close();
}
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.
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.
Connection
DataSet
DataTable
0
1
2
3
.NET DataRow
Application 0 1 2
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”]
Clear(): Clears all the tables, and makes the dataset empty.
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
DataSetDemo.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
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:
Form1.cs
private void
viewDataUsingDataSetFlexibleRecordsPresentationToolStripMenuItem_Click(object sender,
EventArgs e)
{
DataSetDemo_FlexibleRecords f = new DataSetDemo_FlexibleRecords();
f.MdiParent = this;
f.Show();
}
DataSetDemo_FlexibleRecords.cs
using System.Data;
using System.Data.SqlClient;
DataTable dt;
int RowIndex;
DataRow drow;
//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];
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.
Sample Output:
Add the menu item ―View Data using Data Set - DataGridView‖ as shown below:
Form1.cs
DataSetDemo_DataGridView.cs
using System.Data;
using System.Data.SqlClient;
//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;
}
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.
Connection
Command
(provider, data (procedure / .NET
db Source, user id, function name,
parameters) Application
password)
Demo:
Form1.cs
StoredProcedureDemo.cs
using System.Data.SqlClient;
//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();
}
Form1.cs
StoredProcedureDemo_MultipleTables.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("getdata", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
//grid logic
dataGridView1.DataSource = dt1;
dataGridView2.DataSource = dt2;
}
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”.
</appSettings>
</configuration>
In the ―<appSettings>‖ tag, use ―<add>‖ tag to declare the actual application
configuration setting values.
Note: The ―key‖ is used to access the configuration setting value in the code.
App.Config
using System.Configuration;
using System.Data.SqlClient;
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)
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.
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‖.
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
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
UI
Data
Business Access Access
Presentation Layer
Layer Layer
db
A. DCOM:
It is in usage, before .NET.
It is platform dependent.
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.)
App.Config
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);
}
}
}
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;
}
}
}
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
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)
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.
IRemote irem;
irem = (IRemote)Activator.GetObject(typeof(IRemote), ―tcp://server:port/alias_name‖);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RemoteLibrary
{
public interface IRemote
{
bool CheckUserAvailability(string UserName);
}
}
App.config:
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);
}
}
}
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‖.
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.
Form1.cs:
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using RemoteLibrary;
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.
Library:
1) System.Net.Sockets
2) Some classes from ―System.IO‖
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);
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);
using System.Net.Sockets;
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.
using System.Net.Sockets;
using System.IO;
using System.Net;
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.
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()
{
InitializeComponent();
}
Thread th1;
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
―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.
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‖.
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.
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)
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.
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:
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;
using System.IO;
installutil D:\ChatService\ChatService\bin\Debug\ChatService.exe
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.
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.
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
To install the application, simply double click on the ―Setup‖ file and complete the wizard
steps.
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).