Windows Programming
-In development of any application we
require a user interface (UI) to communicate with end users, these user
interfaces are of 2 types:
-CUI
(Character User Interface)
-GUI
(Graphical User Interface)
-Traditionally we have only CUI, eg:
Dos, Unix OS etc., where these applications suffers from few criticisms like:
1. They are not user friendly, bco'z we need
to learn the commands first to use
them.
2. They do not allow to navigate from one
place to other.
-To solve the above problems, in
early 90's GUI applications are introduced by Microsoft with it's Windows OS,
which has a beautiful feature known as 'Look & Feel'. To develop them they
introduced a language also into the market in 90's only i.e VB, later when Microsoft's
.Net was introduced the support for GUI has been given in all .net lang's.
-------------------------------------------------------------------------------------
Developing windows applications:
-To develop a GUI we require a set of
components known as controls which are provided in .net directly as classes
under System.Windows.Forms namespace.
-All the controls we have been
provided, were categorized into different groups like:
1. Common Controls
2. Container Controls
3. Menu's & Tool Bar Controls
4. Dialog Controls
5. Reporting Controls
6. Printing Controls
7. Data Controls etc.,
-What ever the control it was every
control has 3 things in common:
i) Properties: these are attributes of a control which have their impact
on look of the control.
eg: Width, Height, BackColor,
ForeColor, etc.,
ii) Methods: these are actions performed by a control. eg: Clear(),
Focus(), Close(), etc.,
iii) Events: these are time periods which
specifies when an action has to be performed.
eg: Click, Load, KeyPress, MouseOver,
etc.,
Note: the parent class of all the
control classes is Control which is definied with the properties, methods &
events that are common for all the controls.
-------------------------------------------------------------------------------------
-How to develop a Windows Application
?
Ans: To develop a Windows Application
the base control that has to be created first is Form. To create a Form define
a class inheriting from the predefined class "Form" so that the new class
also becomes a Form.
eg: public
class MyForm : Form
-To run the Form we have created call
the static method Run of Application class by passing the object of Form.
eg: MyForm
f = new MyForm();
Application.Run(f);
Or
Application.Run(new
MyForm());
Note: we can develop a windows
application either by using a notepad following the above process as well as
under visual studio using "Windows Forms Application" project
template.
-------------------------------------------------------------------------------------
Developing Windows App using Notepad:
-Open notepad, write the following
code in it, save, compile & then execute:
using System;
using System.Windows.Forms;
public class MyForm : Form
{
static void Main()
{
Application.Run(new MyForm());
}
}
-------------------------------------------------------------------------------------
Developing Windows Application under
VS:
-To develop a windows app. under VS
open new project window -> select Windows Forms App template & specify a
name to the project.
eg: WindowsProject.
-By default the project comes with 2
classes in it:
-Program.cs
-Form1.cs
-The execution of windows application
starts from the class Program which is static & under this class we find a
Main method creating the object of form class that has to be executed:
eg: Application.Run(new
Form1());
-Form1.cs is the file in which the
class Form1 is defined inheriting from predefined class Form & this is the
class that has to be executed.
eg: public partial class Form1 : Form
-Windows applications developed under
VS has 2 places to work with:
1.
Design View
2.
Code View
-Design View is the place where we
design the app. which is accessible both to programmer's and end user's.
-Code View is the place where we
write the code for execution of app. which is accessible only to programmers.
Note: because of the design view what
VS provides it is known as WYSIWYG Editor (What You See Is What You Get).
-------------------------------------------------------------------------------------
Properties:
-As we are aware that every control
has properties, methods & events, to access the properties of a control VS
provides property window which lists all properties corresponding to that
control. To open it select the control and press F4, we can change any property
in the list like Width, Height, BackColor etc., for which you can see the
impact immediately.
-When ever we set a value to any
property of a control VS on behalf of us will write all the necessary code
referring to each property by assigning the values we have specified under
property window. We can view that code under a method InitializeComponent()
which gets called from the constructor.
-To view code under
InitializeComponent, goto Code View, right click on the method and select 'Go
to definition' which takes to Form1.Designer.cs file and here also we find the
same class Form1 as it is partial.
eg:
this.Text = "First Form";
this.BackColor = Color.Pink;
this.Size = new Size(350, 350);
-------------------------------------------------------------------------------------
Events:
-These are time periods which tells
when an action has to be performed i.e. when exactly we want to execute the
code. Every control will have no. of events under it where each event occurs or
raises on a particual time period.
-We can access the events of a
control also under property window only. To view them in the property window
choose events option on top of property window.
-If we want to write any code under
an event
double click on the desired event,
which takes you to code view and provides a method for writing the code.
-In the project we have opened, go to
Events of Form & double click on Load Event, then write the following code
under Form1_Load method generated in Code View:
MessageBox.Show("Welcome to
windows app");
-Again go to design view, double
click on Click Event & write following code under Form1_Click method:
MessageBox.Show("You have
clicked on form");
------------------------------------------------------------------------------------
-What is the method under which we
are writting code corresponding to an Event?
Ans: The method under which we are
writing the code corresponding to an event has a special name "Event
Procedure", which is a block of code that is bound with an event of
control and gets executed when ever the event occurs or raises.
-The code written under an event
procedure will be executed by the Event when it occurs taking the help of a
Delegate as following:
-In the above case when ever the
Event occurs or raises it will call the delegate which then executes the event
procedure that is bound with Event.
-------------------------------------------------------------------------------------
-How does an Event, Delegate &
Event Procedure gets linked with each other?
Ans: Events & Delegates are
predefined under BCL (Events are defined in control classes & delegates are
defined under some namespace), what we define here is only an event proc. After
defining an event proc in form class to link the Event, Delegate & Event
Procedure VS writes a mapping statement as following:
Syntax:
<control>.<event> +=
new
<delegate>(<event procedure>)
eg:
this.Load += new EventHandler(Form1_Load);
button1.Click +=
new EventHandler(button1_Click);
textBox1.KeyPress += new
KeyPressEventHandler(textBox1_KeyPress);
Note: Multiple events may use same
delegate for execution but all events will not use the same delegate, where
different events may use different delegates to execute event proc's. We can
see all above code we have discussed
under the method InitializeComponent.
------------------------------------------------------------------------------------
-How can we define Event Proc's
manually?
Ans: To define Event Proc's manually
we adopt a standard process as following:
Syntax:
[<modifiers>] void
<Name>(
object
sender, EventArgs e)
{
<Stmts>;
}
-Event Proc's are non-value returning
methods.
-An event proc can have any name but
VS adopts a convention while naming them i.e. <control
name>_<event>. eg: Form1_Load, button1_Click, textBox1_KeyPress
-Every event procedure will take 2
mandatory parameters:
1.
object sender
2.
EventArgs e
Note: The concept of events &
event proc's has been derived from classical VB, but there an event proc can be
bound with only single event of single control, where as in .net it can be
bound with multiple events of a single control as well as with multiple controls
also.
-------------------------------------------------------------------------------------
Adding new Forms in the project:
-A project can contain any no. of
forms in it, to add a new form under project open the solution explorer, right
click on project & select Add -> Windows Form that add's a new form
Form2.cs. To run the new form goto Program.cs file and change code under
Application.Run method as Form2.
eg:
Application.Run(new Form2());
-------------------------------------------------------------------------------------
Binding an Event Proc's with multiple
events of a control under VS:
-After the new form is added to
project go to its events and double click on Load which defines an event proc
"Form2_Load". To bind the same event proc with click event of form
also, again go to events, select click event and click on the drop down beside
which displays a list of event proc's available, select 'Form2_Load' that is
defined previously, which binds the event proc with click event also, now under
the proc write the following code & execute:
MessageBox.Show("Bound with
multiple events of a control");
-------------------------------------------------------------------------------------
Placing controls on a form:
-By default we are provided with no. of
controls in the form of classes, available in 'ToolBox' window, to see them go
to view menu & select ToolBox, that displays all controls organised into
different Tabs (groups).
-To place a control on the form
either double click on desired control or select the control & place it in
the desired location on form.
Note: use Layout toolbar to align
controls properly.
-------------------------------------------------------------------------------------
Binding an Event Proc with multiple
controls:
-Add a new form under project and
design it as following:
-Define a click event proc for
button1 and bind the event proc with button2, Form, textBox1 & textBox2
controls then write the following code under the event procedure:
if (sender.GetType().Name ==
"Button")
{
Button b = sender as Button;
if (b.Name == "button1")
MessageBox.Show("Button1 is clicked");
else
MessageBox.Show("Button2 is clicked");
}
else if (sender.GetType().Name ==
"TextBox")
{
TextBox tb = (TextBox)sender;
if (tb.Name == "textBox1")
MessageBox.Show("TextBox1 is clicked");
else
MessageBox.Show("TextBox2 is clicked");
}
else
MessageBox.Show("Form is clicked");
-When a event proc is bound with
multiple controls, if we want to recognize which control has raised the event
with the event procedure we make use of parameter "sender" of event
proc, because in runtime the object of control that has raised the event will
be sent to event procedure as following and captured under sender:
-In the above case we have bound the
event proc with different type of controls (Button's, TextBox's & Form), so
first we can identify the type (Class) of control that has raised the event
(Button or TextBox or Form) using GetType() method of object class.
-After recognizing the type of control
it was, if there are multiple controls of same type then we need to convert
sender into the appropriate control type to identify "Name" of each
control, because sender is of parent type which cannot refer to members of its
child class (Button or TextBox now).
-Converting sender into appropriate
control type can be done in 2 ways as following:
Button
b = (Button)sender;
Or
Button
b = sender as Button;
-------------------------------------------------------------------------------------
Q. How does a form gets created ?
Ans. When a form is added to the
project internally following things takes place:
i) Creates a class inheriting from the pre-defined class Form so that
the new class is also a Form.
eg: public partial class Form1 :
Form
ii) Sets some initialization properties like name, text etc., under
InitializeComponent method.
eg: this.Name =
"Form1";
this.Text
= "Form1";
-----------
Q. How does a control gets placed on
the form ?
Ans: When a control is placed on the
form following things takes place internally:
i) Creates object of appropriate control class.
eg: Button button1 = new Button();
TextBox textBox1 = new TextBox();
ii) Sets some initialization properties that are required like name,
text, size, location etc.,
eg: button1.Name = "button1";
button1.Text = "button1";
button1.Location = new Point(x, y);
button1.Size = new Size(width, height);
iii) Now the control gets added to form by
calling Controls.Add method on current Form.
eg: this.Controls.Add(button1);
Note: All the above code will be
generated by VS under InitializeComponent method.
-Under a windows application code is
of 2 types:
-Designer
Code
-Business
Logic
-Code which is responsible for
construction of the form is known as designer code.
-Code which is responsible for
execution of the form is known as business logic.
-Desinger Code is generated by VS
under the method InitializeComponent & business logic is written by
programmers in the form of event procs.
-Before .net 2.0 designer code and
business logic were defined in a class present under a single file as
following:
Before
2.0
Form1.cs:
public class Form1 : Form
{
-Designer Code
-Business Logic
}
-From .net 2.0 with introduction of
partial classes designer code and business logic are seperated into 2 different
files but of the same class only as following:
From
2.0
Form1.cs:
public partial class Form1 : Form
{
-Business Logic
}
Form1.Designer.cs:
partial class Form1
{
-Designer Code
}
-------------------------------------------------------------------------------------
Default Events: as we are aware every
control has no. of events to it, but 1 event will be its default. To write code
under default event of a control directly double click on it which takes to its
mapping event proc.
Control: Default Event:
Form Load
Button Click
TextBox TextChanged
CheckBox & RadioButton CheckedChanged
TreeView AfterSelect
Timer Tick
ListView, ListBox, ComboBox
& CheckedListBox
SelectedIndexChanged
-------------------------------------------------------------------------------------
Controls:
1. Button: used for taking acceptance
of a user for performing an action.
2. Label: used for displaying static
text on the UI.
3. TextBox: used for taking text
input from the user, this control can be used in 3 different ways:
i. Single Line Text (d)
ii. Text Area (Multi Line Text)
iii.
Password Field
-The default behaviour of the control
is single line text to make it multi line set the property Multiline as true.
By default the text area will not have scroll bars to navigate up & down,
to get them set the ScrollBars property either to Vertial or Horizontal or
Both.
Note: by default the WordWrap
property of control is set as true restricting horizontal scroll bar so set it
as false to get horizontal scroll bar.
-To make the control used as a
password field set the PasswordChar property of control with "*";
-------------------------------------------------------------------------------------
Setting Tab Order of Form Controls:
-While working with a windows app we
navigate between controls using the Tab key of key board. By default Tab key
navigates the focus between controls in the same order how they are placed on
the form. If we want to set the sequence of tab on our own, it can be done by
setting the 'Tab Order'. To do this go to View Menu and select 'Tab Order'
which shows the current tab order, now click on each control in a sequence how
we want to move the tab, again go to view menu & select Tab Order.
-In the above form perform the below
validations:
1. Check the user name, pwd &
confirm pwd fields to be mandatory.
2. Check pwd to be ranging between 6
to 12 chars.
3. Check confirm pwd to be matching
with pwd.
4. Allow users to close the form if
required from mandatory fields also.
-To perform the above 4 validations
first set the MaxLength property of pwd textbox's to 12 so that they accept only
12 chars.
-Define a validating event for user
name textbox & bind the event proc with both pwd textbox's.
-Define a leave event for user name
textbox & bind the event proc with both pwd textbox's.
-Leave event occurs when the focus is
leaving a control & then validating event occurs to validate the content of
control.
-Now write the following code:
Class Declarations:
TextBox tb;
-------------------------------------------------------------------------------------
Under Leave Event Procedure:
tb = sender as TextBox;
-------------------------------------------------------------------------------------
Under Validating Event Procedure:
tb = sender as TextBox;
if (tb.Text.Trim().Length == 0)
{
MessageBox.Show("Cannot leave
empty");
e.Cancel = true;
return;
}
if (tb.Name != "txtName")
{
if (tb.Text.Trim().Length < 6)
{
MessageBox.Show("Pwd should be between 6 to 12 chars");
e.Cancel = true;
return;
}
}
if (tb.Name == "txtCPwd")
{
if (txtPwd.Text.Trim() != txtCPwd.Text.Trim())
{
MessageBox.Show("Confirm pwd should match with pwd");
e.Cancel = true;
}
}
-Not all events but few events have
properties under them eg: Validating, KeyPress etc., if we want to consume the
properties of an event under its event proc we can make use of the parameter
"e" which refers to properties of current executing event.
-In the above case Cancel is property
of validating event when set as true cancels the event and restricts the focus
to leave the control.
-To close the form even from mandatory
fields goto properties of Close button & set 'CausesValidation' property as
false so that code under that button gets executed before the execution of any
controls validating event.
Under Close Button:
tb.CausesValidation = false;
this.Close();
-tb.CausesValidation = false will
restrict validating event of textbox not to occur so that focus can leave the
textbox and form gets closed.
-------------------------------------------------------------------------------------
5. Check phone textbox to accept only
numerics.
-To do this define a keypress event
proc for phone textbox and write the following in it:
//MessageBox.Show(Convert.ToInt32(
e.KeyChar).ToString());
if (char.IsDigit(e.KeyChar) == false
&& Convert.ToInt32(e.KeyChar) != 8)
{
MessageBox.Show("Enter numerics
only");
e.Handled = true;
}
-KeyPress event occurs when we press
& release a key while the focus is in the control.
-KeyChar property of keypress gets
the key value corresponding to the key pressed.
-Handled property when set as true
will restrict the key value to enter into the control.
-Char.IsDigit(char) will return true
if the given char is a numeric or else returns false.
-Convert.ToInt32(char) will return
ascii value of the given character.
-------------------------------------------------------------------------------------
Under Save Button:
//Code for saving the data to db
MessageBox.Show("Data saved to
database");
-------------------------------------------------------------------------------------
Under Clear Button:
txtName.Text = txtPwd.Text=
txtCPwd.Text = "";
txtPhone.Clear(); txtAddr.Clear();
txtName.Focus();
-------------------------------------------------------------------------------------
-Under Form we have 2 properties
AcceptButton & CancelButton which allows us to map buttons on a form with
keyboard keys.
-AcceptButton property if set with a
button that button gets clicked when ever we press Enter key of key board.
-CancelButton property if set with a
button that button gets clicked when ever we press Esc key of key board.
-To set them go to properties of form
select either AcceptButton or CancelButton properties which will display the
list of buttons on form select a button from them.
-------------------------------------------------------------------------------------
RadioButton & CheckBox:
-We use the controls when we want
users to select from a list of values. RadioButton allows only a single value
to select from a group of values where as CheckBox allows multiple selection.
-As RadioButton's allow only single
selection when we want to use them under multiple options or questions we need
to group related RadioButton's so that 1 can be selected from each group, to
group them we need to place RadioButtons on seperate container controls like
Panel, GroupBox, TabControl etc.
-Both these controls provide a common
boolean property Checked which returns true if the control is selected or else
returns false, using which we can identify which option has been choosen by the
users.
-------------------------------------------------------------------------------------
Under First Button:
if (radioButton1.Checked)
MessageBox.Show("Radio Button1 is selected");
else if (radioButton2.Checked)
MessageBox.Show("Radio Button2 is selected");
else if (radioButton3.Checked)
MessageBox.Show("Radio Button3 is selected");
-------------------------------------------------------------------------------------
Under Second Button:
if (checkBox1.Checked)
MessageBox.Show("Check Box1 is selected");
if (checkBox2.Checked)
MessageBox.Show("Check Box2 is selected");
if (checkBox3.Checked)
MessageBox.Show("Check Box3 is selected");
-------------------------------------------------------------------------------------
Declarations:
int count = 0;
-------------------------------------------------------------------------------------
Define a CheckedChanged event for 1
Check Box, bind with the remaining Check Box's & then write following code
under the event procedure:
int amt = int.Parse(txtFees.Text);
CheckBox cb = sender as CheckBox;
if (cb.Checked)
{
count += 1;
amt += Convert.ToInt32(cb.Tag);
}
else
{
count -= 1;
amt -= Convert.ToInt32(cb.Tag);
}
txtFees.Text = amt.ToString();
if (count == 0)
radioButton1.Checked = true;
-------------------------------------------------------------------------------------
Define a CheckedChanged event for 1
radio button, bind with the remaining radio button's & then write following
code under the event procedure:
int amt = int.Parse(txtFees.Text);
if (amt > 0)
{
RadioButton rb = sender as RadioButton;
if (rb.Checked)
amt += Convert.ToInt32(rb.Tag);
else
amt -= Convert.ToInt32(rb.Tag);
txtFees.Text = amt.ToString();
}
else
radioButton1.Checked = true;
-------------------------------------------------------------------------------------
Under Clear All Button:
foreach (Control ctrl in
groupBox1.Controls)
{
if (ctrl.GetType().Name == "CheckBox")
{
CheckBox cb = ctrl as CheckBox;
cb.Checked = false;
}
}
-------------------------------------------------------------------------------------
ComboBox, ListBox, CheckedListBox:
-These controls are also used for
users to select from a list of available values.
-ComboBox allows only single
selection but it was editable which gives a chance to either select from the
available values or enter a new value.
-ListBox by default allows single
selection only but can be customized to multi-selection.
-CheckedListBox by default allows
multi-selection.
Adding values to the controls:
-We can add values to the 3 controls
in diff. ways:
i) In the properties of the control
we find a property Items, select it and click on the button beside it which
opens a window, enter the values you want to add each in a new line.
ii) Using Items.Add method of the
control values can be added one at a time.
<control>.Items.Add(object
value)
iii) Using Items.AddRange method of
the control an array of values can be added at a time.
<control>.Items.AddRange(object[]
vals)
iv) Using DataSource property of the
control a DB table can be bound to it, but as it can display only a single
column we need to specify the column to be displayed using the DisplayMember
property.
<control>.DataSource = <data table>
<control>.DisplayMember = <col name>
Multi-Selection for ListBox:
ListBox control by default allows
single selection only but by changing the SelectionMode property either to
MultiSimple or MultiExtended multi selection is possible.
-SelectionMode
-None
-One
[d]
-MultiSimple
[Only mouse click]
-MultiExtended [Ctrl + Mouse click]
Identifying selected values from the
controls:
ComboBox:
-Text string
-SelectedItem object
-SelectedIndex int
ListBox:
-SelectedItem object
-SelectedIndex int
-SelectedItems object[]
-SelectedIndices int[]
CheckedListBox:
-CheckedItems object[]
-CheckedIndices int[]
-------------------------------------------------------------------------------------
Under Form Load:
listBox1.Items.Add("AP");
listBox1.Items.Add("Tamilnadu");
---<List of states in the same
way>---
string[] cities = {
"Hyderabad", "Chennai", "Delhi", "Bengluru",
"Mumbai", , "Kolkota" };
checkedListBox1.Items.AddRange(cities);
-------------------------------------------------------------------------------------
Under ComboBox KeyPress:
//Adds value to comboBox in runtime
if (Convert.ToInt32(e.KeyChar) == 13)
if(comboBox1.FindString(comboBox1.Text) == -1)
comboBox1.Items.Add(comboBox1.Text);
FindString(string value): returns the
index position of the given value under the control.
FindStringExact(string value): same
as above but checks with the case also.
-------------------------------------------------------------------------------------
Under First Button:
MessageBox.Show(comboBox1.Text);
MessageBox.Show(
comboBox1.SelectedItem.ToString());
MessageBox.Show(
comboBox1.SelectedIndex.ToString());
-------------------------------------------------------------------------------------
Under Second Button:
foreach (object obj in
listBox1.SelectedItems)
MessageBox.Show(obj.ToString());
-------------------------------------------------------------------------------------
Under Third Button:
string str = null;
foreach (object obj in checkedListBox1.CheckedItems)
str += obj.ToString() + ", ";
str = str.Substring(0, str.Length -
2);
int pos =
str.LastIndexOf(",");
if (pos != -1)
{
str = str.Remove(pos, 1);
str = str.Insert(pos, " &");
}
MessageBox.Show(str);
-------------------------------------------------------------------------------------
SelectedIndexChanged: it is the
default event of all the above 3 controls which gets raised once a value gets
selected from them.
-------------------------------------------------------------------------------------
Declarations:
string[] q1 = { "January",
"February", "March" };
string[] q2 = { "April",
"May", "June" };
string[] q3 = { "July",
"August", "September" };
string[] q4 = {
"October","November","December" };
-------------------------------------------------------------------------------------
Under ComboBox1 SelectedIndexChanged:
comboBox2.Items.Clear();
switch (comboBox1.SelectedIndex)
{
case 0:
comboBox2.Items.AddRange(q1);
break;
case 1:
comboBox2.Items.AddRange(q2);
break;
case 2:
comboBox2.Items.AddRange(q3);
break;
case 3:
comboBox2.Items.AddRange(q4);
break;
}
-------------------------------------------------------------------------------------
PictureBox:
-we use it for displaying images with
in an app. To bind an image to the control we can use any of the following
properties:
-ImageLocation = <path of the image>
-Image = Image.FromFile(<path of the image>)
-Image = Image.FromStream(Stream stream)
-Use BorderStyle property to control
what type of border we want for the PictureBox, with any of the following
values:
-None
[d]
-FixedSingle
-Fixed3d
-Use SizeMode property of the control
to set image placement & control sizing under the pictureBox which can be
set with any of the following:
-Normal
[d]
-StretchImage
-AutoSize
-CenterImage
-------------------------------------------------------------------------------------
Dialog Controls: these are used for
displaying a list of system values from which the users can select. We have 5
different dialog controls in .Net like ColorDialog, FolderBrowserDialog,
FontDialog, OpenFileDialog & SaveFileDialog.
-None of the dialog controls are
shown directly on form even after adding
them we can see them only at the bottom of studio in the design time, to make
them visible in runtime we need to explicitly call the method ShowDialog()
which is same for all the 5 controls.
-Dialog Controls never performs any
action they are only responsible for returning the value that has been choosen
by user to the programmer who is responsible for performing the necessary
actions. To capture the values that are choosen by end users we are provided
with following properties:
-ColorDialog Color
-FolderBrowserDialog SelectedPath
-FontDialog Font
-OpenFileDialog FileName
-SaveFileDialog FileName
-------------------------------------------------------------------------------------
Under Change Color Button:
colorDialog1.ShowDialog();
button1.BackColor =
colorDialog1.Color;
-------------------------------------------------------------------------------------
Under Change Font Button:
fontDialog1.ShowDialog();
button2.Font = fontDialog1.Font;
-------------------------------------------------------------------------------------
Under Load Image Button:
openFileDialog1.ShowDialog();
pictureBox1.ImageLocation = openFileDialog1.FileName;
-------------------------------------------------------------------------------------
Under Save Image Button:
saveFileDialog1.ShowDialog();
pictureBox1.Image.Save(
saveFileDialog1.FileName);
----------------------------------------------------------------------------MaskedTextBox:
-It is same as a TextBox but can be
used for taking the input in some specific formats from the user. To set a
format for input, select the Mask property in property window & click on
the button beside it which opens a window in it either choose from list of
available masks or select custom and specify your own format using zeros in the
mask textbox below as following:
-Railway PNR: 000-0000000
-CC No.: 0000-0000-0000-0000
-Short Date: 00/00/00
-------------------------------------------------------------------------------------
Timer Control: it's a control which
can perform an action regularly at a specified interval similar to a button
which performs the action only after we click on it.
Members of Timer:
1. Tick: an event under which we need
to write the code that has to be executed.
2. Interval: a property using which
we specify the frequency of execution in milliseconds.
3. Start(): a method to start the
execution of timer.
4. Stop(): a method to stop the
execution of timer.
-------------------------------------------------------------------------------------
Creating a Menu to Form:
-To create a menu for Form add
MenuStrip control to Form which gets added on top of the Form.
-To add a Menu on MenuStrip click on
LHS corner of it which opens a textbox asking to type here enter a Name in it
which adds a Menu, repeat the same process for adding multiple Menu's.
-To add a MenuItem under a menu click
on the Menu which opens a textbox below asking to type here, enter a
"Name" in it which adds a MenuItem, repeat the same process for
adding multiple MenuItem's.
Note: a Menu & MenuItem are
object's of the class ToolStripMenuItem.
-If we want Menu's to be responding
for "Alt Keys" of keyboard prefix with "&" before the
character that should respond for Alt.
eg:
&File &Edit F&ormat
-To create a shorcut for MenuItem so
that it responds to keyboard actions, go to properties of MenuItem, select
"ShortcutKeys" Property, click on drop down beside it, that displays
a window, in it choose a Modifier Ctrl or Alt or Shift and then choose a Key
from ComboBox below.
-To group related MenuItems under a
Menu we can add seperators between MenuItems, to do it right click on a
MenuItem & select Insert -> seperator which adds a seperator on top of
the MenuItem.
Note: same as we inserted a seperator
we can also insert a MenuItem if required in the middle.
-If we want to display any Image
beside MenuItem right click on it & select "Set Image" which
opens a window, select Local Resource & click on Import button which opens
a DialogBox, using it select an image from your Harddisk.
-Some times we find check marks
beside MenuItem to identify a property is on or off, eg: WordWrap under
Notepad. To create check mark's beside a MenuItem right click on it and select
"Checked".
Note: to check or uncheck the item in
run time we need to write code explicitly under it's click event as following:
if
(<control>.Checked == true)
<control>.Checked = false;
else
<control>.Checked = true;
-------------------------------------------------------------------------------------
Multi Document Interfaces:
-While designing an application with
multiple forms in it, right now we are explicitly setting the start-up form
under the class Program, but as we don't provide source code to client when we
deploy the app, he doesn't have a chance to edit the class Program and specify
his start up form. In that case we use MDI approach.
-In this approach we will be having
only 1 form as a start up, so that clients doesn't require to change it each
time, rest of the forms in app will be under the control of Main Form or Start
Up Form. Here we will be having 2 parts:
-MDI Parent -MDI Child
-The Form which is going to be a
start-up form is MdiParent and to make it as an MdiParent we need to set the
IsMdiContainer property of Form as true.
Note: an application can have only 1
MdiParent, all the other forms should be childs of parent, which comes &
sits under parent, e.g.: Visual Studio is an MdiParent which launches all the
other forms under it as childs.
-To launch a form as child of parent
create object of Form class which has to be launced as child, set its MdiParent
property with parent forms reference and then call Show method.
Layout:
-When we have more than one child
form opened under parent at a time, the way how child forms gets arranged in
parent can be set with a layout, which has 4 options like:
i) Cacade (d): child forms are arranged 1 on top
of
the other.
ii) TileVertical: child forms are arranged 1 beside the other.
iii) TileHorizontal: child forms are arranged
1 below the other.
iv) ArrangeIcons: all the child forms icons
are arranged with in the bottom of parent.
-------------------------------------------------------------------------------------
Under Each Form's MenuItems:
Form1 f = new Form1();
f.MdiParent = this;
f.Show();
----------------------------------------------------------------------------
Under Arrange Icons MenuItem:
this.LayoutMdi(MdiLayout.ArrangeIcons);
----------------------------------------------------------------------------
Under Cascade MenuItem:
this.LayoutMdi(MdiLayout.Cascade);
----------------------------------------------------------------------------
Under Vertical MenuItem:
this.LayoutMdi(MdiLayout.TileVertical);
----------------------------------------------------------------------------
Under Horizontal MenuItem:
this.LayoutMdi(MdiLayout.TileHorizontal);
----------------------------------------------------------------------------
User Controls:
-These are components that are
developed or created by application developers to consume under their
applications.
-User Controls will be developed in 2
ways:
-Creating a new control from existing controls
-Inherited or extended controls
-In the first case we design a new
control making use of existing controls & then write the required behaviour
for control. To design the control first we need to define a class (because
every control is a class) inheriting from the predefined class UserControl
which provides a container required for designing.
public class <ControlName> :
UserControl
{
//Design the control
//Write the behaviour for control
}
-In the second case we don't design
any thing newly, we only copy the design of an exisiting control to add new
functionalities or behaviour that is required. In this case we define a class
that is inheriting from the control class for which new behaviour has to be
added.
public class NumericTextBox : TextBox
{
//write the code for accepting only numerics
}
-To create control in first process
we need to add UserControl ItemTemplate in the project which provides a class
that is inheriting from UserControl class, where as in the second case we need
to add Class ItemTemplate & then inherit the class from the control class
we want to extend.
Note: to develop user controls we are
provided with Windows Forms Control Library project template. The controls what
ever we develop are finally consumed from Windows Forms Application project
templates only.
-------------------------------------------------------------------------------------
People working on controls are
classified as:
1. Component Developers
2. Application Developers
-The person who develop controls are
known as component developers and those who consumes the controls are known as
application developers or component consumers.
-While developing controls the
developer should first design the control, write all the behaviour to control
and then define properties, methods and events that are required for the
control.
-Properties are defined to provide
access of any value in the control to application developer.
E.g.: Text property of TextBox,
Checked property of CheckBox etc.,
-Methods are defined so that any
actions can be performed thru the controls when ever required.
E.g.: Clear(), Focus() methods of
TextBox, Close() method of Form etc.,
Events:
-While developing a control the
developer of control may not know what actions has to be performed at some
specific time periods.
Eg:
1. The developer of button control is
not aware what should happen when end user clicks on the button.
2. What should happen when button is
clicked by end user will be decided by application developer.
3. Even if decided by application
developer it is the responsiblity of component developer to execute the code
that is written by application developer when ever end user clicks on the
button.
4. To resolve the above problem
component developer first defines an event under his control and then asks the
application developer to write code under an event procedure & bind it with
the event he has defined, so that when ever the event occurs or raises event
procedure gets executed.
5. To execute the event procedures,
events will internally take the help of delegates.
Syntax to define event:
[<modifiers>] event
<delegate> <Name>
Note: As we are aware that events
take help of delegates to execute event procedures, so while defining events we
must also specify that which delegate will be used by event to execute the
event proc. So first a delegate has to be defined and then the event has to be
defined.
E.g.:
public delegate void EventHandler(
object
sender, EventArgs e);
public event EventHandler Click;
-All delegate that are pre-defined in
BCL which we are consuming right now under existing controls are declared with
2 parameters:
1. object sender 2. EventArgs e
-That is the reason why all our event
proc's are also taking the same two parameters b'coz we are already aware that
IO params of delegate should be same as the IO params of method it has to call.
-While defining events to user
controls we can either make use of any pre-defined delegate or we can also
define our own delegates.
public event EventHandler MyClick;
//using predefined delegate
or
public delegate void
MyEventHandler();
public event MyEventHandler MyClick;
//using user-defined
delegate
-If we are defining delegates
explicitly they can be defined with or with out parameters also, so that
depending upon delegate declaration event proc's gets generated with or with
out parameters respectively.
Tasks of Component Developer &
App. Developer related to Events:
Component Developer Tasks:
1. Define a delegate (optional).
2. Define a event making use of a
delegate (either pre-defined or user-defined).
3. Specify the time period when the
event has to raise or occur.
Application Developer Tasks:
1. Define a event procedure.
2. Bind the event, delegate &
event procedure with each other.
Note: for a application developer the
above 2 tasks gets performed implicitly when he double click on the event in
property window.
-------------------------------------------------------------------------------------
Declarations:
//Defining a delegate for using it
under event:
public delegate void MyDelegate();
//Defining event making use of above
delegate:
public event MyDelegate MyClick;
int sec, min;
string secstr, minstr;
-------------------------------------------------------------------------------------
Under Timer Tick Event:
if (sec < 59)
sec += 1;
else
{
sec = 0;
min += 1;
}
if (sec < 10)
secstr = "0" + sec.ToString();
else
secstr = sec.ToString();
if (min < 10)
minstr = "0" + min.ToString();
else
minstr = min.ToString();
mtbTime.Text = minstr + secstr;
-------------------------------------------------------------------------------------
Under Start Button:
timer1.Start();
-------------------------------------------------------------------------------------
Under Stop Button:
timer1.Stop();
-------------------------------------------------------------------------------------
Under Reset Button:
timer1.Stop();
mtbTime.Text = "0000";
min = sec = 0;
-------------------------------------------------------------------------------------
Under Close Button:
//Raising the MyClick event we have
defined above
MyClick();
-------------------------------------------------------------------------------------
//Defining a property to access the
elapsed time
public string Time
{
get { return mtbTime.Text; }
}
-------------------------------------------------------------------------------------
//Defining a method to start the
StopClock
public void Start()
{
btnStart.Enabled = false;
btnStop.Enabled = false;
timer1.Start();
}
-Now open the solution explorer right
click on the project & select build which compiles the project and
generates an assembly as ControlsProject.dll
-------------------------------------------------------------------------------------
using System;
using System.Windows.Forms;
namespace ControlsProject
{
public class MyTextBox : TextBox
{
public enum Options {
Any,
Char, CharOrDigit, Digit };
Options opt = 0;
bool flag = false;
public bool AcceptDecimal
{
get { return flag; }
set { flag = value; }
}
public Options SetOption
{
get { return opt; }
set { opt = value; }
}
public MyTextBox()
{
this.KeyPress += new KeyPressEventHandler( MyTextBox_KeyPress);
}
private void MyTextBox_KeyPress(
object
sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 8)
return;
switch (opt)
{
case Options.Digit:
if (flag == true)
if (Convert.ToInt32(e.KeyChar) == 46)
return;
if (char.IsDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter numerics only");
e.Handled = true;
}
break;
case Options.Char:
if (char.IsLetter(e.KeyChar) == false && Convert.ToInt32(e.KeyChar) != 32)
{
MessageBox.Show("Enter alphabets only");
e.Handled = true;
}
break;
case Options.CharOrDigit:
if (char.IsLetterOrDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter alpha-numerics only");
e.Handled = true;
}
break;
}
}
}
}
-------------------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-Dock: It is a property available
under all the controls which decides the location where the control sits on the container as well as the
size of the control.
-It can be set with any of the
following values:
-None: In this case the size & location of the control will be same
as what we have specified while creating the control, that will not change in
the runtime.
-Left, Right, Top & Bottom: In this case the control get's placed on
any of the 4 choosen options with in the container and also adjusts itself
according to the size of the container.
-Fill: In this case the control
occupies the complete available space of the container.
-------------------------------------------------------------------------------------
MessageBox:
Show(string msg)
Show(string msg, string caption)
Show(string msg, string caption, MessageBoxButtons
buttons)
Show(string msg, string caption, MessageBoxButtons buttons,
MessageBoxIcon icon)
------------------------------------------------------------------------------------
Under New MenuItem:
if (richTextBox1.Text.Trim().Length
> 0)
{
DialogResult dr = MessageBox.Show(
"Do you wish to save the file?", "My Notepad", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
DialogResult d = saveFileDialog1.ShowDialog();
if (d != DialogResult.Cancel)
{
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
richTextBox1.Clear();
}
}
else if (dr == DialogResult.No)
richTextBox1.Clear();
}
-------------------------------------------------------------------------------------
Under Open MenuItem:
openFileDialog1.ShowDialog();
richTextBox1.LoadFile(openFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
-------------------------------------------------------------------------------------
Under Save MenuItem:
DialogResult d =
saveFileDialog1.ShowDialog();
if (d != DialogResult.Cancel)
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
-------------------------------------------------------------------------------------
Under Exit MenuItem:
this.Close();
-------------------------------------------------------------------------------------
Under Cut MenuItem:
richTextBox1.Cut();
-------------------------------------------------------------------------------------
Under Copy MenuItem:
richTextBox1.Copy();
-------------------------------------------------------------------------------------
Under Paste MenuItem:
richTextBox1.Paste();
-------------------------------------------------------------------------------------
Under Select All MenuItem:
richTextBox1.SelectAll();
-------------------------------------------------------------------------------------
Under WordWrap MenuItem:
if
(wordWrapToolStripMenuItem.Checked)
{
wordWrapToolStripMenuItem.Checked = false;
richTextBox1.WordWrap = false;
}
else
{
wordWrapToolStripMenuItem.Checked = true;
richTextBox1.WordWrap = true;
}
-------------------------------------------------------------------------------------
Under Font MenuItem:
fontDialog1.ShowDialog();
richTextBox1.Font = fontDialog1.Font;
-------------------------------------------------------------------------------------
Under Color MenuItem:
colorDialog1.ShowDialog();
richTextBox1.ForeColor =
colorDialog1.Color;
-------------------------------------------------------------------------------------
TreeView:
-It is a control used for
representing the data in hierarchial structure.
eg: Windows Explorer & Solution
Explorer.
-Every element under the control are
represented as nodes which can be either a parent or child.
-We can add nodes to the control in 2
ways:
i) Manually using Tree Node Editor.
ii) Programatically from Code Editor.
-To construct a tree manually go to
properties of it, select Nodes property & click on button beside it which
opens Tree Node Editor. Use "Add Root" & "Add Child"
buttons to add nodes in your required heirarchy.
-To assign a caption to the node make
use of Text Property of the node.
-Call ExpandAll() method which
displays nodes of the tree in expanded state.
-Default event of TreeView is
AfterSelect which fires when a node is selected under Tree. With-in the event
we can identify the node that has been selected using "e.Node"
property.
-Make use of Text property of the
node to get caption of node & make use of FullPath property to get
heirarchy of the node selected.
-Every Node under TreeView is
recognized by its index position from root node, as following:
CEO Nodes[0]
-President 1 Nodes[0].Nodes[0]
-Manager 1 Nodes[0].Nodes[0].Nodes[0]
-President 2 Nodes[0].Nodes[1]
-Manager 2 Nodes[0].Nodes[1].Nodes[0]
-Manager 3 Nodes[0].Nodes[1].Nodes[1]
-To construct a tree programatically
make use of the method Nodes.Add of TreeView.
TreeView:
Nodes.Add(string text)
-------------------------------------------------------------------------------------
Under Form Load:
treeView1.Nodes.Add("CEO");
treeView1.Nodes[0].Nodes.Add("Director1");
treeView1.Nodes[0].Nodes[0].Nodes.Add("Manager1");
treeView1.Nodes[0].Nodes.Add("Director2");
treeView1.Nodes[0].Nodes[1].Nodes.Add("Manager2");
treeView1.Nodes[0].Nodes[1].Nodes.Add("Manager3");
treeView1.ExpandAll();
-------------------------------------------------------------------------------------
List View: it is used for displaying
data in table format.
-To design a ListView first set View
property of it as details, which gets the look of a table.
-To Add columns for ListView use
Columns.Add method of it.
Columns.Add(string
name)
Columns.Add(string
name, int width)
-The first column of ListView is
represented as item & identified by its index position, to add an item use
Items.Add method of ListView.
Items.Add(string
text)
-From second column of ListView it is
represented as subitem & identified by its index position, to add a SubItem
under Item use SubItems.Add method of ListView referring to the Item under
which we want to add.
SubItems.Add(string
text)
Note: while identifying a record from
listview each cell can be referred as a subitem (first also) with their index
positions starting from 0.
-SelectedIndexChanged was the default
event of ListView which gets raised when a record is selected as well as
de-selected also.
-To get lines under ListView make use
of GridLines property by setting it as true.
-By default the FullRowSelect
property of ListView is disabled to enable set the property value as true.
Under Form Load:
listView1.Columns.Add("Custid",
200);
listView1.Columns.Add("Cname",
200);
listView1.Columns.Add("City",
200);
listView1.Columns.Add("Balance",
200);
listView1.Items.Add("101");
listView1.Items[0].SubItems.Add("Ajay");
listView1.Items[0].SubItems.Add("Hyderabad");
listView1.Items[0].SubItems.Add("10000");
listView1.Items.Add("102");
listView1.Items[1].SubItems.Add("Xyz");
listView1.Items[1].SubItems.Add("Chennai");
listView1.Items[1].SubItems.Add("14560");
<--Add
multiple records-->
-------------------------------------------------------------------------------------
Under SelectedIndexChanged:
if (listView1.SelectedItems.Count
> 0)
{
MessageBox.Show(listView1.SelectedItems[0].SubItems[0].Text);
MessageBox.Show(listView1.SelectedItems[0].SubItems[1].Text);
MessageBox.Show(listView1.SelectedItems[0].SubItems[2].Text);
MessageBox.Show(listView1.SelectedItems[0].SubItems[3].Text);
}
-------------------------------------------------------------------------------------
SplitContainer: it is container
control which contains 2 panels in it 1 in the LHS and 1 in the RHS, the sizes
of these panels can be adjusted in the runtime.
-------------------------------------------------------------------------------------
System.IO
Directory.GetDirectories(string path) string[]
Directory.GetFiles(string path) string[]
File.ReadAllBytes(string path) byte[]
File.GetLastWriteTime(string path) DateTime
String:
Substring(int start)
Substring(int start, int length)
-Substring method is used for picking
a part of a string from a given string.
string str = "Hello"
str.Substring(2) -> llo
str.Substring(0, 3) -> Hel
str.Substring(1, 3) -> ell
String:
IndexOf(string s)
IndexOf(string s, int start)
LastIndexOf(string s)
-IndexOf & LastIndexOf methods
are used for identifying the index position of a given string under the actual
string.
string str = "Hello World";
str.IndexOf("W") -> 6
str.IndexOf("o") -> 4
str.IndexOf("o", 5) -> 7
str.LastIndexOf("o") -> 7
System.Diagnostics
Process.Start(string <exename>)
-Start method under the Process class
is capable of running any given exe.
eg: Process.Start("calc.exe")
Process.Start("C:\\CSharp11\\MyForm.exe");
Control:
-Text and Tag are 2 properties under
a control which can be used for associating user defined info with any control
where Text is visible and Tag is not visible to the end user, but both can be
accessed by the programmers under the code.
-------------------------------------------------------------------------------------
using System.IO;
using System.Diagnostics;
-------------------------------------------------------------------------------------
Under Form Load:
treeView1.Nodes.Add("C:\\");
string[] dirs =
Directory.GetDirectories("C:");
foreach (string dir in dirs)
{
string dpath = dir;
string dname = dpath.Substring(2);
treeView1.Nodes[0].Nodes.Add(dname);
}
treeView1.ExpandAll();
listView1.Columns.Add("Name",
190);
listView1.Columns.Add("Size",
75);
listView1.Columns.Add("Type",
75);
listView1.Columns.Add("Date
Modified", 190);
-------------------------------------------------------------------------------------
Under TreeView AfterSelect:
try
{
listView1.Items.Clear();
string[] files =
Directory.GetFiles(e.Node.FullPath);
for (int i = 0; i < files.Length; i++)
{
string fpath = files[i];
string fname =
fpath.Substring(fpath.LastIndexOf("\\") + 1);
listView1.Items.Add(fname);
listView1.Items[i].Tag = fpath;
byte[] data = File.ReadAllBytes(fpath);
int size = data.Length / 1024;
size++;
listView1.Items[i].SubItems.Add(size + " kb");
listView1.Items[i].SubItems.Add("File");
DateTime dt = File.GetLastWriteTime(fpath);
listView1.Items[i].SubItems.Add(dt.ToString("g"));
}
}
catch (Exception ex)
{ ex = null; }
-------------------------------------------------------------------------------------
Note: while converting an DateTime
value into string we can use formatters under the ToString method which can be
either "D, d, T, t, G(d) or g".
-------------------------------------------------------------------------------------
Under ListView SelectedIndexChanged:
if (listView1.SelectedItems.Count
> 0)
Process.Start(
listView1.SelectedItems[0].Tag.ToString());
-------------------------------------------------------------------------------------
CheckBox & RadioButton: both
these controls are used so that the users can select from a list of available
values.
-CheckBox allows multiple selection
where as RadioButton allows only single selection with in a group of controls.
-While using RadioButtons under
multiple options we will be facing a problem i.e as it allows only single
selection at any point of time it will allow only single option to be selected,
to overcome this we need to group related radio buttons.
-To group the radio buttons they need
to be placed on seperate containers like either a panel or groupbox controls.
-Both these controls provides u a
boolean property known as Checked, which returns true if the controls is
selected or else returns false.
-------------------------------------------------------------------------------------
Under Button1:
if (radioButton1.Checked)
MessageBox.Show("Radio Button1 Selected");
else if (radioButton2.Checked)
MessageBox.Show("Radio Button2 Selected");
else if (radioButton3.Checked)
MessageBox.Show("Radio Button3 Selected");
-------------------------------------------------------------------------------------
Under Button2:
if (checkBox1.Checked)
MessageBox.Show("Check Box1 Selected");
if (checkBox2.Checked)
MessageBox.Show("Check Box2 Selected");
if (checkBox3.Checked)
MessageBox.Show("Check Box3 Selected");
-------------------------------------------------------------------------------------
ComboBox, ListBox, CheckedListBox:
-These controls are used when we want
the user to select form a list of available values.
-ComboBox allows only single
selection, where as ListBox and CheckedListBox provides multi selection.
-CheckedListBox is same as a ListBox
which displays a CheckBox beside each item to recognize the option that has
been selected.
-ComboBox is editable where as a
ListBox and CheckedListBox are not.
-To add values under the control we
have 4 different ways:
i) Using the Items Collection property under the property window, to do
this open property window corresponding to the control, select Items property
and click on the button beside it which opens u a "String Collection
Editor" window enter values under it, each in a new line.
ii) Using the Items.Add method we can add Items under the control 1 at a
time.
<control>.Items.Add(object
value)
iii) Using the Items.AddRange method we can
add an array of values at a time to the control.
<control>.Items.AddRange(object[]
values)
iv) Using the DataSource property of the control we can bind a db table
to the control, but we can display only a single column of table with in the
control which has to be specified using the display member property.
<control>.DataSource
= <data table>
<control>.DisplayMember
= <col name>
-A ListBox by default allows only
single selection if u want to go for multi selection we need to change the
"Selection Mode" property of the control either to "MultiSimple"
or "MultiExtended".
SelectionMode:
-One
(d)
-None
-MultiSimple
(only mouse click)
-MultiExtended
(ctrl + mouse click)
-To identify the Item(s) that has
been selected under the controls we can make use of the following properties:
SelectedItem ComboBox, ListBox
SelectedItems ListBox
CheckedItems CheckedListBox
Under Show Selected Country:
MessageBox.Show(comboBox1.SelectedItem.ToString());
-------------------------------------------------------------------------------------
Under Show Selected States:
foreach (object obj in
listBox1.SelectedItems)
MessageBox.Show(obj.ToString());
-------------------------------------------------------------------------------------
Under Show Selected Colors:
string str = "";
foreach (object obj in checkedListBox1.CheckedItems)
str += obj.ToString() + ",
";
str = str.Substring(0, str.Length -
2);
MessageBox.Show(str);
-------------------------------------------------------------------------------------
Class Declarations:
string[] q1 = { "January",
"February", "March" };
string[] q2 = { "April",
"May", "June" };
string[] q3 = { "July",
"August", "September" };
string[] q4 = {
"October","November", "December" };
-------------------------------------------------------------------------------------
Under ComboBox SelectedIndexChanged:
listBox2.Items.Clear();
switch (comboBox2.SelectedIndex)
{
case 0:
listBox2.Items.AddRange(q1);
break;
case 1:
listBox2.Items.AddRange(q2);
break;
case 2:
listBox2.Items.AddRange(q3);
break;
case 3:
listBox2.Items.AddRange(q4);
break;
}
-------------------------------------------------------------------------------------
Panel, GroupBox, TabControl:
-All these 3 are containers which can
be used for placing other controls over them.
-Panel and GroupBox are one and the
same where as a GroupBox has a caption but panel doesn't have.
-A TabControl is a collection of
pages which are arranged as pages in a book, where each page is referred as
TabPage.
-It provides links on top of the
control known as Tab's to go to the required page.
-By default it comes with 2 TabPages,
we can add a new page by right clicking on the control & select "Add
Tab" and delete by selecting "Remove Tab".
-This control is used in 2 situations
like placing of multiple controls on a form with out vertical or horizontal
scroll bars & grouping of related options by placing on seperate TabPages.
-------------------------------------------------------------------------------------
PictureBox: it is used for displaying
any image on the form.
-To load an image into the control we
can use any of the following Properties:
ImageLocation = "<path of the image>"
Image = Image.FromFile("<path of the image>")
-------------------------------------------------------------------------------------
ToolTip:
-It is used for associating a brief
information about any control when mouse is placed on the control.
Note: In classical VB & WPF (3.0)
tool tip was an property to every control, but in winforms it was a seperate
control again.
-SetToolTip is a method of the
control which can be used for binding ToopTip to any of the control on form
with a message.
SetToolTip(Control ctrl, string msg)
-------------------------------------------------------------------------------------
Under Form Load:
toolTip1.SetToolTip(button1, "Click Me");
-------------------------------------------------------------------------------------
Under Button Click:
openFileDialog1.ShowDialog();
pictureBox1.ImageLocation = openFileDialog1.FileName;
toolTip2.SetToolTip(pictureBox1, openFileDialog1.FileName);
-------------------------------------------------------------------------------------
ErrorProvider:
-It is a control used for displaying
error msgs under an application with out a message box.
-To use the control first it has to
be associated with a control for which the error has to be bound. To do this
use the method SetError & Clear to remove the binding with control to which
it was bound.
SetError(Control ctrl, string errormsg)
Clear()
-------------------------------------------------------------------------------------
Under TextBox Validating:
TextBox t = (TextBox)sender;
if (t.Text.Trim().Length == 0)
{
errorProvider1.SetError(t, "Cannot leave emtpy");
e.Cancel = true;
}
else
errorProvider1.Clear();
-------------------------------------------------------------------------------------
Under Login Button:
if (textBox1.Text.Trim() ==
"Admin" && textBox2.Text.Trim()
== "Admin")
MessageBox.Show("Valid User");
else
MessageBox.Show("Invalid User");
-------------------------------------------------------------------------------------
Under Cancel Button:
this.Close();
-------------------------------------------------------------------------------------
WebBrowser:
-It is used for displaying Html, Xml
pages and Images with in the windows applications.
-Navigate(string path): it opens the specified file under the
webbrowser.
-GoBack()
-GoForward()
-Stop()
-Refresh()
-GoHome()
-GoSearch()
-ToolStrip: it is a control used for
creating ToolBars on your form.
-A ToolBar is similar to that of a
MenuBar, where as ToolBar can be placed with various controls like Buttons,
Labels, TextBoxs, ComboBoxs, etc., on it.
-Every windows application has
toolbars to it which can be multiple. eg: Visual Studio.
-To create a Toolbar to your
application place a ToolStrip control on the form and then click on the LHS
corner of the control which displays u the list of controls that can be added
on it like Button, Label, TextBox etc.,
-A control placed on the ToolBar is
referred as a ToolStripControl i.e. ToolStripButton, ToolStripComboBox etc.,
-Once a Button is placed on the
ToolStrip it looks like a Image with a default image set to it, it has a
property DisplayStyle which can be used for changing the look of the control,
the property can be set with values like None, Text, Image (d), Image &
Text.
-To change the default image
associated with it right click on the button and select SetImage which opens u
a window click on the Import button and select an image from the harddisk.
-StatusStrip: It is a control which
can be used for displaying status messages on the windows form eg: Browser.
-On this control also u can place
controls similar to that of a toolstrip like StatusLabels, ComboBoxs,
DropDownButtons etc.,
-------------------------------------------------------------------------------------
Under Form Load:
toolStripComboBox1.Focus();
-------------------------------------------------------------------------------------
Under Go Button:
webBrowser1.Navigate(toolStripComboBox1.Text);
if(toolStripComboBox1.FindStringExact(toolStripComboBox1.Text)
== -1)
toolStripComboBox1.Items.Add(toolStripComboBox1.Text);
toolStripStatusLabel1.Text =
"Done";
-------------------------------------------------------------------------------------Under
ComboBox KeyPress:
if (Convert.ToInt32(e.KeyChar) == 13)
toolStripButton5.PerformClick();
Note: PerformClick is a method under
the button class which executes the code under the click on the button when
called.
-------------------------------------------------------------------------------------Under
ComboBox SelectedIndexChanged:
toolStripButton5.PerformClick();
-------------------------------------------------------------------------------------
Under Open MenuItem:
openFileDialog1.ShowDialog();
toolStripComboBox1.Text = openFileDialog1.FileName;
toolStripButton5.PerformClick();
-------------------------------------------------------------------------------------
Under Close MenuItem:
this.Close();
-------------------------------------------------------------------------------------
Under Back MenuItem:
webBrowser1.GoBack();
-------------------------------------------------------------------------------------
Under Forward MenuItem:
webBrowser1.GoForward();
-------------------------------------------------------------------------------------
Under Refresh MenuItem:
webBrowser1.Refresh();
-------------------------------------------------------------------------------------
Under Stop MenuItem:
webBrowser1.Stop();
-------------------------------------------------------------------------------------
User Controls:
-These are controls which were
designed by us according to the requirements for reusability.
-These are of 2 types:
-Controls created from scratch.
-Inherited or Extended controls.
-Controls created from scratch in the
sense here we are altogether going to design the control according our
requirements.
-Inherited control in the sense here
we are going to develop a new control by inheriting from an existing control
and then provide additional functionalities:
eg: public
class RichTextBox : TextBox
public
class MaskedTextBox : TextBox
-To develop user controls we are
provided with the project template "Windows Forms Control Library"
under which u can develop both type of controls.
-To develop a user control from
scratch we need to create a class inherting from the predefined class
UserControl of System.Windows.Forms namespace.
MaskedTextBox: It's a control which
can be used for taking the input from the user in some specific formats like
phone number, credit card no, railway pnr no etc.,
-To set a format to the control go to
the properties of the control and select the property mask and click on the
button beside it which opens u a "Input Mask Editor" under which u
can select from any available formats like US Phone Number, Date, Time etc or specify
your own format by selecting the custom option and enter your format in the
"Mask" Text Box below as following:
PNR Number: 000-0000000
Date & Time: 00/00/0000 00:00:00
Time: 00:00:00
-------------------------------------------------------------------------------------
Timer Control: It is a control which
can be used for executing the code regularly on specified intervals, i.e. the
code under a button executes only when the button is clicked where as the code
under the timer executes regularly once the specified time is elapsed once its
starts execution.
-The control provides u the following
properties, methods and events:
Interval: A property to specify the
elapsed time.
Tick: An event under which u need to
write the code that has to be executed.
Start: A method using which we start
the execution of the Timer.
Stop: A method using which we stop
the execution of the Timer.
D:\CSharp7\CSharp7Controls\CSharp7Controls\bin\Debug\CSharp7Controls.dll
-------------------------------------------------------------------------------------
Developing Controls:
-As we are already aware that every
control has Properties, Methods & Events. When we develop a control we can
also define them under our controls.
-When ever a control has some values
which should be accessible out side of the control class we need to go for
defining properties. eg: Text, Name etc.,
-Define Methods under the control
when u want to perform any actions with the control. eg: Clear(), Focus() etc.,
which were defined under the TextBox class.
-Define Events under the control when
u want to specify a time period to perform certain actions. eg: Click is a
event under the Button that performs an action when we press the button.
-How or When to define Events under a
control ? Ans. People working on controls were of 2 types:
-Component
Developer
-Component
Consumer
-Component Developer is the person
who designs the controls that can be reused.
eg: Microsoft, who designed Button,
Textbox, etc.,
-Component Consumer is one who uses
the control that has been developed by the developer.
eg: Software Development companies
(ourself).
-A Component developer while
developing a control never knows what action has to be performed when a Button
is pressed or a Form is opened etc.,
-The actions that has to be performed
when the Button is pressed or a Form is opened etc., has to be defined by the
Consumer only, but the responsiblity of executing the actions defined by the
consumer has to be taken by the Developer only.
-Because these 2 people will never
sit together towork at any point of time, they adopt a process to perform this
task, i.e. a Developer first defines Events and Delegates under his control
which is provided to the Consumer asking to write the code that has to be
executed under an EventProcedure mapping with the Event of control, so when
ever the Event raises the Delegate will take the responsiblity of executing the
code under the Procedure that is mapped with the event.
Syntax to define an event:
<modifiers> event
<delegate> <event name>;
public event EventHandler Click;
Note: while defining an event u need
to specify the name of the delegate which will execute the code.
-------------------------------------------------------------------------------------
Component Developer:
public class Button
{
public delegate void
EventHandler(object sender, EventArgs e);
public event EventHandler Click;
}
-------------------------------------------------------------------------------------
Component Consumer:
public class Form1 : Form
{
public Form1()
{
Button b = new Button();
b.Text = "Click Me";
b.Click += new EventHandler(Test);
this.Controls.Add(b);
}
private void Test(object sender, EventArgs e)
{
Console.WriteLine("Event Raised");
}
static void Main()
{
Application.Run(new Form1());
}
}
-------------------------------------------------------------------------------------
Note: After defining an event under
the controls the developer also needs to specify when this event has to be
raised.
-Passing parameters to a delegate is
optional, where as Microsoft followed a convention while defining delegates
i.e. every delegate takes 2 parameters "sender & e" so the
mapping event procedures should also take them.
-When we were defining a delegate if
no input params where specified the Event Procedure also doesn't require any
parameters.
-------------------------------------------------------------------------------------
Class Declarations:
//Defining a delegate to execute the Event
public delegate void MyEventHandler();
//Defining an event for the control
public event MyEventHandler MyClick;
int min = 0, sec = 0;
string minstr, secstr;
-------------------------------------------------------------------------------------
Under Load Event:
maskedTextBox1.Text = "0000";
-------------------------------------------------------------------------------------
Under Timer Tick Event:
if (sec < 59)
sec += 1;
else
{
sec = 0;
min += 1;
}
if (sec < 10)
secstr = "0" +
sec.ToString();
else
secstr = sec.ToString();
if (min < 10)
minstr = "0" + min.ToString();
else
minstr = min.ToString();
maskedTextBox1.Text = minstr + secstr;
-------------------------------------------------------------------------------------
Under Start Button:
timer1.Start();
-------------------------------------------------------------------------------------
Under Stop Button:
timer1.Stop();
-------------------------------------------------------------------------------------
Under Reset Button:
timer1.Stop();
min = sec = 0;
maskedTextBox1.Text = "0000";
-------------------------------------------------------------------------------------
//Defining a property to access the
stopclock's time
public string ShowTime
{
get { return maskedTextBox1.Text; }
}
-------------------------------------------------------------------------------------
//Defining a method to start the
StopClock
public void StartClock()
{
timer1.Start();
}
-------------------------------------------------------------------------------------
Under Close Button:
//Raising the MyClick event defined by us:
MyClick();
-------------------------------------------------------------------------------------
-Now open the solution explorer right
click on the project and select build which compiles the project and creates an
assembly under the following location:
C:\CSharp7\ControlsProject\ControlsProject\bin\Debug\
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
Under Form Load:
//Calling the method defined under StopClock
stopClock1.StartClock();
-------------------------------------------------------------------------------------
Under Button Click:
//Calling the property defined under StopClock
MessageBox.Show(stopClock1.GetTime);
-------------------------------------------------------------------------------------
Under stopClock1_MyClick:
MessageBox.Show("Event Raised");
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
using System;
using System.Windows.Forms;
namespace CSharp11Controls
{
public class MyTextBox : TextBox
{
public enum Options { Any, Chars, CharOrDigits, Digits }
Options opt = 0;
public Options SetOption
{
get { return opt; }
set { opt = value; }
}
public MyTextBox()
{
this.KeyPress += new
KeyPressEventHandler(MyTextBox_KeyPress);
}
private void MyTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Convert.ToInt32(e.KeyChar) == 8)
return;
switch (opt)
{
case Options.Digits:
if (char.IsDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter numerics only");
e.Handled = true;
}
break;
case Options.Chars:
if (char.IsLetter(e.KeyChar) == false)
{
MessageBox.Show("Enter characters only");
e.Handled = true;
}
break;
case Options.CharOrDigits:
if (char.IsLetterOrDigit(e.KeyChar) == false)
{
MessageBox.Show("Enter alphanumerics only");
e.Handled = true;
}
break;
}
}
}
}
No comments:
Post a Comment