Professional Documents
Culture Documents
VC#2012 Series 1
VC#2012 Series 1
VC#2012 Series 1
Introduction to
Visual C# 2012
Programming
(Series 1- Windows Forms Application)
Copernicus P. Pepito
Available at Nationwide!
2
Dedication
This book is excitedly dedicated to
Queenie lyn Lenterna Tautjo for being simply unbelievable!
3
Acknowledgement
I would like to express my heartfelt gratitude to Ms. Letty Custodio and Ms.
Mildred Villapando of National Bookstore - Purchasing Department whose tandem made
this book possible.
I am very thankful also to Madam Zeny Alulod of Cacho Hermanos Publishing,
for the heart-to-heart talks and to Ms. Lyn Francisco of National Bookstore – Accounting
Department whose inspiring words (based on biblical wisdom) can never be forgotten .
If there is someone who motivated me to be brave in expressing myself through
written-words, she was no other than my beloved grandmother, Dr. Roberta Pepito. Her
editing-style made me feel very confident about my English-grammar proficiency
(eventhough, I’m not good at it - honestly speaking).
Most of the time, my book was written behind an inspiration coming from a “girl-
next-door”. But in the case of Queenie lyn Lenterna Tautjo, she is a “girl-next-jungle”,
literally speaking! Well, probably this makes her unbelievable! Until now, I cannot
believed in my experience that I had to pass-through a small jungle before reaching the
house where she lived. And to think of it that she lived in a faraway place right there at the
top of the mountain, made me feel a little bit eerie. I am sure that if I say again that she was
beautiful, she won’t believe it (as she usually does). But who cares? The most important
thing is that I said what I feel. And you know what? It makes me happy.
Lastly, I give thanks to our Almighty God who unceasingly poured out a lot of
blessings to me, and whose plan to my life and the lives of my loveones I cannot
questioned, and who answered my questions about life, trials, and death through the books
written by His servants.
4
Preface
C# programming language is so very new, newer than Java. And yet, very
powerful and elegant. My learning experience with C# is purely coincidental. I learned it
not because I want to learn it (though, I plan to), but because I was assigned to teach
about it, to my students at Mapua IT Center – Makati campus. I was challenged to learn
it, most especially when one of my students came to me and said, “sir, how can you teach
us C# when in fact, you didn’t know about it?”. And I replied (with certainty), “well,
what I’ve heard that C# is a combination of C++, Java, and Visual Basic. Now, since I
already learned these three programming languages, it is easier for me to learn and adapt
C# .” I was absolutely right with that answer. Because eventually, I learned C# easily. I
told you this personal experience of mine to let you know that if you have a background
in C++, Java, or Visual Basic, you too can learn C# easily. So what can I say more?
Nothing, but to wish you all the luck in programming. Luck, afterall is something that
you attract when you work hard for things that you truly love. In short, we are the creator
of our own luck. Create your own luck now! God bless.
Copernicus P. Pepito
Member, *PSITE-NCR
Makati City, Metro Manila
Table of Contents
Dedication ii
Acknowledgement iii
Preface to the First Edition v
Preface of the Second Edition vi
About the Author vii
Chapter 1 Introduction 1
The Examples will Run also in Visual C# 2008 & 2010 1
A Brief History and Background of Visual C# 1
Different Version of Visual C#.Net 2
Common Elements of the Visual C# IDE 3
The Start Page 3
The New Project Dialog 3
Menu Bar 3
Toolbars 3
Toolbox 5
Solution Explorer 6
Properties Window 6
Output Window 6
Context Menus 6
Form Designer 7
Code Designer 7
Class View 7
The IntelliSense 8
Component Trays 8
Server Explorer 8
Program Conventions Used 8
Explaining Properties, Methods, and Events briefly 9
Event-Driven Programming 32
Object and Classes Defined 33
To Comment or Not to Comment 33
A Friendly Reminder for the Instructors 34
LAB ACTIVITY TEST 1 35
Chapter 1
Introduction
The Examples will Run also in Visual C# 2008 and Visual C# 2010
All the program examples in this book are coded using Microsoft Visual C# 2012 Express
Edition. However, the main reference books that I have used are based on Visual C# 2010.
With this reason, backward compatibility is not a problem. You can use either the new
Visual C# 2012 or the older versions which are Visual C# 2008 and 2010 releases. You
can use even the much more older Visual C# 2005 too.
All program examples in this book will run successfully on any editions of Visual Studio
whether you are using Express Edition, Professional Edition, Premium Edition, or Ultimate
Edition.
1 2 3 4
Figure 1.1 Visual Studio Integrated Development Environment (IDE) Start Page
5 6
Here are the meaning of the arrows and legends that we point to:
1 - ToolBox
2 - ToolBar
3 – Menu Bar (Menu System)
4 - Solution Explorer
5 –Output Window
6 –Properties Window
12
Note:
The Recent Projects are simply the list of recent projects that we have designed and developed. There is no
other special meaning about them.
Menu Bar
The menu bar (menu system) is actually like the menus we have seen in other
Windows application software such as MS Word, MS Excel, and PowerPoint. It is the
line of text that lies across the top of the Visual C# window. This menu will give us
access to many features within the integrated development environment (IDE). Some of
the menu items that we can see at the Menu bar are File, Edit, View, Tools and more.
In the File menu, we will work with the actual files that make our application system.
Here we can open or save the projects or programs that we have created.
In the Edit menu, we can perform the standard Clipboard options such as cut, copy, and
paste. In the View menu, we can view various component and tools. We can view the
Class View, Error List, and Output, Properties Window as well as other utilities that help
make our program development time more productive, easy, and fast.
Toolbars
Below the menu bar are list of icons which are called toolbars. They provide us a
quick access to commonly used menu items (as an alternate way to search for a
command), we simply click an icon (which is an equivalent to that menu-bar command
we need, and presto, it serves our wishes. Plus, we can dock this list of icons beneath the
menu bar or above it, or dock it sideways.
13
Toolbox
The toolbox contains the tools or objects (controls) that we might want to place
(drag and drop) on a Form control in our application system on which we presently
design and develop. An example of these objects are Buttons control and Text boxes
control.
Solution Explorer
The Solution Explorer tracks the item in our projects. If we want to add new items
on our project, we simply use the menu items in our Project menu, such as Add Windows
Form. Furthermore, the Solution Explorer sees things in terms of files or folders. Like
for example, the References folder holds the currently referenced items such as
namespaces in a project. Now if we want to set the properties of the various items in our
project, we will simply click the Properties folder.
Properties Window
The properties window is docked right under the Solution Explorer window. It
provides us the lists of the property settings from the currently selected form or other
control objects. A property in Object-Oriented Programming (OOP) term is a
characteristic of an object such as its size, caption, or color. The characteristic is not
limited to the appearance of an object (control) but also about the way it behaves.
Output Window
The Output Window echoes the result when we build and run our programs. This
is where the debugging results occur. On this Output Window, we can see the list of
errors our program generated.
Context Menus
Form Designer
The form designer is our drawing board where we design graphically the layout of
the form and controls of our application system. In short, this is where we draw our
graphical-user interface (GUI). Here we can add controls, pictures, or other graphics to a
form to design the look we want. We have all the powers to make our GUI to look funny
or elegant in the eyes of the beholder (our target users). Imagine how powerful we are? It
doesn’t take a professional artist to do that; but a clear mind and a heart with a good taste
of beauty as an art.
There are four common Graphical Designers we usually used in C# programming.
They are Windows Form Designer, Web Form Designer, Component Designer and XML
designer.
Code Designer
The code designer window serves as a program editor where we can write our
program (code) behind each form and control (object) we design or where we can place
the code module we develop in our application system. We can use the tabs at the top
center of the IDE to switch between the Form Designer such as the Form1.cs [Design]
and the Code designer such as Form1.cs.
Note:
The .cs of the Form1 means c sharp.
Class View
The Class View window which is located next to the Solution Explorer, is
actually another tab that sits beside the Solution Explorer, presents solutions and projects
in terms of the classes they contain, and the members of these classes. Furthermore, the
class view window provides us an easy way of jumping to a member of the class that we
want to access quickly. We simply find it in the Class View window, and double-click it
to bring it up in the code designer.
The IntelliSense
The IntelliSense is a box that pops-up as we write the code into our Code
Designer, and lists all possible options and even completing our typing of code for us.
15
This is useful when we cannot remember what built-in Visual C# method accepts,
because it will display those arguments as we type in the call to that method.
Moreover, the IntelliSense offers syntax tips which display the syntax of the statement we
are typing. This is great, if we know what statement we have to apply but cannot recall
its exact syntax.
Component Trays
The Component Trays are one of the most useful components of Visual C# IDE,
most especially when our application system requires us to put a timer, a menustrip, a
toolstrip, or contextmenustrip in our program. These Timer, MenuStrip, ToolStrip,
ContextMenuStrip and ToolTips controls will appear in the component tray which we can
see at the bottom part of our Form during the time we design our program.
Server Explorer
The Server Explorer is very useful when we want to connect our database to our
code and bind it to the Controls we design at the Form. Like for example, if we drag a
database table onto the Form, Visual C# would create the connection and command
objects that we need to access that table from our code.
As we ended our discussion with the common elements of Visual C#, I am pretty sure,
that this time on, you already gained a basic idea of what the IDE is all about. Am I
wrong or not?
Let us now go to the program conventions we used in this book. Here they are!
Here in this book, the code to be embedded in the procedure are written in bold
letters. For example:
private void button1_Click(object sender, EventArgs e)
{
this.textBox1.Text = "Hello World!";
}
In short, the statements you are instructed to type or to embed within the method
appears in bold letters. In most situations, the statements which are not in bold letters are
compiler system-generated code, so there is no need to type them. In the above example,
they are:
Tip:
The caption refers to the Text property of a particular control.
Warning!
The Sample Output may differ from the given Figure in our example. The author is trying his very best to
provide you with the exact sample output. However, due to time constraints, the output is but just nearer to
the given figure.
Tip:
A method is simply a function that is a member of a class. In structured programming era, a function is a
subprogram that performs a specific task. Function is also commonly called a subroutine.
Tip:
During the high time of Pascal programming language (it earns the title of being the structured
programming flagship), there is another type of subprogram that looks and acts almost like a function. It is
called procedure. A procedure is a type of subprogram that performs a specific task, and after doing the
task, it returns no value. The Pascal creator argues that this is how procedure differs from a function,
because a function will always return a value. It could be a valuable value returned, or in other case it
returned a null value (in case of no value to return to). The declaration of a function that returns no value
will always contain a void keyword.
17
Chapter 2
Designing Basic Controls or Objects
Controls or objects are the primary medium of the user’s interaction with the application
system on which we design and develop. Mostly, we use controls to get the user input
and to display the corresponding output. The other controls provide us an access to some
application system and process data or information as though the remote application
system is part of our program. The basic controls that we can use in our application
system are buttons, text box, label, check boxes, radio buttons, list box, and combo box.
By clicking or typing something on these controls, the user can accomplish their tasks.
The function of a Button is to carry out a command or action (event) as the user
clicks it, while the text box provides an area to input or display text. We can use the
Button to extract simple responses from the user or to invoke special functions on the
form. The text boxes are commonly used to display string or numeric data and to accept
user input or for entering data.
Example 1:
Design and develop an application system that when the user clicks the Greet Now!
button, the message “Hello World!” will be displayed at the text box. Follow the given
figure below in designing and developing the application system.
18
vbButton1
Greet Now!
Button
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csButton1. Now click the OK button.
4. Set the Form’s Text property to vbButton1.
5. Click, drag and drop a text box from the Toolbox to add it to the form. Position it
properly and adjust its width appropriately. Next, click, drag and drop a button
from the Toolbox to add it into the Form, then set its Text property to Greet
Now!
6. Double-click the button on the Form to display the button1_Click event method.
Embed the following lines (in bold only) into the method:
7. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Tip:
You can also use Microsoft Windows 7, instead of Windows 8 as your operating system when developing
all the programs or examples here in this book. It just work fine in either of these two operating system.
Sample Output:
19
Note:
The this keyword refers to the current instance of the class. It is also used as a modifier of the first
parameter of an extension method. Moreover, the application of this keyword is useful when you want to
qualify members hidden by similar names.
Explanation:
We usually use the button to get simple responses from the user such as clicking it to do
some action. We will notice here that the embedded code (within the method):
is simply changing the Text property of the object named textBox1 to display “Hello
World!” at the Text box control. Text box is commonly used for accepting input or for
entering data, but in this example, it is used to display the data. In the next chapter, we
will use text boxes for accepting input data. As of the moment, we will focus on how to
output the data on the text box control. The syntax for our example takes the format of
object.property
where textBox1 is the object (control) and Text is the property. We can use this syntax to
change property settings for any form or control in response to events that occurs while
our application system is running. The specific event here is a click event (generated by
clicking the button).
20
Example 2:
Design and develop an application system that when the user clicks the Greet Now!
button, the message “Hello World!” will be displayed at the message box. Follow the
given figure below in designing and developing the application system.
vbButton2
Hello World!
OK
Figure 2.2 Button and Message box design
Message Box
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csButton2. Now click the OK button.
4. Set the Form’s Text property to vbButton2.
5. Click, drag and drop a button from the Toolbox to add it into the Form, then set
its Text property to Greet Now!
6. Double-click the button on the Form to display the button1_Click event method.
Embed the following lines (in bold only) into the method:
7. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
21
Explanation:
We usually use the button to get simple responses from the user such as clicking it to do
some action . We will notice here that the embedded code (within the method):
MessageBox.Show("Hello World!");
is simply to display the message “Hello World!” at the Message box control.
A message box is used for displaying simple messages to the user.
Example 3:
Design and develop a simple Check box and Text box application that when the user
clicks one of the three check boxes, it will indicate in the text box on which check box
the user had clicked. For example if Check box 2 was clicked by the user, it will display
“Check box 2 is clicked!” at the text box. It will do the same with Check box 1 and
Check box 3. Follow the given figure below in designing and developing the application
system.
vbCheckBox1
CheckBox 1
CheckBox 2
CheckBox 3
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csCheckBox1. Now click the OK button.
4. Set the Form’s Text property to vbCheckBox1.
5. Click, drag and drop three (3) Check boxes from the Toolbox to add them into the
Form, then set their respective Text property to Check 1, Check 2, and Check 3!
Finally, click, drag and drop a Text box from the Toolbox to add it into the Form.
6. Double-click the Check Box 1 on the Form to display the
checkBox1_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
this.textBox1.Text = "Check box 1 clicked!";
}
23
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Note:
In running the application program, you can click the Start debugging icon on the Toolbar or you can
simply press F5.
24
Explanation:
Although a check box control is rather similar to a radio button which we will describe in
the upcoming examples, there are two fundamental differences between them. You can
select many choices in check boxes, while in radio button you are only allowed to select
one option at a time. You can observe that when you click the check box 1 (Check 1)
then you click the check box two (Check 2), these two check boxes have the check mark
on both of them. And even when you click the check box three (Check 3), it will also
contain the check mark. In radio button, this will not be the case, only one radio button
will contain the bullet or the big dot at a time, because once you click the next radio
button, the next radio button will contain the bullet as though it transfers from the
previous radio button.
In this example, we will notice here that the embedded code (within the method)
is simply changing the Text property of the object named textBox1 to display “Check
box 1 is clicked!” at the Text box control. The same thing happen to other check boxes if
we click them. The syntax for our example takes the format of object.property, where
textBox1 is the object (control) and Text is the property. We can use this syntax to change
property settings for any form or control in response to events that occurs while our
application system is running. The specific event here is the click event which is
generated by clicking the check boxes.
Example 4:
Design and develop a simple Check box and Message box application that when the user
clicks one of the three check boxes, it will indicate in the Message box on which check
box the user had clicked. For example if Check box 2 was clicked by the user, it will
display “Check box 2 is clicked!” at the Message box. It will do the same with Check box
1 and Check box 3. Follow the given figure below in designing and developing the
application system.
vbCheckBox2
CheckBox 1
CheckBox 2
CheckBox 3
Project1
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csCheckBox2. Now click the OK button.
4. Set the Form’s Text property to vbCheckBox2.
5. Click, drag and drop three (3) Check boxes from the Toolbox to add them into the
Form, then set their respective Text property to Check 1, Check 2, and Check 3!
6. Double-click the Check Box 1 on the Form to display the
checkBox1_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
26
Explanation:
is simply to display the message “Check box 1 is clicked!” at the Message box control.
The same thing happened to other check boxes if we click them. The Message box
control is a pop-up dialog box that displays the message that we would like to convey to
the user.
Example 5:
Design and develop a simple Text box and Radio buttons application that when the user
clicks one of the three radio buttons, it will indicate in the Text box on which radio button
the user had clicked. For example, if radio button 2 was clicked by the user, it will
display “Radio button 2 is clicked!” at the Text box. It will do the same with Radio
button 1 and Radio button 3. Follow the given figure below in designing and developing
the application system.
27
vbRadiobutton1
Radio 1
Radio 2
Radio 3
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csRadioButton1. Now click the OK button.
4. Set the Form’s Text property to vbRadioButton1.
5. Click, drag and drop three (3) Radio buttons from the Toolbox to add them into
the Form, then set their respective Text property to Radio 1, Radio 2, and Radio
3! Finally, click, drag and drop a Text box from the Toolbox to add it into the
Form.
6. Double-click the Radio 1 on the Form to display the
radioButton1_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
Now you will see the effect of using the radio button. As I have said, you can only
select one option at a time. Once you click the next radio button, the bullet or the
big black dot will transfer from the previous button to the currently clicked radio
button.
We will notice here that the embedded code (within the method):
is simply changing the Text property of the object named textBox1 to display
“Radio button 1 clicked!” at the Text box control. The same thing happened to
other radio buttons if we click them. The syntax for our example takes the format
of object.property, where textBox1 is the object (control) and Text is the property.
We can use this syntax to change property settings for any form or control in
29
response to events that occur while our application system is running. The
specific event here is the click event which is generated by clicking the radio
buttons.
Example 6:
Design and develop a simple Message box and Radio buttons application that when the
user clicks one of the three radio buttons, it will indicate in the Message box on which
radio button the user had clicked. For example if radio button 2 was clicked by the user, it
will display “Radio button 2 is clicked!” at the Message box. It will do the same with
Radio button 1 and Radio button 3. Follow the given figure below in designing and
developing the application system.
vbRadiobutton2
Radio 1
Radio 2
Project1
Radio 3
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csRadioButton2. Now click the OK button.
4. Set the Form’s Text property to vbRadioButton2.
5. Click, drag and drop three (3) Radio buttons from the Toolbox to add them into
the Form, then set their respective Text property to Radio 1, Radio 2, and Radio
3!
6. Double-click the Radio 1 on the Form to display the
radioButton1_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
30
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
31
Explanation:
You will noticed that the Radio button 1 is by default, the first control to be selected.
It’s because in Radio button controls, one of its control object must be selected, and only
one of the controls must be selected exclusively. Unlike in Check boxes control, two or
more check boxes can be selected simultaneously.
A message box is used for displaying simple messages to the user. We will notice here
that the embedded code (within the method):
if (radioButton1.Checked)
MessageBox.Show("Radio button 1 clicked!");
is simply to display the message “Radio button 1 clicked!” at the Message box control.
The same thing happened to other radio buttons if we click them. The Message box
control is a pop-up dialog box that displays the message that we would like to convey to
the user.
The most noticeable part in our code is that we put the MessageBox method under the if
conditional statement. This is due primarily to the fact that we have to check first if a
particular radio button is being checked (selected), and if it is, we have to trigger the
MessageBox to show the message. The MessageBox method needs to be triggered to
display or show something, if we are using a radio button control, since this control has to
be pre-selected first, as its default selection.
You can experiment based on this example, what would be the effect if you wouldn’t
apply the if conditional statement. You will see why we really need to put the conditional
statement, after the experimentation. Because I am pretty sure, there is a side-effect that
would come up with your simple solution.
Example 7:
Design and develop a simple Text box and Radio buttons application that when the user
clicks one of the four radio buttons, it will indicate in the Text box on which radio button
the user had clicked. For example if radio button 2 (Second Year) was clicked by the
user, it will display “Sophomore!” at the Text box. It will do the same with Radio button
1, Radio button 3, and Radio button 4. The high school level of First Year is
“Freshman”, for Second Year is “Sophomore”, for Third Year is “Junior” while for
Fourth Year is “Senior”. Follow the given figure below in designing and developing the
application system.
32
vbHighschool2
First Year
Second Year
Third Year
Fourth Year
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csHighSchool2. Now click the OK button.
4. Set the Form’s Text property to vbHighSchool2.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to High School Level:.
6. Click, drag and drop four (4) Radio buttons from the Toolbox to add them into the
Form, then set their respective Text property to First Year, Second Year, Third
Year, and Fourth Year.
7. Finally, click, drag and drop a Text box from the Toolbox to add it into the Form.
8. Double-click the First Year radio button on the Form to display the
radioButton1_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
9. Double-click the Second Year radio button on the Form to display the
radioButton2_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void radioButton2_CheckedChanged(object sender, EventArgs e)
33
{
textBox1.Text = "Sophomore!";
}
10. Double-click the Third Year radio button on the Form to display the
radioButton3_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "Junior!";
}
11. Double-click the Fourth Year radio button on the Form to display the
radioButton4_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "Senior!";
}
12. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
Now you will see the effect of using the radio button. As I have said, you can only
select one option at a time. Once you click the next radio button, the bullet or the
big black dot will transfer from the previous button to the currently clicked radio
button.
We will notice here that the embedded code (within the method):
this.textBox1.Text = "Freshman!";
is simply changing the Text property of the object named textBox1 to display
“Freshman!” at the Text box control. The same thing happened to other radio
buttons if we click them. The syntax for our example takes the format of
object.property, where textBox1 is the object (control) and Text is the property.
We can use this syntax to change property settings for any form or control in
response to events that occur while our application system is running. The
specific event here is the click event which is generated by clicking the radio
buttons.
You will notice in our example, that there will always be a default selection in
Radio button control. And that default selection is the Radio button 1 (in this
example, it is the First Year radio button). This is how Radio button is specifically
designed.
Objectname.Enabled = false;
Or
Objectname.Visible = false;
Note:
When we talk about design time it means that we are modifying our program as we design it on
the Form where we can set the Control’s property through the Property Window. In other words,
as we design the controls on our Form while we invoke the Form Designer. Now, how about run-
time? Run-time refers to the coding we do that sets the property of a particular Control right on
our program. In other words, as we open (invoke) the Code Designer, we hard-coded the setting of
properties.
35
Example 8:
Design and develop an application system that disables or enables a Button, and displays
its feedback to the Textbox. When the user clicks the Try to Click Me! Button, the
feedback that says “Yes! I was Enabled ! Thank you!” should be displayed at the Text
box. Now when the user clicks the Disable Button! Radio button, the Button control
should be disabled (grayed), and the feedback that says “You Disabled the Button!” is
displayed at the Text box. Plus, the Try to Click Me! Button is unclickable. Now when
the user clicks the Enable Button! Radio button, the Try to Click Me! Button should be
restored to its enabled state, and the feedback that says “You Enabled the Button!” should
be displayed at the Text box. Follow the given figure below in designing and developing
the application system.
vbDisableControl1
Text box
Radio buttons
Enable Button! Disable Button!
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csDisableControl1. Now click the OK button.
4. Set the Form’s Text property to vbDisableControl1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Try to Click Me!.
6. Click, drag and drop a Text box from the Toolbox to add it into the Form.
7. Click, drag and drop two (2) Radio buttons from the Toolbox to add them into the
Form, then set their respective Text property to Enable Button!, and Disable
Button!.
36
8. Double-click the Try to Click Me! Button on the Form to display the
button1_Click event method. Embed the following lines (in bold only) to the
method:
9. Double-click the Enable Button! radio button on the Form to display the
radioButton1_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
10. Double-click the Disable Button! radio button on the Form to display the
radioButton2_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
button1.Enabled = false;
textBox1.Text = "You Disabled the Button!";
}
11. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
37
Explanation:
We can see here in the example above how easy it was to enable or disable a control. We
just simply set a particular control’s Enabled property to true (for enabling) and false (for
disabling) it. Take for example, when the user clicks the Enable radio button
(radioButton1), we enabled it through the following code:
Now, when the user clicks the Disable radio button (radioButton2), we disabled it
through the following code:
Yes buddy, as simple as this code. It is very easy isn’t it? Okay, let us now go to how to
hide or show a control in the succedding example.
38
Example 9:
Design and develop an application system that shows or hides Radio button 1. Follow the
given figure below in designing and developing the application system.
vbShowHideControl1
radioButton1
radioButton2
radioButton3
radioButton4
Buttons
Figure 2.9 Showing and Hiding Controls
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csShowHideControl1. Now click the OK
button.
4. Set the Form’s Text property to vbShowHideControl1.
5. Click, drag and drop four (4) Radio buttons from the Toolbox to add them into the
Form.
6. Click, drag and drop two (2) Buttons from the Toolbox to add them to the Form,
then set their respective Text property to Hide Radio1!, and Show Radio1!.
7. Double-click the Hide Radio1! Button on the Form to display the button1_Click
event method. Embed the following lines (in bold only) to the method:
private void button1_Click(object sender, EventArgs e)
{
radioButton1.Visible = false;
}
39
8. Double-click the Show Radio1! Button on the Form to display the button2_Click
event method. Embed the following lines (in bold only) to the method:
private void button2_Click(object sender, EventArgs e)
{
radioButton1.Visible = true;
}
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
We can see here in the example above how easy it was to hide or show a control. We just
simply set a particular control’s Visible property to true (for showing) and false (for
hiding) it. Take for example, when the user clicks the Hide radio button (radioButton1),
we hide it through the following code:
Now, when the user clicks the Show radio button (radioButton2), we showed it through
the following code:
You could notice that the preceding codes are similar to the enabling and disabling a
particular control which was demonstrated in our previous example.
Example 10:
Design and develop a simple Text box and Radio buttons application that when the user
clicks one of the four radio buttons, it will indicate in the Text box on which radio button
the user had clicked. For example if radio button 2 (Second Year) was clicked by the
user, it will display “Sophomore!” at the Text box. It will do the same with Radio button
1, Radio button 3, and Radio button 4. The high school level of First Year is
“Freshman”, for Second Year is “Sophomore”, for Third Year is “Junior” while for
Fourth Year is “Senior”. Follow the given figure below in designing and developing the
application system.
41
Now, your implementation will differ from csHighSchool1, because here we have to
display the list of Radio buttons as empty (unselected). Then we add two Buttons that
can enable the Radio button 1 to reappear or to hide again.
Follow the given figure below in designing and developing the application system:
vbHighschool3
Tricky Presentations!
Radio button 1 is intentionally, hidden.
radioButton1
First Year
Second Year
Third Year
Fourth Year
Text box
Sophomore!
Buttons
Figure 2.10 Hiding some controls to trick up the application
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csHighSchool3. Now click the OK button.
4. Set the Form’s Text property to vbHighSchool3.
5. Click, drag and drop five (5) Radio buttons from the Toolbox to add them into the
Form, then set their respective Text property to First Year for the second radio
button, Second Year for the third radio button, Third Year for the fourth radio
button, and Fourth Year for the fifth radio button. We just leave Radio button 1
with its default caption.
6. Click, drag and drop a Text box from the Toolbox to add it into the Form.
7. Click, drag and drop two (2) Buttons from the Toolbox to add them into the Form,
then set their respective Text property to Show Radio1!, and Hide Radio1!.
8. Finally, click, drag and drop a Text box from the Toolbox to add it into the Form.
42
9. Double-click now the Form to display the Form1_Load event method. Embed the
following lines (in bold only) to the method:
11. Double-click the First Year Radio button on the Form to display the
radioButton2_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
12. Double-click the Second Year Radio button on the Form to display the
radioButton3_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "Sophomore!";
}
13. Double-click the Third Year Radio button on the Form to display the
radioButton3_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "Junior!";
}
14. Double-click the Fourth Year Radio button on the Form to display the
radioButton3_CheckedChanged event method. Embed the following lines (in bold
only) to the method:
private void radioButton5_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "Senior!";
43
15. Double-click the Show Radio1! Button on the Form to display the button1_Click
event method. Embed the following lines (in bold only) to the method:
private void button1_Click(object sender, EventArgs e)
{
radioButton1.Visible = true;
textBox1.Text = "I just hide for a purpose!";
}
16. Double-click the Hide Radio1! Button on the Form to display the button2_Click
event method. Embed the following lines (in bold only) to the method:
private void button2_Click(object sender, EventArgs e)
{
radioButton1.Visible = false;
textBox1.Text = "";
}
17. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
The first time we run our application system, we need to hide right away the first radio
button so that it won’t appear. This is the trick that we are doing to our control, so that it
appears as though there is no pre-selection happened in our radio buttons control. We
already know that in radio buttons control, there is always a pre-selection of radio button.
And it is always the first radio button to be selected by default.
To hide the first button from appearing and selected when we run our application
program, we need to set the code this way:
In the code above, the Visible property of radio button 1 (radioButton1) is set to false to
hide the control, while its Checked property is set to true so that the selection will always
be at radio button 1. This is the main reason why the remaining radio buttons are empty
(or no selection appears).
Once the Button 1 (Show radio 1) is clicked by the user, we have to empty the text box
from any text message on it. We did it through the following code:
The code above will ensure that when the user had already selected other radio buttons
such as the radio button 2, radio button 3, and others, the displayed text message as the
result of the following selections will be erased from the text box, once the user clicks the
Button 1 (Show Radio 1).
When the user clicks the Button2 (Hide Radio 1), we have to hide the radio button 1 with
the following code:
And at the same time, we have to empty the text box, so that the user is free again to
select any of the radio buttons presented and will display the corresponding output text
for the respected selection. For example, when the user clicks the First Year radio button,
the output text:
"Freshman!"
45
will be displayed at the text box. We did it by using the following code:
This will also produce the same effect to other remaining selections of radio buttons.
Example 11:
Design and develop an application system that when the user points the mouse-pointer at
any control on the Form, it will display the tooltip of what kind of control it is pointing
to. Follow the given figure below in designing and developing the application system.
vbToolTip1
label2
button1
checkBox1
radioButton1
Note:
When the user points his or her mouse on the Form, the tooltip should be, “This is a
Form!”, now if the user points the mouse on the Label1, the tooltip should be, “This is a
Label!”. Now apply the same respective tooltip to other controls, too.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csToolTip1. Now click the OK button.
46
7. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
See, it is easy to program a simple ToolTip application, isn’t it? Here, in this code below:
47
the this of the ToolTip1.SetToolTip object and method parameter means the Form control.
The other tooltips parameters are self-explanatory. Agree?
Example 12:
Design and develop an application system that will echo the message typed at the Text
box to the Label with bigger font size. Follow the given figure below in designing and
developing the application system.
vbEcho1
Text box
label 2
vbEcho1
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csEcho1. Now click the OK button.
4. Set the Form’s Text property to vbEcho1.
5. Click, drag and drop a Label from the Toolbox, then set its Text property as
Enter a message to echo:.
6. Click, drag and drop a text box from the Toolbox to add it into the form. Position
it properly and adjust its width appropriately.
7. Next, click, drag and drop another Label from the Toolbox, then set its Font size
property to 16.
8. This time, double-click the Text box to display the TextBox1_TextChanged event
method. Embed the following lines (in bold only) into the method:
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
49
Explanation:
Echoing a message typed at the text box control is very simple and easy. We just simply
used the textBox1 control method and its Text property respectively, to be stored at
Label2.Text control. With this, we can echo the message we typed at text box into the
label control. We can accomplish this task by the following code:
Event-Driven Programming
In the preceding examples above, we learned how event-driven application
system works. An event is an action recognized by a control or form. An event-driven
application system executes Visual C# program in response to an event. For example, if
the user clicks a button (a check box, or radio button), the button’s Click event method is
executed. When we want a control such as a button or check box to respond to an event,
we write a program in the event method for that event. As though we are writing a small
program behind it, which is really the case.
50
Object is simply a combination of program and data that can be treated as a unit.
Like for example, a Form or a Button is an object. Inside (or behind) a button is a
program and data which we can use to manipulate itself. Its data such as the caption (text
property), size, or color can be modified to suit our needs. Now if we want to click it to
perform a particular task, we need its Click program to accomplish the task. These
program and data are encapsulated within an object, thus eliminates conflict to other code
in other object or module. Classes are the blueprint or template of an object. It is just like
saying, “If a floor is an object, then its floor-plan is the class. Without the
floor-plan, the floor can be impossibly built reliably and accurately. The same goes to an
object, without the class, it is impossible to create it successfully and elegantly.
The object in Visual C# is defined by a class. A class defines the characteristics of an
object - for instance, its size and shape. The class is used to create an object. The controls
which are also called objects in the Toolbox represent classes. When we design a control
(object) onto the form such as clicking, dragging, and dropping a button or text box, we
are really creating a copy or an instance of the control class. In this case the control class
is the button class or text box class. All objects (controls) are created as identical copies
of their respective classes.
LAB ACTIVITY
TEST 1
1. Design and develop an application system that when the user clicks the Button 1, the
message “Button 1 clicked!” will be displayed at the Text box. When the user clicks the
Button 2, the message “Button 2 clicked!” will be displayed at the Text box, and “Button
3 clicked!” will be displayed when the user clicks the Button 3. Follow the given figure
below in designing and developing the application system.
csButton2
2. Design and develop an application system that when the user clicks the Button 1,
the message “Button 1 clicked!” will be displayed at the Text box 1. When the
user clicks the Button 2, the message “Button 2 clicked!” will be displayed at the
Text box 2. Follow the given figure below in designing and developing the
application system.
csButton3
Text box
Button 1 clicked!
Button
Command1
Text box
Button 2 clicked!
Command2 Button
3. Design and develop an application system that when the user clicks the Button 1, the
message “Button 1 clicked!” will be displayed at the Text box 1. When the user clicks the
Button 2, the message “Button 2 clicked!” will be displayed at the Text box 2, and
“Button 3 clicked!” will be displayed at Text box 3 when the user clicks the Button 3.
Follow the given figure below in designing and developing the application system.
53
csButton3
4. Design and develop an application system that when the user clicks the Button with
the caption “Submit”, the message “Submit button 1 clicked!” will be displayed at the
Message box . Follow the given figure below in designing and developing the application
system.
csButton6
Submit
Message box
Button
Message box
5.Design and develop an application system that when the user clicks the Button 1, the
message “Button 1 clicked!” will be displayed at the Message box. When the user clicks
the Button 2, the message “Button 2 clicked!” will be displayed at the Message box.
Follow the given figure below in designing and developing the application system.
54
csButton7
Button1 Button2
Message box
Button 1 clicked!
6.Design and develop an application system that when the user clicks the Check box 1,
the message “Check box 1 clicked!” will be displayed at the Text box 1. When the user
clicks the Check box 2, the message “Check box 2 clicked!” will be displayed at the Text
box 2 and when the user clicks the Check box 3, the message “Check box 3 clicked!” will
be displayed at the Text box 3. Follow the given figure below in designing and
developing the application system.
csCheck3
Check 3
Check box 3 clicked!
7.Design and develop an application system that when the user clicks the Radio button 2,
the message “Radio button 2 clicked!” will be displayed at the text box 2. When the user
clicks the Radio button 1, the message “Radio button 1 clicked!” will be displayed at the
text box 1 and when the user clicks the Radio button 3, the message “Radio button 3
clicked!” will be displayed at the text box. Follow the given figure below in designing
and developing the application system.
55
csOption3
Option 1
Option 3
8.Design and develop an application system that when the user clicks the Button 1, the
message “Button 1 clicked!” will be displayed at the text box 1. When the user clicks the
Button 2, the message “Button 2 clicked!” will be displayed at the text box 1 and when
the user clicks the Button 3, the message “Button 3 clicked!” will be displayed at the text
box 1.
When the user clicks the Check box 1, the message “Check box 1 clicked!” will be
displayed at the text box 2. When the user clicks the Check box 2, the message “Check
box 2 clicked!” will be displayed at text box 2, and when the user clicks the Check box 3,
the message “Check box 3 clicked!” will be displayed at the text box 2. Follow the given
figure below in designing and developing the application system.
csButtoncheck1
9. Design and develop an application system that when the user clicks the Option
1, the message “Radio button 1 clicked!” will be displayed at the text box 1.
When the user clicks the Radio button 2, the message “Radio button 2
clicked!” will be displayed at the text box 1 and when the user clicks the
Radio button 3, the message “Radio button 3 clicked!” will be displayed at the
text box 1.
When the user clicks the Check box 2, the message “Check box 2 clicked!” is
displayed at the text box 2. When the user clicks the Check box 1, the message
“Check box 1 clicked!” will be displayed at the text box 2 and when the user
56
clicks the Check box 3, the message “Check box 3 clicked!” will be displayed at
the Text box 2. Follow the given figure below in designing and developing the
application system.
csOptioncheck2
10.Design and develop an application system that when the user clicks the Radio
button 1 (Grade 1), the message “Grade I” will be displayed at the text box 1. When the
user clicks the Radio button 2 (Grade 2), the message “Grade II” will be displayed at the
text box 2 and when the user clicks the Radio button 3 (Grade 3), the message “Grade
III” will be displayed at the text box 3 and when the user clicks the Radio button 4
(Grade 4), the message “Grade IV” will be displayed at the text box and so on and so
forth. In other words, the Elementary school level is just written into its equivalent
Roman numeral form. Follow the given figure below in designing and developing the
application system.
Grade 1
Grade 2
Grade 3
Grade 4
Grade 5
Grade 6
Chapter 3
Using Controls with Input/Output Functions
“The most important single aspect of software development
is to be clear about what you are trying to build.”
-Bjarne Strousup
(Creator of C++)
Tip:
A method is simply a function that is a member of a class.
Arithmetic Operators
+ Addition
_ Subtraction
* Multiplication
/ Division
% Modulus
The above arithmetic operators are handy for our next examples on this chapter. So
remember their symbol so that we can easily understand the succeeding examples and
successfully solve the upcoming Lab Activity Test. Are you ready now? Yes, you are!
58
Note:
We use the ToDouble( ) function if we want to get the input value that is in decimal format such as 54.60 or
as big as 100000.4567. The ToInt16( ) is only limited to integer value which is a whole number such as 10
or 32000 (but not more than 32,000 something; in case of big whole number - you have to use the
ToInt32( ) function instead).
Example 1:
Design and develop a simple application program that calculates the sum of two input
numbers. Follow the given figure below in designing and developing the application
program:
vbSum1
Compute Button
Text box 3
Figure 3.1 Sum of two input numbers
Note:
When the user enters two numbers in two text boxes, the user should click the Button
(with a Compute caption) before the resulting computed value will be displayed at the
third box (Text box 3).
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csSum1. Now click the OK button.
4. Set the Form’s Text property to vbSum1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Compute.
59
6. Click, drag and drop three Text boxes from the Toolbox to add them into the
Form.
7. Double-click now the Compute button on the Form to display the button1_Click
event method. Embed the following lines (in bold only) to the method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Try to enter any numbers at the two text boxes. Then click the Compute button to see the
result. Is the result okay? I hope so.
Sample Output:
Explanation:
60
First, we declare all the variables we used in our program. For the sake of simplicity, we
declared all variables as integer data types. This means that our variables are capable only
of handling smaller whole numbers that will not exceed the 32,000 (the comma symbol
(,) must not be included in entering numeric values, otherwise an error will surely occur)
something values. We declare our variables this way:
As well as initializing the variable with a value of zero (0), in the case of variable sum.
Any character (whether alphabetic, numeric, or special symbol), when it is entered at the
text box is considered and formatted as a text. That is why we need to convert an input
data into its equivalent numerical data by using the Convert.ToInt16 syntax. We did it
this way:
no1 = Convert.ToInt16(textBox1.Text);
no2 = Convert.ToInt16(textBox2.Text);
After the conversion, the variable no1 and no2 will now contain the converted numerical
data. This is the time that we can now compute their values. So we have this simple
adding equation:
Since we cannot display a numeric data directly to the text box control, that is why we
have to convert the numeric data into its text (or string) equivalent using the ToString( )
syntax, such as what we have here in the following code:
textBox3.Text = Convert.ToString(sum);
Note:
The ToInt16 means To Integer 16 bit. So the text data entered will be converted into integer which is 16-
bit wide. Some ToInt??( ) versions are ToInt32( ) and ToInt64( ) functions which are used mainly in very
large numbers of integer data such as in the range of 100,000 (hundreds to millions) to 10,0000000 (the
comma symbol is not included in inputting the numeric data, otherwise, an error will occur) . The
ToInt32( ) function is a 32-bit wide integer, while the ToInt64( ) function is a 64-bit wide integer.
The ToString( ) function is our syntax to use in converting a numeric data into its equivalent string data so
that we can display the data to the text box control (or other controls that are used for displaying data).
61
Example 2:
Design and develop a simple application system that computes the area of a circle. Use
the formula: A = πr2 , where Pi (π) is approximately equivalent to 3.1416. Follow the
given figure below in designing and developing the application system.
vbArea1
Compute Button
Note:
When the user enters the value of the radius in text box 1, the user should click the
Button (with a Compute caption) before the resulting computed value will be displayed at
text box 2.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csArea1. Now click the OK button.
4. Set the Form’s Text property to vbArea1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Compute.
6. Click, drag and drop two Text boxes from the Toolbox to add them into the Form.
Then click two Labels to label these two text boxes properly, based on the given
figure above.
7. Double-click now the Compute button on the Form to display the button1_Click
event method. Embed the following lines (in bold only) to the method:
int r;
Area = 0;
Pi = 3.1416;
r = Convert.ToInt16(textBox1.Text);
Area = 2*Pi*r*r;
textBox2.Text = Convert.ToString(Area);
}
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Now try to enter any value at the text box of the radius. Then click the Compute button to
see the result. Is the result okay?
Sample Output:
Explanation:
First, we declared all the variables we used in our program. We did that with the
following code:
double Area,Pi;
int r;
Area = 0;
Pi = 3.1416;
63
In this example, we declared a constant which name is Pi . This is one of the ways on
how we can declare a constant value in Visual C#. We could noticed also that the
variable Area is declared as double data type. Variable Area will eventually contain a
computed value with decimal point upon processing the equation. Since a variable would
hold a value with a decimal point, it must be declared as double. This is the main reason
why we declared variable Area as double data type. This correct variable data type
declaration also ensures the accuracy of the calculation of our equation.
We initialize the variable Area with a value of zero(0) to ensure that the resulting
calculation in our equation is correct. Forgetting to do so, will result to undesirable
output.
In this code:
.
.
.
r = Convert.ToInt16(textBox1.Text);
Area = 2*Pi*r*r;
textBox2.Text = Convert.ToString(Area);
You will notice also that we convert the input value at text box 1 into its equivalent
numeric value using the ToInt16( ) function to properly calculate it in our equation.
We can see the conversion syntax on the following code:
r = Convert.ToInt16(textBox1.Text);
When we input a number in our text box, it is treated as a string data. Therefore,
converting it to numeric data is needed, otherwise it cannot be properly calculated in the
equation, which in turn results to undesirable output or wrong calculation.
After the conversion, we put the converted numeric integer value at variable r so that we
can use this converted numeric value in the succedding equation which is:
Area = 2*Pi*r*r;
This is the proper way on how to calculate the area of a circle in programming syntax
form. Then finally, we convert the computed value that is stored in Area variable into a
string value before we can display it at the text box 2 successfully, with this code:
textBox2.Text = Convert.ToString(Area);
This is needed to display the value properly. Forgetting to do so, will result to
undesirable output.
64
Example 3:
Design and develop a simple application system that computes the average of three input
quizzes. Then display the result. Follow the given figure below in designing and
developing the application system.
vbAverage1
Compute Button
Text box 4
Figure 3.3. Compute the average quiz
Note:
When the user enters the score of three quizzes in text box 1, 2 and 3, the user should
click the Button (with a Compute caption) before the resulting computed value will be
displayed at text box 4.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csAverage1. Now click the OK button.
4. Set the Form’s Text property to vbAverage1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Compute.
6. Click, drag and drop four Text boxes from the Toolbox to add them into the
Form. Then click two Labels to label the text boxes properly, based on the given
specification above.
7. Double-click now the Compute button on the Form to display the button1_Click
event method. Embed the following lines (in bold only) to the method:
float Ave;
Ave = 0;
Quiz1 = Convert.ToInt16(textBox1.Text);
Quiz2 = Convert.ToInt16(textBox2.Text);
Quiz3 = Convert.ToInt16(textBox3.Text);
Ave = (Quiz1 + Quiz2 + Quiz3)/3;
textBox4.Text = Convert.ToString(Ave);
}
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Now try to enter three quizzes score at the text boxes. Then click the Compute button to
see the result. Is the result okay?
Sample Output:
Explanation:
First, we declared all the variables we used in our program. We did that with the
following code:
.
.
Our variable Ave (for average) was declared as float data type because it is used for a
division operation. The syntax rule in Visual C# and other programming languages is
that any variable which hold the resulting computation of the equation which involves a
division operation must be declared as float (or double for larger floating-point numeric
data) data type. The main reason for this is that even if we divide two whole (integer)
numbers, there is still a big possibility that it yields a value of type float (a number with a
decimal point). Take for example, if we divide N1 / N2 ( D=N1/N2) where N1=7 and
N2=3, this division operation will yield a value of 2.3334 which is a float data type.
Since variable D will hold the resulting computed value with decimal point, therefore
variable D must be declared as float data type. This is also the same case with the
variable Ave that we are using here in our program.
This correct variable data type declaration also ensures the accuracy of the calculation of
our equation, because the numerical data after the decimal point will also be displayed in
our output. So if your output data does not contain any number after the decimal point,
even if you believe that it must, then, the problem probably lies with the way you
declared the variable with its corresponding data type. You might be declaring that
particular variable with an integer data type. Changing it to float data type will solve the
problem.
Tip:
If you encounter a problem where your output numeric data does not produce a number with a decimal
point, then probably you declared the variable that holds that output numeric data as integer. Changing its
declaration to float or double data type would solve the problem. Try it!
In this code:
.
.
.
Quiz1 = Convert.ToInt16(textBox1.Text);
Quiz2 = Convert.ToInt16(textBox2.Text);
Quiz3 = Convert.ToInt16(textBox3.Text);
Ave = (Quiz1 + Quiz2 + Quiz3)/3;
textBox4.Text = Convert.ToString(Ave);
You will notice also that we convert the input value at text box 1, text box 2, and text
box 3 into its equivalent numeric value using the ToInt16( ) function to properly
calculate them in our equation. We can see the conversion syntax on the following
code:
Quiz1 = Convert.ToInt16(textBox1.Text);
Quiz2 = Convert.ToInt16(textBox2.Text);
Quiz3 = Convert.ToInt16(textBox3.Text);
67
When we input a number in our text box, it is treated as a string data. Therefore,
converting it to numeric data is needed, otherwise it cannot be properly calculated in the
equation, which in turn results to undesirable output or wrong calculation.
After the conversion, we put the converted numeric integer values at the variables Quiz1,
Quiz2, and Quiz3 so that we can use these converted numeric values in the succedding
equation which is:
Then finally, we convert the computed value that is stored in Ave variable into a string
value before we can display it at the text box 4 successfully, with this code:
textBox4.Text = Convert.ToString(Ave);
This is needed to display the value properly. Forgetting to do so, will result to
undesirable output.
Example 4:
Design and develop a simple application system that converts the input value of Celsius
into its equivalent Fahrenheit degree. Use the formula: F= (9/5) * C + 32. Follow the
given figure below in designing and developing the application system.
vbDegree1
Button
Compute
Note:
When the user enters the value of the Celsius in text box 1, the user should click the
Button (with a Compute caption) before the resulting computed value will be displayed at
text box 2.
68
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csDegree1. Now click the OK button.
4. Set the Form’s Text property to vbDegree1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Compute.
6. Click, drag and drop two Text boxes from the Toolbox to add them into the Form.
Then click two Labels to label the two text boxes properly, based on the given
specification above.
7. Double-click now the Compute button on the Form to display the button1_Click
event method. Embed the following lines (in bold only) to the method:
8.Run the application system by selecting the Run menu at the menu bar and click the
Start item (or click its equivalent icon at the tool bar).
Now try to enter any value at the text box of the Celsius. Then click the Compute button
to see the result.
Sample Output:
69
Explanation:
First, we declared all the variables we used in our program. We did that with the
following code:
int Celsius;
double Fahrenheit;
Fahrenheit = 0;
.
.
.
We could notice that the variable Fahrenheit is declared as double data type. Variable
Fahrenheit will eventually contain a computed value with decimal point upon processing
the equation. Since a variable would hold a value with a decimal point, it must be
declared as double data type. This correct variable data type declaration also ensures the
accuracy of the calculation of our equation.
In this code:
.
.
.
Celsius = Convert.ToInt16(textBox1.Text);
Fahrenheit = (9.0 / 5.0) * (Celsius + 32);
textBox2.Text = Convert.ToString(Fahrenheit);
70
we write the given equation Fahrenheit = (9/5) * (txtCelsius+32) to convert the input
Celsius into its equivalent Fahrenheit degree. Then we convert the computed value that is
stored in Fahrenheit variable into a string value before we can display it at the text box 2
successfully with this code:
textBox2.Text = Convert.ToString(Fahrenheit);
This is needed to display the value properly. Forgetting to do so, will result to undesirable
output. You will notice also that we convert the input value at text box 1 into its
equivalent numeric value using the ToInt16( ) function to properly calculate it in our
equation. We can see the conversion syntax on the following code:
Celsius = Convert.ToInt16(textBox1.Text);
When we input a number in our text box, it is treated as a string data. Therefore,
converting it to numeric data is needed, otherwise it cannot be properly calculated in the
equation, which in turn results to undesirable output or wrong calculation.
string A sequence of one or more characters that are enclosed within double
quotation marks.
Examples:
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
LAB
ACTIVITY
TEST 2
1. Design and develop a simple application system that converts the input dollar(s) into
its equivalent Peso rate. Follow the given figure below in designing and developing the
application system.
csExchangeRate1
Note:
When the user enters the value of the dollar(s) in text box 1, the user should click the
Button (with a Convert caption) before the resulting computed value will be displayed at
text box 2.
2. Design and develop a simple application system that converts the input Fahrenheit into
its equivalent Celsius degree. Use the formula: C = (5/9) * F - 32. Follow the given figure
below in designing and developing the application system.
csDegree4
Text box 1
Enter the Fahrenheit: 125
Convert Button
Text box 2
The Celsius is: 51.667
73
Note:
When the user enters the value of the Fahrenheit in text box 1, the user should click the
Button (with a Convert caption) before the resulting computed value will be displayed at
text box 2.
3. Design and develop a simple application system that converts the input inch(es) into
its equivalent centimeters. One inch is equivalent to 2.54 cms. Follow the given figure
below in designing and developing the application system.
csInchesConversion2
Text box 1
Enter the inch(es): 4
Convert
Button
Note:
When the user enters the value of the inch(es) in text box 1, the user should click the
Button (with a Convert caption) before the resulting computed value will be displayed at
text box 2.
4. Design and develop a simple application system that computes the volume of a sphere.
Use the formula: V = 4/3 πr3 , where Pi (π) is approximately equivalent to 3.1416. Follow
the given figure below in designing and developing the application system.
csSphere1
Compute Button
Note:
When the user enters the value of the radius in text box 1, the user should click the
Button (with a Compute caption) before the resulting computed value will be displayed at
text box 2.
74
5.Design and develop a simple application system that computes the Depreciation cost of
the item (D). Takes as input the purchase Price of an item (P), its expected number of
years of Service (S), and Yearly depreciation for the item (Y).
Use the formula: D=P-S /Y. Follow the given figure below in designing and developing
the application system.
csDepreciation1
Compute Button
Text box 4
The Depreciation is: 18.75
Note:
After the user enters the purchase Price of an item (P), its expected number of years of
Service (S), and Yearly depreciation for the item (Y) at text boxes 1,2 & 3, the user
should click the Button (with a Compute caption) before the resulting computed value
will be displayed at text box 4.
6.Design and develop a simple application system that determines the most
economical quantity to be stocked for each product that a manufacturing company has
in its inventory. This quantity called economic order quantity (EOQ) is calculated as
follows:
where:
R = total yearly production Requirement
S = Set Up Cost per order
I = Inventory Carrying Cost per unit
Follow the given figure below in designing and developing the application system:
75
csEconomical1
Compute Button
Text box 4
Economic order quantity: 6.324
Note:
After the user enters the total year production Requirement (R), its Set up cost per order
(S), and Inventory carrying cost per unit (I) at text boxes 1,2 & 3 respectively, the user
should click the Button (with a Compute caption) before the resulting computed value
will be displayed at text box 4.
Hint:
Use the Math.Sqrt(intNum1);
-as a mathematical function to get the square root value.
7.Design and develop a simple application system that calculates the difference of two
input numbers. Follow the given figure below in designing and developing the
application system:
csDifference
Compute Button
Text box 3
Note:
When the user enters two numbers in two text boxes, the user should click the Button
(with a Compute caption) before the resulting computed value will be displayed at the
third box (Text box 3).
76
8.Design and develop a simple application system that calculates the product of two
input numbers. Follow the given figure below in designing and developing the
application system:
csProduct
Compute Button
10
Text box 3
Note:
When the user enters two numbers in two text boxes, the user should click the Button
(with a Compute caption) before the resulting computed value will be displayed at the
third box (Text box 3).
9.Design and develop a simple application system that calculates the quotient of two
input numbers. Follow the given figure below in designing and developing the
application system:
csQuotient
Compute Button
2.5
Text box 3
Note:
When the user enters two numbers in two text boxes, the user should click the Button
(with a Compute caption) before the resulting computed value will be displayed at the
third box (Text box 3).
77
Chapter 4
Using Controls with Conditional Statements
Computers can make decisions based on a given condition. This condition can be
evaluated or tested whether true or false. The computer will act appropriately based on
the result of the evaluation. Usually, the conditions are conditional expressions with the
use of relational operators and logical operators.
Relational Operators
Logical Operators
Operators Rules
&& If both or all expressions are evaluated to True, then the result is True.
|| When either or any (or just one) of the expression(s) is True, the result is True.
! If the expression is True, then the result is the opposite of the expression.
Note:
The logical OR symbol ( | ) – a vertical bar - which is called pipe can be found at the top of the Enter key.
Logical OR symbol is a double pipe symbol ( || ).
X Y Z=X * Y
0 0 0
0 1 0
78
1 0 0
1 1 1
X Y Z = X*Y
False False False
False True False
True False False
True True True
X Y Z=X +Y
0 0 0
0 1 1
1 0 1
1 1 1
X Y Z=X+Y
False False False
False True True
True False True
True True True
X Z
0 1
1 0
X Z
False True
True False
In logical NOT (!) operator, the value of variable X is simply inverted, so the value of
variable Z is the inverted value of variable X.
The Visual C# language supports the following three conditional statements (decision
structures):
• if-else
79
• if-else if
• case / switch / default:
if-else Syntax
The simple if-else conditional statement allows the computer to choose one and only one
of the given two alternatives. Its general syntax is:
if condition
statement1
else
statement2
if-else if Syntax
The if - else if control construct allows the computer to evaluate three or more
conditional statements, but to execute only one associated statement (or group of
statements enclosed with begin ({) and end (}) curly brackets) which is the statement of
the first conditional expression that is evaluated to true. In other words, use the if – else if
control structure to define several blocks of statements, one of which will execute. Its
general syntax is:
if condition1
statement1
else if condition2
statement2
else if condition3
statement3
.
.
.
else
statementn
80
if condition1
{
statement1a
statement1b
statement1c
statement1d
…
…
}
else if condition2
{
statement2a
statement2b
statement2c
statement2d
…
…
}
else if condition3
{
statement3a
statement3b
statement3c
statement3d
.
.
.
}
else
{
statementna
statementnb
statementnc
statementnd
}
Visual C# will evaluate first the condition1. If it is false, the Visual C#’s invisible
program pointer will proceed to evaluate condition2, and so on, until it finds a true
condition. When true condition is found, only then that its associated statements will be
executed. We can also add the else conditional statement as the option to choose in the if-
81
else if conditional statement. This will provide a way to catch some impossible to meet
conditions or the “none of the above” situation. We may use the else statement for error-
checking, sometimes.
switch (value_expression)
{
case expression1
statement1;
break;
case expression2
statement2;
break;
case expression3
statement3;
break;
default:
statementn;
break;
}
Each expression is a list of one or more values to be tested or evaluated. Like in the rules
of if – else if statement, if more than one case matches the value_expression, only the
statement associated with the first matching switch/case will be executed. Again, like the
rules of if - else if, the default statement will be executed if none of the values in the
above expression list matches the value_expression. So the default statement of the
switch/case statement is exactly equivalent to the else statement in the if – else if
conditional statement.
Like the else statement is optional to the if or else if conditional statements, the default is
optional also with the switch/case conditional statements. In other words, you can use it
or not.
We have to take note also that although the switch/case statement is the best substitute
statement for the if/else if statement, it has an inherent limitations. For example, we
cannot apply most of the relational operators that are mixed with logical operators with it
such as less than (<), greater than (>), less than or equal to (<=), greater than or equal to
(>=), and not equal (!=) and the logical Or and logical And operators. We cannot say:
82
Or
Example 1:
Design and develop a simple application program that determines if the input number at
Text box 1 is equivalent to the magic words: “I love you” or not. Display the result “I
love you!” at the Text box 2 if the input number is 143, and “Wrong guess!” if it is not.
Follow the given figure below in designing and developing the application system.
csMagicWords1
Determine
Now! Button
I love you!
Text box 2
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMagicWords1. Now click the OK button.
4. Set the Form’s Text property to csMagicWords1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Determine Now!.
83
6. Click, drag and drop two Text boxes from the Toolbox to add them into the Form.
Then click two Labels to label the text boxes properly, based on the given
specification above.
7. Double-click now the Determine Now! button on the Form to display the
button1_Click event method. Embed the following lines (in bold only) to the
method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Try to enter number 143 at text box 1 and click the Determine Now! button to see what
happens. Then try another number. You will see that the output message at text box 2
changes as you enter another number on text box 1.
Sample Output:
Explanation:
if (textBox1.Text == "143")
we are evaluating if the conditional expression is true. Meaning, we are trying to know if
the user is entering a number 143 at text box 1. If he or she was, then we will display the
message “I love you!” at text box 2. Displaying the message can be accomplished
through this code:
Otherwise if other numbers are entered, then the message “Wrong guess!” will be
displayed at text box 2 instead.
One noticeable point here in our program syntax is the way the number 143 is formatted.
It is formatted as a string data (enclosed in double quotation mark). We did this so that
the “Operator ‘==’ cannot be applied to operands of type ‘string’ and ‘int’ error message
at the Output Window can be prevented. Remember that we are testing the conditional
statement with this syntax:
property
if (textBox1.Text == "143")
object
therefore the right side of the equal symbol (==) must be a string (text) data, otherwise it
mismatches with the Text property of object Text box 1.
You can try experiencing this “error message” by omitting the double quotation mark in
the number 143. Do you want to try?
Example 2:
Design and develop a simple application program that determines if the input number is
Positive or Negative. Consider 0 as positive number. Follow the given figure below in
designing and developing the application system.
85
csPositiveNegative1
Determine
Button
Now!
Negative number!
Text box 2
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csPositiveNegative1. Now click the OK button.
4. Set the Form’s Text property to csPositiveNegative1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Determine Now!.
6. Click, drag and drop two Text boxes from the Toolbox to add them into the Form.
Then click two Labels to label the text boxes properly, based on the given
specification above.
7. Double-click now the Determine Now! button on the Form to display the
button1_Click event method. Embed the following lines (in bold only) to the
method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
86
Try to enter a -5 at text box 1 and click the Determine Now! button to see what happens.
Then try another number. You will see that the output message at text box 2 changes as
you enter another number on text box 1.
Sample Output:
Explanation:
First, we declared the variable we used in our program. We did that with the following
code:
int num1;
We need to apply the ToInt16( ) function here in our textBox1.Text expression so that the
number entered at text box 1 which is a string (text) by default will be converted into its
numeric equivalent:
num1 = Convert.ToInt16(textBox1.Text);
In this way, we can evaluate if the number entered is greater than or equal to the number
at the right side of the conditional expression such as in the following code:
if (num1 >= 0)
Conditional expression
87
By the way, how would we know if a number is Positive? Well, a number is positive if it
is greater than or equal to zero, (considering 0 as positive since it is an unsigned number).
How about a Negative number? Well, it is a number that is less than zero. With this logic
in mind, we can simply construct the following code to accomplish the given task:
if (num1 >= 0)
textBox2.Text = "Positive number!";
else
textBox2.Text = "Negative number!";
Actually, there are many ways to solve this given problem such as the following:
If (num1 <=-1)
“It is a Negative Number!”
Else
“It is a Positive Number!”
If (num<0)
“It is a Negative Number!”
Else
“It is a Positive Number!”
It’s up to you, how you come up with your own solution, based on your own logic. Truly, people
have different logic in mind. I hope your logic is right!
Example 3:
Design and develop a simple application program that will assist a teacher in converting
a range of numerical grade into its equivalent letter-form grade, based on the given scale:
Range Grade
90 and above A
80 - 89 B
70 - 79 C
60 - 69 D
below 60 F
Follow the given figure below in designing and developing the application system:
88
csGrade1
Determine
Button
Now!
A Text box 2
Your grade in letter form is:
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csGrade1. Now click the OK button.
4. Set the Form’s Text property to csGrade1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Determine Now!.
6. Click, drag and drop two Text boxes from the Toolbox to add them into the Form.
Then click two Labels to label the text boxes properly, based on the given
specification above.
7. Double-click now the Determine Now! button on the Form to display the
button1_Click event method. Embed the following lines (in bold only) to the
method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Try to enter number 94 at text box 1 and click the Determine Now! button to see what
happens. Then try another number. You will see that the output message at text box 2
changes as you enter another number on text box 1.
Sample Output:
Explanation:
First, we declared the variable we used in our program. We did that with the following
code:
int grade;
grade = Convert.ToInt16(textBox1.Text);
In this way, we can evaluate if the number entered is greater than or equal to the number
at the right side of the conditional expression such as in the following code:
.
.
.
else if (grade<60)
We apply here also the logical AND (&&) operator so that we can trap the numeric range
of the grade entered. In doing so, we can ensure that the number entered falls within a
specific range, and our program will respond appropriately based on it. Remember that in
logical AND (&&), both or all conditional expressions must be evaluated to true so that
its associated statement(s) will be executed. Like for example, if we input a numeric
grade of 75, the conditional expressions:
.
.
.
if (grade>=90)
textBox2.Text="A";
else if ((grade>=80) && (grade<=89))
textBox2.Text="B";
else if ((grade>=70) && (grade<=79))
textBox2.Text="C";
else if ((grade>=60) && (grade<=69))
textBox2.Text="D";
else if (grade<60)
textBox2.Text="F";
.
.
.
were evaluated to true since the number 75 is greater than 70 and less than 79 (so both
conditional expressions are tested true). Therefore, the associated statement:
textBox2.Text = “C” was executed that results to the output on text box 2 with a letter
“C”.
In the if-else if syntax, after finding a true evaluation for a particular conditional
statement, the Visual C# system compiler will jump right to the end of the if statement,
thus ending the evaluation process. In other words, the remaining conditions below it will
no longer be evaluated or tested (or simply ignored). Technically, this will save much
microprocessor’s processing power compared to using all ifs conditional statements in
your program. Meaning, using the if statement all throughout instead of else if statement.
With the if statement, all conditional statements will be evaluated, regardless of how
many true evaluations were found at the upper part of the conditional block. This makes
very taxing to the microprocessor’s processing energy. In other words, the following code
is not advisable to use (since there is only one option to be selected by our Visual C#
system compiler to comply with the given program requirement):
.
.
.
if (grade>=90)
textBox2.Text="A";
if ((grade>=80) && (grade<=89))
91
textBox2.Text="B";
if ((grade>=70) && (grade<=79))
textBox2.Text="C";
if ((grade>=60) && (grade<=69))
textBox2.Text="D";
if (grade<60)
textBox2.Text="F";
.
.
.
Notice all the conditional statements pointed by the arrows. It contained all ifs. It’s bad in
programming. There are cases or situations in real-world application that we have no
other choice but to use all the ifs throughout in our sub procedure, however such cases or
situations rarely occur. So use all ifs with utmost care, okay?
Example 4:
Design and develop a simple application program that displays an equivalent color once
an input letter matches its first character. For example b for Blue, r for Red, and so on.
Here is the given criteria:
Letters Colors
Follow the given figure below in designing and developing the application system:
csColor1
Determine
Now! Button
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csColor1. Now click the OK button.
4. Set the Form’s Text property to csColor1.
5. Click, drag, and drop two text boxes from the Toolbox to add them into the Form.
Position them properly and adjust their width appropriately.
6. Click, drag, and drop a Button from the Toolbox, then set its Text property to
Determine Now!.
7. Now, click, drag and drop a Label from the Toolbox and set its Text property to
Enter a letter:.
8. Double-click now the Determine Now! button on the Form to display the
button1_Click event method. Embed the following lines (in bold only) to the
method:
9.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Try to enter a letter “r” at text box 1 and click the Determine Now! button to see what
happens. Then try another letter. You will see that the output message at text box 2
changes as you enter another letter on text box 1.
93
Sample Output:
Explanation:
First, we declared the variable we used in our program. We did that with the following
code:
char Letter;
Letter = Convert.ToChar(textBox1.Text);
Tip:
A character data type refers to a single letter (such as any letter we can see in the Alphabet), a single
special symbol (such as ‘*’, ‘!’, ‘@’, ‘#’, ‘$’, ‘%’, ‘^’, ‘&’, etc.), or a number enclosed by a pair of single
quote ( such as ‘0 ‘, ‘1’, ‘2’, ‘3’, and so on).
In this way, we can evaluate if the letter entered is equal to the letter at the right side of
the conditional expression such as in the following code:
textBox2.Text = "Blue!";
else if ((Letter == 'R') || (Letter == 'r'))
textBox2.Text = "Red!";
else if ((Letter == 'G') || (Letter == 'g'))
textBox2.Text = "Green!";
else if ((Letter == 'Y') || (Letter == 'y'))
textBox2.Text ="Yellow!";
else
textBox2.Text ="Unknown Color!";
}
In this type of program, we need to apply the Logical Or (| |), so that we can accomplish
the given task required. Remember that in logical Or (| |), at least one conditional
expression which is evaluated True will trigger the computer to execute the associated
statement(s). The logical Or (| |) is applied to this kind of program requirement, because
the user’s input whether uppercase(capital) letter or lowercase(small) letter should be
accepted as valid. In programming, the data or value small ‘r’ is not equivalent to capital
‘R’. Now if we input the small letter r then the message “Red” will be displayed at text
box 2, and if we change the small letter r to capital letter R, the output is still “Red”. The
same goes to small letter b or capital letter B. That’s the end of our discussion.
Now let us go to the application of switch/case conditional statement. Are you excited
for the next topic? I hope so.
In our next example, let us try to use the switch/case conditional statement to the above
example instead of the if/else if construct. And here it is!
Example 5:
Design and develop a simple application program that displays an equivalent color once
an input letter matches its first character. For example b for Blue, r for Red, and so on.
This time, use the Select Case conditional statement instead of If/Else If conditional
statement. Here is the given criteria:
Letters Colors
Follow the given figure below in designing and developing the application system:
95
csColor2
Determine Button
Now!
Text box 2
Red!
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csColor2. Now click the OK button.
4. Set the Form’s Text property to csColor2.
5. Click, drag, and drop two text boxes from the Toolbox to add them into the Form.
Position them properly and adjust their width appropriately.
6. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Determine Now!.
7. Now click, drag, and drop a Label from the Toolbox and set its Text property to
Enter a letter:.
8. Double-click now the Determine Now! button on the Form to display the
button1_Click event method. Embed the following lines (in bold only) to the
method:
case 'g':
textBox2.Text = "Green!";
break;
case 'Y':
case 'y':
textBox2.Text = "Yellow!";
break;
default:
textBox2.Text = "Unknown Color!";
break;
} // end of switch/case statement
}
9.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Try to enter a letter “r” at text box 1 and click the Determine Now! button to see what
happens. Then try another letter. You will see that the output message at text box 2
changes as you enter another letter on text box 1.
Sample Output:
Explanation:
First, we declared the variable we used in our program. We did that with the following
code:
char Letter;
97
Letter = Convert.ToChar(textBox1.Text);
Tip:
A character data type refers to a single letter (such as any letter we can see in the Alphabet), a single
special symbol (such as ‘*’, ‘!’, ‘@’, ‘#’, ‘$’, ‘%’, ‘^’, ‘&’, etc.), or a number enclosed by a pair of single
quote ( such as ‘0 ‘, ‘1’, ‘2’, ‘3’, and so on).
switch (Letter)
The switch (Letter) command holds the value of the variable Letter for testing, evaluation,
or comparison with the given value_expression of each case or group of cases.
Once the match is found (means the value of variable Letter is the same with the
value_expression found) then the program pointer will search the associated statement and
execute it. For example, if we enter letter r at the text box 1, the program pointer will
execute the associated statement:
textBox2.Text = "Red!";
since this value_expression can be found at the second case label. When the value entered
does not match to any value_expression listed, the associated statement of default is
executed instead. If the default is not included (since it is optional), then nothing will be
executed.
Warning!
The else and default which are both optional in if-else if and switch/case conditional statements respectively,
are actually a helpful and useful optional statements. These optional statements can catch some impossible
or simply outrageous input data. Furthermore, if they are not present in our conditional statement as the last
option to choose by the invisible program pointer, then there is a possibility that our program would give the
impression to the user that the computer hangs.
You will observe that all the associated statements are followed by the break command.
This break command will trigger the program pointer to break out from the whole switch/case
(statement) block. Meaning, it jumps to the statement that follows the end ( } ) symbol of
switch/case statement. This makes our switch/case solution to act and execute like the way if /
else if do. It’s like ignoring all the remaining conditional statements and expressions below
when there is already a true-evaluation at the top. In short, the break statement causes an
immediate exit from the switch/case (statement) block.
You will notice that instead of using the logical Or (| |) operator (to evaluate the
expression), we use the list of case value_expression. To understand this explanation
easily, let us have this comparative presentation:
98
The system compiler will test first the first expression in the list of the switch/case block,
then if it is evaluated to False, it will proceed testing the next expression and so on until it
will find a True evaluated expression. However, if all listed expressions in the
switch/case block are evaluated to False then the associated statement of the optional
default statement will be executed. In the absence of this optional default statement, our
application system will simply display no output (or it seems our application program is
hanging). This is the beauty of putting an default optional statement for this kind of
situation to prompt the user about what happened. Informing the user on what happened
is always the best defense. Without doing so, the user might misunderstand how the
application system reacts or behaves in this type of circumstances. As a result, the user
might reboot the computer (thinking, that it hangs), which should not be the case, since
there is no need to reboot it.
Example 6:
Design and develop a simple application program to display the high school level of a
student, based on its year-entry number. For example, the year-entry 1 means the student
is a freshman, 2 for sophomore, and so on. Here is the given criteria:
1 Freshman
2 Sophomore
3 Junior
4 Senior
Other entry no. Out-Of-School
Follow the given figure below in designing and developing the application system:
99
csHighSchoolLevel1
Determine Button
Now!
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csHighSchoolLevel1. Now click the OK
button.
4. Set the Form’s Text property to csHighSchoolLevel1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Determine Now!.
6. Click, drag, and drop two text boxes from the Toolbox to add them into the Form.
Position them properly and adjust their width appropriately.
7. Now click, drag, and drop a Label from the Toolbox and set its Text property to
Enter Year-entry number:.
8. Double-click now the Determine Now! button on the Form to display the
button1_Click event method. Embed the following lines (in bold only) to the
method:
case 4:
textBox2.Text = "Senior!";
break;
default:
textBox2.Text = "Out-Of-School!";
break;
} // end of switch/case statement
}
9.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Try to enter number 2 at text box 1 and click the Determine Now! button to see what
happens. Then try another number. You will see that the output message at text box 2
changes as you enter another number on text box 1.
Sample Output:
Explanation:
First, we declared the variable we used in our program. We did that with the following
code:
int Level;
101
The moment we enter a number at any text boxes, its default data type is a string. To
convert the input data to numeric value, we need to use the Convert.ToInt16( ) method.
This is the reason why we have the following statement:
Level = Convert.ToInt16(textBox1.Text);
With the above statement, the Level variable will contain the converted numeric data. If
case 1 is evaluated to True then its associated statement:
textBox2.Text = "Freshmen!";
is executed. After that, the system compiler’s invisible program pointer will jump to the
end ( } ) of the switch/case statement right away (ignoring all the remaining list of
expressions below).
Tip:
The end symbol of C# is a closing curly bracket - }. This is also the same with Java, C/C++, and
JavaScript, and other scripting languages.
If case 1 is evaluated to False, then the next case statement is evaluated. The system
compiler will test the remaining case statements until it finds a True evaluated
expression. If none is found, then the associated statement of default conditional
statement will be executed. In the absence of the optional default statement in our code,
the result will simply a “no output” in our program’s text box 2. It is recommended that
we will always put a default statement in our code that uses switch/case conditional
statement in order to catch an impossible input data or to the “none of the above”
selection situation.
Remember that we can use the input string data on the text box directly in our code by
not using the ToInt??( ) method. However, we will declare the Level variable as String
and enclose the numeric expression in the case statement with double quotes so that it
can be read by the compiler system as a string expression. Examine the changes in our
code below:
break;
default:
textBox2.Text = "Out-Of-School!";
break;
} // end of switch
} // end of private void button1_Click
The system compiler will test first the first expression in the list of the switch/case block,
then if it is evaluated to False, it will proceed testing the next expression and so on, until
it will find a True evaluation result from a particular expression. However, if all listed
expressions in the switch/case block are evaluated to False then the associated statement
of the optional default statement will be executed. In the absence of this optional default
statement, our application system will simply display no output (or it seems our
application program is hanging). This is the beauty of putting a default optional statement
for this kind of situation that prompts the user about what happened. Informing the user
on what happened is always the best defense. Without doing so, the user might
misinterpret the application systems’ reaction or behavior to this type of circumstances.
As a result, the user might reboot the computer (thinking, that it hangs), which should not
be the case, since there is no need to reboot it.
Example 7:
Design and develop a simple application program that demonstrates how to use the String
data type variable. In this program, the user will input his or her name, then the output
will be a simple greeting. Follow the given figure below in designing and developing the
application system.
vbString1
Greet Me?
Button
OK
103
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csString1. Now click the OK button.
4. Set the Form’s Text property to vbString1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Greet Me!.
6. Click, drag, and drop two text boxes from the Toolbox to add them into the Form.
Position them properly and adjust their width appropriately.
7. Now click, drag, and drop two Labels from the Toolbox and set their respective
Text property to Enter your name: and Good morning:.
8. Double-click now the Greet Me! button on the Form to display the button1_Click
event method. Embed the following lines (in bold only) to the method:
9.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Sample Output:
104
Explanation:
First, we declared the variable we used in our program. We did that with the following
code:
You will notice that we declared our variable strName as a String data type. Then we
initialize it as an empty string variable with the declaration:
Since our strName variable is declared as String data type, therefore, it can contain any
text string that is entered in the Text box 1. So we can store any text string data that is
entered on Text box 1 into string variable strName with the following code:
strName = textBox1.Text;
Now to display the string value of variable strName into Text box 2, we simply store it
directly into Text box 2 with the following code:
textBox2.Text = strName;
And finally, to display the string data that is stored at strName variable into the Message
box, we have the following code:
105
That’s the end of our discussion, and let us go to other application that will make us more
excited!
Here in our next example, we will use the Radio buttons together with Check Boxes in a
hypothetical application system. Let us learn how to manipulate them together. Well, we
will apply other popular controls too, such as the Text box and Button. Okay, let us see it
in action!
By the way, the Label control displays read-only text, and its main function is to provide
information to the user. This can be in the form of a message shown on the form or a
prompt. A message such as labeling an output data of what it is or telling the user what
kind of data to input. This Label application is usually with a conjunction of a text box
that holds the input or output data. Like for example, that the numeric output in the text
box is the Area of a circle or a Fahrenheit degree. Or simply telling the user to enter a
numeric data for calculation or a character to process. The label as a prompt is usually
combined with a text box, list box, combo box or other control. It provides the user an
idea of the nature of the referenced control. For instance, if we had a list box that contains
the abbreviated different States in America. We can put a label at the top of list box that
tells about the abbreviations.
Example 8:
Design and develop a simple application system that when the user chooses the Deluxe
pizza option, the ingredients to be checked are: Cheese, Bacon & Ham, and Onion &
Chili; its corresponding price is 185 pesos (to be displayed at the text box). When the
user chooses the Special pizza option, the ingredients to be checked are: Cheese, Pepper,
Bacon & Ham, Mushroom, and Onions & Chili; its price is 250 pesos. Now if the user
chooses the Primo pizza option, all ingredients should be marked with a check, and its
price is 290 pesos.
Follow the given figure below in designing and developing the application system:
106
vbPizza1
Pizza Ingredients
Cheese
Deluxe
Pepper
Special
Bacon & Ham
Primo
Mushroom
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csPizza1. Now click the OK button.
4. Set the Form’s Text property to vbPizza1.
5. Click, drag and drop a GroupBox (can be found at the All Windows Forms
category) from a Toolbox and change its caption to “Pizza”, then put three Radio
buttons inside it and name the Radio buttons with the captions : Deluxe, Special,
and Primo. Next, click, drag and drop another GroupBox with a caption
“Ingredients”, then put seven check boxes on it and name the Check boxes
captions with these: Cheese, Pepper, Bacon & Ham (put a double && at the
Properties Box), Mushroom, Onions & Chili (put a double && again at the
Properties Box), Tomato & P-Apple (for Pineapple and put a double && at the
Properties Box again), and Salami.
6. Finally, drag and drop a Text box from a Toolbox and place it below the Pizza
Frame. Then put a label at the top of it with the word “Price:”.
7. Double-click the Deluxe (Radio button 1) on the Form to display the
radioButton1_CheckedChanged event method. Embed the following lines of code
(in bold only) to the method:
chkPepper.Checked = false;
chkBaconHam.Checked = true;
chkMushroom.Checked = false;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
chkSalami.Checked = false;
textBox1.Text = "185";
}
10.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Try to click the Deluxe Pizza option, then the Special Pizza option, and finally the Primo
Pizza option, to see how our program works. Is it working? I hope so.
Sample Output:
108
Explanation:
Since we want to put a check mark for the ingredients - Cheese (positioned at Check 1
object), Bacon & Ham (positioned at Check 3 object), Onions & Chili (positioned at
Check 5 object) when the user clicks the Deluxe pizza option (positioned at Radio button
1 object), therefore we have to assign them with a Boolean value of true. The false
Boolean value means the check box will be displayed without a check mark or with
unselected status. We can accomplish this task with the following code:
Once the Deluxe pizza option is clicked by the user, we will also display the 185 pesos
price of Deluxe pizza at the text box 1. We can accomplish the task with this code:
textBox1.Text = "185";
109
The above explanation applies also (with a slight modifications to fit with the given
situation or requirement) to the Special and Primo pizza options. So there is no need for
me to explain it in details.
What we have done previously is a simple Assessment system. How about an Assessment
system where we can input a quantity of a particular item, then it will output its
computation such as its amount. Is it not more flexible? Okay, we will do it now in our
next example.
Example 8:
Design and develop a simple application system that when the user chooses the Deluxe
pizza option, the ingredients to be marked are Cheese, Bacon & Ham, and Onions &
Chili. Its price is P 185 pesos. If the user inputs 2 in the Qty (Quantity) box, the Amt
(Amount) to be displayed should be 270, because 185 * 2 is equal to P 270 pesos. If the
input quantity is 3 then the amount to be displayed is 455 pesos, and so on.
When the user chooses the Special pizza option, the ingredients to be checked are
Cheese, Pepper, Bacon & Ham, Mushroom, and Onions & Chili. Its price is P250 pesos.
If the user inputs 2 at the Qty box, the Amt to be displayed is P500 pesos. If the input
quantity is 3 then the amount to be displayed is P750 pesos, and so on.
When the user chooses the Primo pizza option, all ingredients should be marked with a
check. Its price is P290 pesos. If the user inputs 2 at the quantity box, the amount to be
displayed is P380 pesos. If the input quantity is 3 then the amount to be displayed is
P870, and so on.
Follow the given figure below in designing and developing the application system.
vbPizza2
Pizza Ingredients
Cheese
Deluxe
Pepper
Special
Bacon & Ham
Primo
Mushroom
Salami
Compute
Button
Now!
Amount: 370
110
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csPizza2. Now click the OK button.
4. Set the Form’s Text property to vbPizza2.
5. Click, drag and drop a GroupBox (can be found at the All Windows Forms
category) from a Toolbox and change its caption to “Pizza”, then put three Radio
buttons inside it and name the Radio buttons with the captions : Deluxe, Special,
and Primo. Next, click, drag and drop another GroupBox with a caption
“Ingredients”, then put seven check boxes on it and name the Check boxes
captions with these: Cheese, Pepper, Bacon & Ham (put a double && at the
Properties Box), Mushroom, Onions & Chili (put a double && again at the
Properties Box), Tomato & P-Apple (for Pineapple and put a double && at the
Properties Box again), and Salami.
6. This time, click, drag and drop a Button from the Toolbox to add it into the Form,
the set its Text property to Compute Now!
7. Now at the Property box, set the Name property of Radio Button 1 as rdoDeluxe.
Make it sure that you are at the Radio Button 1 property box. To accomplish this
task, you have to click the Radio Button 1 so that the focus is now at Radio
Button 1 which Text value is Deluxe. Next, set the Name property of Radio
Button 2 as rdoSpecial. Again, make it sure that you are at the Radio Button 2
property box, so you have to click the Radio Button 2 which Text value is
Special. Lastly, set the Name property of Radio Button 3 as rdoPrimo and make
it sure that you are at the Radio Button 3 property box by clicking the Radio
Button 3 which Text value is Primo.
8. Now at the Property box, set the corresponding Name property of Checkbox 1 as
chkCheese; Checkbox 2 as chkPepper; Checkbox 3 as chkBaconHam;
Checkbox 4 as chkMushroom; Checkbox 5 as chkOnionsChili; Checkbox 6 as
chkTomatoPineapple; and lastly: Checkbox 7 as chkSalami.
9. Finally, click, drag and drop three Text boxes from a Toolbox and place them
below the Pizza Frame. Then put its corresponding labels in front of them, such as
the Price, Qty:., and Amt:. Now at the Property box, set the Name property of
TextBox 1 as txtPrice TextBox 2 as txtQty and TextBox 3 as txtAmt,
respectively.
10. Double-click the Deluxe (Radio button 1) on the Form to display the
rdoDeluxe_CheckedChanged event method. Embed the following lines of code
(in bold only) to the method:
111
13. Double-click now the Compute Now! Button to display the button1_Click event
method. Embed the following lines of code (in bold only) to the method:
private void button1_Click(object sender, EventArgs e)
{
int Quantity;
float Amount;
Amount = 0;
if (rdoDeluxe.Checked)
112
{
Quantity = Convert.ToInt16(txtQty.Text);
Amount = Quantity * 185;
txtAmount.Text = Convert.ToString(Amount);
}
else if (rdoSpecial.Checked)
{
Quantity = Convert.ToInt16(txtQty.Text);
Amount = Quantity * 250;
txtAmount.Text = Convert.ToString(Amount);
}
else if (rdoPrimo.Checked)
{
Quantity = Convert.ToInt16(txtQty.Text);
Amount = Quantity * 290;
txtAmount.Text = Convert.ToString(Amount);
}
}
14. Double-click now the Qty text box (Text Box 2) on the Form to display the
txtQty_TextChanged event method. Embed the following lines of code (in bold
only) to the method:
private void txtQty_TextChanged(object sender, EventArgs e)
{
txtAmount.Text = " ";
}
15. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Try to click the Deluxe pizza option, to see how our program works. Now input a number
in the Qty (Quantity) text box, then click the Compute Now! button. Does the program
display the amount correctly? Now try to click the Special pizza option and change the
input number at the Qty (Quantity) text box, then click the Compute Now! button, and
see what happens. Is the amount correct? I hope so.
Sample Output:
113
Explanation:
Since we want to put a check mark for the ingredients - Cheese (positioned at Check box
1 object), Bacon & Ham (positioned at Check box 3 object), Onions & Chili (positioned
at Check box 5 object) when the user clicks the Deluxe pizza option (positioned at Radio
button 1 object), therefore we have to assign them with a Boolean value true. The false
Boolean value means the check box will be displayed without a check mark or with
unselected status. We can accomplish this task with the following code:
The above explanation applies also (with a slight modification to fit with the given
situation or requirement) to the Special and Primo pizza options. So there’s no need to
repeat the discussion for each of them.
114
We are using here the if/else conditional statement to evaluate if the conditional
expressions Deluxe (Radio button 1), Special (Radio button 2), and Primo (Radio button
3) are evaluated to True. If the Deluxe (Radio button 1) is evaluated to True, then its
associated statements which is an equation and a display at Text box 3 will be executed
or performed. The same thing applies to Special (Radio button 2) and Primo (Radio
button 3) conditional expressions, too. Remember that the conditional expressions such
as Deluxe, Special, and Primo can be evaluated to True only if they are selected by the
user through clicking its corresponding Radio button. Try to examine its code below:
We have ended well. Let us now go to the topics which I find very interesting to share
with you. And I really love to express the succeeding idea how Visual Basic differs from
Visual C# programming in some instances. Though, most of the time, they are
comparable in power and flexibility.
As we end this chapter, I would like to introduce a topic that probably trigger’s your
curiosity why our examples here does not introduce a
this.listBox1.SelectedIndexChanged event method. Probably, you would noticed that in
my Introduction To Visual Basic 2012 Programming book, I extensively present this
115
event method. The main reason for this is that, in C#, this method requires stricter
implementation with data type inputs. A numeric input data may not be easily converted
to string data, or if it could, it generates a FormatException unhandled error. To
expound my presentation about this issue, I have here some examples for you to try,
before you’ll go to your Lab Activity Test 3. This is for the sake of curiosity, only.
I have here two examples, which the other one works, and the other does not.
Specifically, Example 1 works, while Example 2 generates FormatException unhandled
error. Let us try these two examples now!
Design and develop a simple application program that determines if the input number at
Text box 1 is equivalent to the magic words: “I love you” or not. Display the result “I
love you!” at the Text box 2 if the input number is 143, and “Wrong guess!” if it is not.
Follow the given figure below in designing and developing the application system.
csMagicWords3
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMagicWords3. Now click the OK button.
4. Set the Form’s Text property to csMagicWords3.
5. Click, drag and drop two Text boxes from the Toolbox to add them into the Form.
6. Finally, click, drag, and drop one Label and place it appropriately.
7. Double-click now the Text box 1 on the Form to display the
TextBox1_TextChanged event method. Embed the following lines of code (in
bold only) to the method:
{
if (textBox1.Text == "143")
textBox2.Text = "I love you!";
else
textBox2.Text = "Wrong guess!";
}
8. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Now try to enter a number “143” at text box 1 and see what happens. Then try
another number. You will see that the output message at text box 2 changes as you
enter another number on text box 1.
Sample Output:
Design and develop a simple application program that determines if the input number is
Positive or Negative. Consider 0 as positive number. Follow the given figure below in
designing and developing the application system.
117
csPositiveNegative3
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csPositiveNegative3. Now click the OK button.
4. Set the Form’s Text property to csPositiveNegative3.
5. Click, drag and drop two Text boxes from the Toolbox to add them into the Form.
6. Finally, click, drag, and drop one Label and place it appropriately.
7. Double-click now the Text box 1 on the Form to display the
TextBox1_TextChanged event method. Embed the following lines of code (in
bold only) to the method:
8. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Now try to enter a -5 number at text box 1 and see what happens. See? It doesn’t work!
I told you so, buddy.
118
Warning!
The above program generates the System.FormatException was unhandled.
The foregoing presentation reminds us that although there are many successful
implementations that we can convert our Visual Basic code into Visual C# code easily in
like manner, not all of them are possible. This is because Visual C# input data
manipulation is stricter than Visual Basic.
Example 9:
Design and develop a simple Password program. The user should input a password to the
text box 1. To confirm if the password is correct, the user should click the Check if
correct! button. The feedback about the user’s input should be displayed at text box 2.
Follow the given figure below in designing and developing the application system.
vbMyPassword1
Text box 2
Note:
The correct password for this program is MyPassword
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMyPassWord1. Now click the OK button.
4. Set the Form’s Text property to vbMyPassWord1.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Login now your Password:.
119
6. Click, drag, and drop a Text box from the Toolbox, then set its Password property
as * (asterisk symbol).
This asterisk symbol at the Password property of Text box 1, means once the user inputs
his or her password, the asterisk will be the character to be written on it, instead of its
readable password.
7. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Check if correct!.
8. Finally, click, drag and drop a Text box from the Toolbox to add it into the Form.
9. Now, this time, double-click the Check if correct! button on the Form to display
the Button1_Click event method. Embed the following lines (in bold only) to the
method:
10. Finally, double-click the Text box1 on the Form to display the
textBox1_TextChanged event method. Embed the following lines (in bold only)
to the method:
11.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
120
Explanation:
It is unbelievable that this simple Password programming is so easy. We just simply set
the Password property of a Text box into a special symbol such as * (asterisk – the most
common and famous special character for masking password) so that when the user types
his or her password, the * will be displayed instead of the readable password. Now to
test if the input password is correct or not, we simply use the if / else conditional
statements to accomplish this programming task, using the following code:
if (textBox1.Text == "MyPassword" )
textBox2.Text = "Correct Password!";
else
textBox2.Text = "Incorrect Password!!, Try again!";
We need to clear also the Text box 2 once the user enters another password at Text box 1.
We can accomplish the task with the following code:
We put the code right at the Text box 1 TextChanged event method. This further means
that if the user enters another password on it (so there is a text changed event that
happened), then Text box 1 should be cleared right away.
LAB ACTIVITY
TEST 3
1. Design and develop a simple application program that determines if the input
letter at text box 1 is a Vowel or Consonant. The output message should be
displayed at text box 2. The Vowels are: A E I O U; while the remaining letters
are Consonants. Your program must be able to handle an uppercase or lowercase
input letter. Follow the given figure below in designing and developing the
application program:
csAlphabet1
Button
Determine
Now!
2. Design and develop a simple program that examines the input value of a variable
nTemp (Temperature) at text box 1. Then display the following messages at text
box 2 depending on the value assigned to nTemp variable.
Temperature Message
Follow the given figure below in designing and developing the application program:
csTemperature9
Determine
Now! Button
3. Design and develop a simple program for the Air Force to label an aircraft as
military or civilian. The program is to be given the plane’s observed speed in
km/h (kilometer per hour).The speed will serve as its input at text box 1. For
planes traveling in excess of 1100 km/h, you should label them as “civilian”
aircraft; between 500 km/h to 1100 km/h, label them as “military” aircraft and for
planes traveling at more slower speed - less than 500 km/h, you should label them
as an “It’s a bird!” message. The labeled message should be displayed at text box
2 . Follow the given figure below in designing and developing the application
program:
csAircraft1
Text box 1
Enter the aircraft speed in km/h: 700
Determine Button
Now
4. Design and develop a simple program that determines the class of the Ship
depending on its class ID (identifier). Here is the criteria. The class ID serves as
the input data at text box 1 and the class of the ship serves as the output
information at text box 2. Your program should be able to handle both capital or
lower case letter as an input data.
B or b Battleship
C or c Cruiser
D or d Destroyer
F or f Frigate
123
Follow the given figure below in designing and developing the application program:
csShip3
Text box 1
Enter the class id of the ship: C
Determine Button
Now!
Follow the given figure below in designing and developing the application program:
csEarthquake2
Determine
Now! Button
6. Design and develop a simple application program that accepts an input grade in
percentile form at text box 1 and output its grade equivalent at text box 2 based on
the given range of percentile and grade equivalent table below:
98 - 100 1.00
95 - 97 1.25
92 - 94 1.50
89 - 91 1.75
85 - 88 2.00
82 - 84 2.25
80 - 81 2.50
77 - 79 2.75
75 - 76 3.00
other grades “Out - Of-Range”
Follow the given figure below in designing and developing the application program:
csGradingSystem2
Determine
Now! Button
7. Design and develop a simple application program that adds, subtracts, multiplies, or
divides two input numbers using the radio buttons. Follow the given figure below in
designing and developing the application program:
125
csSimpleCalc2
Compute
Radio buttons
Hint:
Double-click the Form to open the Form1_Load( ) event method, then put the initial
value for intNum1 and intNum2 variables, so that there will be no IOException error at
the compiling stage would occur. For example (embed similar codes below:):
8. Design and develop a simple application program that adds, subtracts, multiplies, or
divides two input numbers using a group of buttons. Follow the given figure below in
designing and developing the application program:
126
csSimpleCalc3
Compute
Add 1st no. 5
=
Multiply
7
Answer:
Divide
Buttons
9. Design and develop a simple application system so that when the user chooses the
Economy accommodation, the Toilet and Meals amenities should be marked with a check
and the fare is P1,500. When the user chooses the Tourist accommodation, the Toilet,
Aircon, Bed sheets, and Meals amenities should be marked with a check and the fare is
P1,700. When the user chooses the Cabin accommodation, all amenities should be
marked with a check and the fare is P2,000 pesos.
csShip4
Amenities
Accommodation Toilet
Economy Aircon
Tourist Television
Meals
Fare:
P 1500
VIP Lounge
Text box
10.Design and develop this simple application system. Here in our program, we
will input the tuition fee. Now if the user clicks the Compute button, the total
tuition fee will be displayed at Text box 2 (Text2). In our sample input data, we
127
input the 30,000 tuition fee, now its 5 % (percent) interest is 1,500. Thus, output
at text box 2 (Text2) is 31,500 (30,000 + 1,500).
Now for example we enter a tuition fee of 20,000 and then we select the Cash as
the mode of payment, the output at text box 2 (Text2) should be 18,000 since
there is a 10 % (percent) discount for paying a Cash tuition fee.
Follow the given figure below in designing and developing the application
system:
csTuitionFee2
Mode of Payments
Enter tuition fee:
Cash (10% discount)
30000 Text box 1
Two Payments
(5% interest) Compute Button
Now!
Three Payments 1
(10% interest) Your total tuition fee:
31500 Text box 2
11.Design and develop a simple application system that if the user selects CT-
Scan, only the Head body parts is marked with a check. If X-Ray is chosen, only
the Body will be marked with a check. And if the Physical exam is chosen, then
all the body parts are marked with a check. In our example, we chose the X-ray as
the Medical exam chosen, and since the number of Medical exam is 2, therefore,
the Bill is 2000 (1000 * 2).
csPatientRecord2
Chapter 5
Using Controls with Looping Statements
Looping Statements
The looping statement is a program instruction that repeats some statement or sequence
of statements in a specified number of times. Looping statement allows a set of
instructions to be performed all over and over again until a certain condition is reached,
met, proven or tested as false or true. In other words, looping statement allows us to
execute one or more lines of code repetitively.
The three parts of the for loop are the initialization (init) part , the condition part, and the
increment (inc) or decrement (dec) part. The initialization part of the loop statement is the
first value where the loop starts. For example, we can start our loop with the value of zero (0)
or one (1). Usually, we use 0 since most of the Java array (or C & C++ languages) starts at
zero-th position. The condition part is where we say when to stop the looping process. The
loop continues to execute so long as the condition which the program is evaluating (or
checking) is true. Once it is no longer true, the loop terminates. Now if in the first time the
program check the condition and find out it is false, the loop is never executed at all.
The incrementation part is where we say by how much to increase the loop counter on each
pass through the loop. Usually, we add one to variable i each time through using ++ symbol.
This is opposite in decrementation process because we subtract one to variable i each time
through using -- symbol. The sample of incrementation formula is i++ or ++i, while the
decrementation formula is --i or i-- .
The foreach loop repeats a group of statements for each element in a collection of objects
or in an array instead of repeating the statements in a specified number of times. This is
especially helpful if we don’t know how many elements are in a collection.
init;
while (condition) {
statements;
inc/dec;
}
The syntax of the do/while loop statement is different from other looping statements, because
the checking or evaluating of conditional part for continuing the loop is at the end of the
loop instead of at the top. This means that the loop will always execute at least once. There
are real-world system applications that need to be executed at least once, so do/while loop
statement is fitted to this kind of situation. And in some cases, the do/while loop is easier to
implement in these real-world system applications compared to other looping statements.
init;
do {
statements;
inc/dec
} while (condition);
i++ or ++i
++n or n++
i-- or --i
--n or n--
130
The variable initialization (init) specifies the first value where the loop starts. The conditional
part specifies conditions to be evaluated or tested. If the condition is false, then no action is
taken and the program pointer proceeds to the next statement after the loop. If the conditional
expression is evaluated to be true, then all the statements within the body of the loop are
executed. This looping process (iteration) is repeated as long as the conditional expression
remains true. After each iteration, the incrementation/decrementation (inc/dec) part is
executed, then the conditional expression is reevaluated. In a simple for loop statement, the
initialization part is executed only once. This happens during the first time the program pointer
points to the loop. But in nested loop, the inner loop’s initialization part could be reexecuted
many times depending on the condition set at the outer loop. This will happen every time the
program pointer reevaluates the condition of the outer loop to True.
For the sake of simplicity and easy understanding about looping statement, we will focus our
discussion on the simple looping statement construct only.
A list box is an ideal way of presenting a list of data or choices to the user. In fact, the list
box is an effective way to present a large number of choices or data to the user in a
limited amount of space. The user can browse the data in the list box or select one or
more items for processing purposes. The process could be transferring the chosen items
from the list box to a cart (or a transfer of items from one list box to another) The transfer
can also be from a list box to a text box or to a combo box (we will discuss the combo
box, later). In the computerized grocery store system, the items could be the products
which the buyer can select and buy.
By default, the items in the list box are displayed vertically in a single column, although
we can set up multiple columns too. When the list of items or data is too long for the list
box, the Visual C# system will simply add a vertical scroll bar. With this, the user can
then scroll up and down or left to right through the list of items.
Let us now have our next example on list box control.
Example 1:
Design and develop a simple looping statement program that generates the given
sequence numbers using the For Next syntax.
Follow the given figure below in designing and developing the application system.
131
vbForLoop1
Button
Increment Now!
Loop 1
Loop 2
Loop 3 List Box
Loop 4
Loop 5
Note:
When the user clicks the Click Me! button, the Loop 1 up to Loop 5 numbers will be
generated and displayed at the List box.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csForLoop1. Now click the OK button.
4. Set the Form’s Text property to vbForLoop1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Increment Now!.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Double-click now the Increment Now! button on the Form to display the
button1_Click event method. Embed the following lines of code (in bold only) to
the method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Sample Output:
Figure 5.1a Generating sequence number using for loop syntax output
Explanation:
int nCounter;
Then we initialize our loop’s variable nCounter with 1, so that the first generated
sequence number is 1. Now we have the condition: nCounter<=5 , meaning the loop will
continue iterating as long as the value of variable nCounter is less than or equal to 5. The
role of the incrementation formula: nCounter++, means we add one to the value of
variable nCounter each time the loop iterates until such time its value becomes 6 which
in turn terminates the loop operation.
.
.
for (nCounter = 1; nCounter <= 5; nCounter++)
{
listBox1.Items.Add("Loop " + nCounter.ToString( ));
}
.
.
133
We will notice that since the loop is performed 5 times, the following statement within
the body of the loop will be executed 5 times:
We need to convert the numeric value of variable nCounter to its equivalent string value
by using the ToString( ) method as follows:
Tip:
The nCounter++ is a shortcut version of nCouter = nCounter + 1 incrementation formula, while the
nDecre- - is a shortcut version of nDecre = nDecre – 1.
Example 2:
Design and develop a simple looping statement program that generates the given
sequence numbers using the Do-While-Loop syntax.
Follow the given figure below in designing and developing the application system.
vbDoWhile1
Increment Now!
Button
Loop 1
Loop 2
Loop 3
Loop 4 List box
Loop 5
Note:
When the user clicks the Click Me! button, the Loop 1 up to Loop 5 numbers will be
generated and displayed at the List box.
134
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csDoWhile1. Now click the OK button.
4. Set the Form’s Text property to vbDoWhile1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Increment Now!.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Double-click now the Increment Now! button on the Form to display the
button1_Click event method. Embed the following lines of code (in bold only) to
the method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Explanation:
The initial value of nCounter variable is 1. So when the program pointer evaluates or
tests the condition:
nCounter<=5
it is evaluated to True, since the value of variable nCounter is less than 5. Because the
condition is evaluated to true, all statements within the body of the loop:
condition
are executed. The execution of all the statements within the body of the loop are repeated
until the evaluation of the condition becomes False, as you can observed at the code
below:
do {
listBox1.Items.Add("Loop "+nCounter.ToString( ) );
nCounter++;
} while (nCounter<=5);
You will notice that in the do/while loop solution, the condition is tested at the last part of
our loop. This ensures that even if the condition is evaluated or tested as False, the
statements within the body of the loop will be executed at least once.
Sample Output:
Figure 5.2a Generating sequence numbers using do-while Loop syntax output
Example 4:
Design and develop a simple looping statement program that generates the given inverse
sequence numbers using the for - loop syntax.
Follow the given figure below in designing and developing the application system.
136
vbForLoop2
Decrement Now!
Loop 5
Loop 4
Loop 3
Loop 2
Loop 1
Note:
When the user clicks the Decrement Now! button, the Loop 5 down to Loop 1 numbers
will be generated and displayed at the List box.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csForLoop2. Now click the OK button.
4. Set the Form’s Text property to vbForLoop2.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Decrement Now!.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Double-click now the Decrement Now! button on the Form to display the
button1_Click event method. Embed the following lines of code (in bold only) to
the method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
int nCounter;
Then we initialize our loop’s variable nCounter with 5, so that the first generated
sequence number is 5. Now we have the condition: nCounter>=1 , meaning the loop will
continue iterating as long as the value of variable nCounter is greater than or equal to 1.
The role of the decrementation formula: nCounter-- , means we decrease one to the value
of variable nCounter each time the loop iterates until such time its value becomes 0
which in turn terminates the loop operation.
.
.
for (nCounter = 5; nCounter >= 1; nCounter--)
{
listBox1.Items.Add("Loop " + nCounter.ToString( ));
}
138
.
.
We need to convert the numeric value of variable nCounter to its equivalent string value
by using the ToString( ) method as follows:
Sample Output:
Example 5:
Design and develop a simple looping statement program that generates the given inverse
sequence numbers using the Do-While-Loop syntax.
Follow the given figure below in designing and developing the application system.
139
vbDoWhile2
Decrement Now!
Loop 5
Loop 4
Loop 3
Loop 2
Loop 1
Note:
When the user clicks the Decrement Now! button, the Loop 5 down to Loop 1 numbers
will be generated and displayed at the List box.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csDoWhile2. Now click the OK button.
4. Set the Form’s Text property to vbDoWhile2.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Decrement Now!.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Double-click now the Decrement Now! button on the Form to display the
button1_Click event method. Embed the following lines of code (in bold only) to
the method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
int nCounter=5;
The initial value of nCounter variable is 5. So when the program pointer evaluates or
tests the condition: nCounter>=1, it is evaluated to True, since the value of variable
nCounter is greater than 1. Because the condition is evaluated to true, all statements
within the body of the loop are executed:
.
.
do {
listBox1.Items.Add("Loop "+nCounter.ToString( ));
nCounter--;
} while (nCounter>=1);
.
.
141
.
The execution of all the statements within the body of the loop are repeated until the
evaluation of the condition becomes False.
You will notice that in the do/while loop solution, the condition is tested at the last part of
our loop. This ensures that even if the condition is evaluated or tested as False, the
statements within the body of the loop will be executed at least once.
This time, we are pretty much familiar with how the looping statement works. We are
also confident that we can easily convert one looping statement syntax to another, such as
converting a for loop statement into while loop statement.
In our next example, we will explore on how to use looping statement in manipulating
objects or controls in a form. Let us start now.
What if we want to generate a sequence numbers by 5 (as in 5, 10, 15, 20 and so on)?
Consider the design specification below:
csIncrementby5
Increment by 5!
Button
5
10
15
20 List box
25
30
35
40
45
50
Sample Output:
Since we start from 5 and end at 50, we have this for loop line:
To convert the code to do while loop statement equivalent, we will have the following
solution:
What if we want to generate the number in reverse order? Consider the following design
specification:
143
Decrement by 5 Now!
50
40
35
30
25
20
15
10
5
Sample Output:
144
Here, we are using the decrementation process in the for loop line:
How can we convert the syntax into the do-while Loop statement? Here is its equivalent
code:
We have covered the looping statements with such simple yet useful and curiosity-
triggering presentation. This time, we will go further with looping statements’ many uses
and implementations. So, fasten now your seatbelt, as I drive you thru with our journey to
discover more programming techniques (not tricks, but techniques!).
145
An array is a special type of variable which can contain or hold one or more values of the
same data type with reference to only one variable name. In other words, the array
variable has a common name identifier and can hold many values at the same time,
provided that they have the same data type. In most programming languages, an array
variable can be distinguished through a pair of square brackets: [ ], and on specified
number inside them which is called an index. . In case of enumerated arrays, we can
distinguish its declaration through a pair of curly brackets: { }.
Here is the syntax of one-dimensional array:
Data_type ArrayName[ ]
Example 1:
strIDArray[0] = "Monkey";
strIDArray[1] = "Zebra";
strIDArray[2] = "Elephant";
strIDArray[3] = "Eagle";
strIDArray[4] = "Crocodile";
Example 2:
To understand how array variable works, we will have a running example about it, in our
succeeding examples. Are you now excited to learn how array works? I guess so.
146
Tip:
In Visual Basic programming language, an array variable can be distinguished through a pair of open
and close parentheses: ( ). The number inside the parentheses is called an index or element. In case of
enumerated arrays, we can distinguish its declaration through a pair of curly brackets: { }. Here is the
syntax of a simple one-dimensional array: Data_type ArrayName[index]
Example 6:
Design and develop a simple program that demonstrates how to use the for each loop
syntax that display each item in an array with a string data.
Follow the given figure below in designing and developing the application program.
vbForEach9
My Little Zoo!
Monkey
Zebra List box
Elephant
Eagle
Crocodile
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csForEach9. Now click the OK button.
4. Set the Form’s Text property to vbForEach9.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Click Now!.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
147
7. Double-click now the Click Now! button on the Form to display the button1_Click
event method. Embed the following lines of code (in bold only) to the method:
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
.
.
.
And here is how we can assign an individual string value to the array variable:
strIDArray[0] = "Monkey";
strIDArray[1] = "Zebra";
strIDArray[2] = "Elephant";
strIDArray[3] = "Eagle";
strIDArray[4] = "Crocodile";
Though, the index number of an array variable starts technically at 0, the declaration of
strIDArray = new String[5] can hold only five values, which starts at strIDArray[0] and
ends at strIDArray[4]. Putting an strIDArray[5] with its corresponding array value to the
list, will surely generate a runtime error during compilation of our code, because this is
already beyond the bound of our array variable’s maximum allowable values to be stored.
Tip:
In Visual Basic, we declare an array variable like in the following code:
The index number of an array variable starts technically at 0, therefore, an array declaration of
intIDArray(4) can hold five values. That is the case here in our example, wherein we have five animals
stored in our array variable.
As you could noticed, the Visual C# has a different way of how it declares an array variable and the
number of its array index. In our C# example, the array maximum index is 5, while in Visual Basic, the
array maximum index is 4. Yet, they are both can contain five maximum array values. In other words, the
maximum index number of 4 in Visual Basic means we can store a maximum of 5 array values, while in
C#, we can store a maximum of 5 array values if our maximum index number is 5.
So be very vigilant about this big difference. Otherwise, your data could overflow the maximum array
value allowed to be stored in your array variable.
We apply here the for-each loop, because we want to easily loop over elements in an
array, as you could observe in our code below:
Actually, by using the for-each loop, we can also easily loop over the items in a
collection of objects (or controls). We will learn this one later.
Example 10:
Design and develop a simple program that demonstrates how to use the For Each loop
syntax that display each item in an array with an integer data.
Follow the given figure below in designing and developing the application program.
vbForEach8
6
12 List box
14
9
4
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csForEach8. Now click the OK button.
4. Set the Form’s Text property to vbForEach8.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to List Now!.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Double-click now the List Now! button on the Form to display the button1_Click
event method. Embed the following lines of code (in bold only) to the method:
private void button1_Click(object sender, EventArgs e)
{
listBox1.BeginUpdate();
150
8.Build and execute the application system by clicking the Start debugging icon (or press
F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
intIDArray[0] = 6;
151
intIDArray[1] = 12;
intIDArray[2] = 14;
intIDArray[3] = 9;
intIDArray[4] = 4;
Though, the index number of an array variable starts technically at 0, the declaration of
strIDArray = new String[5] can hold only five values, which starts at strIDArray[0] and
ends at strIDArray[4]. Putting an strIDArray[5] with its corresponding array value to the
list, will surely generate a runtime error during compilation of our code, because this is
already beyond the bound of our array variable’s maximum allowable values to be stored.
We apply here the for-each loop, because we want to easily loop over elements in an
array, as you could observe in our code below:
.
.
.
foreach (int intArrayItem in intIDArray)
{
listBox1.Items.Add(intArrayItem.ToString());
}
.
.
Actually, by using the for-each loop, we can also easily loop over the items in a
collection of objects (or controls). Our next example will be about this one. I promise.
Example 11:
Design and develop a simple program that demonstrates how to use the For Each loop
syntax that counts how many objects are there in a Form.
Follow the given figure below in designing and developing the application program.
csForEach1
Count Now!
Button
There are: 8 objects in this form!
Text box 1
Text box 2
Radio Button 1
Radio button
Check Box 1
Check box
Can you count them?
152
Note:
When the user clicks the Click Me! button, the value 8 should appear at the Text box
which in turn, completes the message, such as the following:
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csForEach1. Now click the OK button.
4. Set the Form’s Text property to vbForEach1.
5. Click, drag and drop a Button from the Toolbox to add it into the Form, and set its
Text property to Count Now!.
6. Click, drag and drop a Label, then set its Text property as There are: .
7. Then, click, drag and drop a Text box (in between two labels).
8. Click, drag and drop another Label and set its Text property as objects in this
form!
9. Now click, drag and drop another Text box, then a Radio button, and finally a
Check box into the Form.
10. The last control to click, drag and drop is the last Label which you have to set its
Text property as Can you count them?
11. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
153
Sample Output:
Figure 5.9a Display and Count the Objects in the form output
Explanation:
First, we declare a variable nIterate as an integer data type and initialized its value with 0
(zero). Here are their syntax:
int nIterate = 0;
You will notice that we declare a Control variable which we named oObject within our
for-each loop statement with the following syntax:
The nIterate variable will simply increment by 1 (one) each time the loop iterates. After
the loop iterates, the nIterate variable contains the latest incremented value which will
depend on how many times the loop iterates. In this case, the loop iterates 8 (eight) times
since there are eight objects or controls that are found in our form. In other words, the
nIterate variable contains the value of 8 (eight). Finally, we displayed the number of
objects found in the form with the following statements:
Text box 1
textBox1.Text = nIterate.ToString( );
and the nIterate variable contains a value of 8 which in turn will be displayed inside Text
box 1.
Button - 1
Labels - 3
Text boxes - 2
Radio button - 1
Check box - 1
----------
A total of 8
Example 12:
Design and develop a simple program that demonstrates how to preload a collection of
items to a List box at run time. Follow the given figure below in designing and
developing the application program.
csListbox1
Preloaded Items:
Milan
Paris
Madrid
Tokyo List box
Manila
New Delhi
Kuala Lumpur
San Francisco
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox1. Now click the OK button.
4. Set the Form’s Text property to vbListbox1.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Preloaded Items.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
8. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
156
Figure 5.10a Preload the items into the List Box output
Explanation:
In this simple example about List box, we just simply pre-loaded the List box with items
which we want to display. So we just use the following code:
listBox1.Items.Add("Milan");
listBox1.Items.Add("Paris");
listBox1.Items.Add("Madrid");
listBox1.Items.Add("Tokyo");
listBox1.Items.Add("Manila");
listBox1.Items.Add("New Delhi");
listBox1.Items.Add("Kuala Lumpur");
listBox1.Items.Add("San Francisco");
The List box has built-in methods for adding, removing and retrieving collection of items
or data. In this case, we applied the built-in method for adding an item into the List box
using the Items.Add method. Now how about choosing an item from the List box and
display it into the text box? Let us have an example about this particular requirement.
Example 13:
Design and develop a simple program that demonstrates how to preload the List box with
items. When the user chooses an item at the list box by double-clicking it, that particular
item will be displayed at the text box. Follow the given figure below in designing and
developing the application program.
157
vbListbox2
List of Products:
Chicken
Beef
Pork
List box
Vegetables
Fish
Squids
Noodles
Fruits
Figure 5.12 Displaying an item from List box into Text box
Note:
When the user clicks the Beef at the list box, the item “Beef” will be displayed at the text
box.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox2. Now click the OK button.
4. Set the Form’s Text property to vbListbox2.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to List of Products:.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Next, click, drag and drop a Text box from the Toolbox to add it into the Form.
8. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
listBox1.Items.Add("Fish");
listBox1.Items.Add("Squids");
listBox1.Items.Add("Noodles");
listBox1.Items.Add("Fruits");
}
10. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Figure 5.11a Displaying an item from List box into Text box output
Explanation:
In this example, the user chooses the Beef product by double-clicking it using the mouse.
That is why the product Beef is displayed at text box 1 .
You will notice that we initialize the list box and text box as empty using the empty
string value. Here is the code that accomplishes the task:
Then we preloaded the list box with the following list of products using the AddItem
method:
And finally, we display the selected item into the text box with the following code:
The Text property of the List box returns the value of the selected item. This is the reason
why the selected item is displayed at text box 1.
Example 14:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box and as well as add an item into the List box which is entered by
the user from the text box. The program also will be able to remove all the items one by
one, starting from the top down to the bottom. Follow the given figure below in designing
and developing the application program.
vbListbox3
Note:
When the user types the “Item 5” at the text box and press the Enter key, the “Item 5”
should be added at the list box. Now if the user clicks the Remove button, the Item 1 will
be removed from the list box. And if the user continues to click the Remove button, the
next item that follows will be removed from the list box until the list box becomes empty.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox3. Now click the OK button.
4. Set the Form’s Text property to vbListbox3.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Add Item to the List box:.
6. Now click, drag and drop a Text box, then a Button which Text property is set as
Add to the List.
7. This time, you have to add another Button where you have to set its Text property
to Remove from the List.
8. Click, drag and drop a List box from the Toolbox to add it into the Form.
9. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
10. Double-click the Add to the List button control to display the Add_Click event
method. Embed the following lines of code (in bold only) to the method:
textBox1.Focus();
}
11. Double-click the Remove from the List button control to display the
Remove_Click event method. Embed the following lines of code (in bold only) to
the method:
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.Items.Count== 0)
MessageBox.Show("No More Item!");
else
listBox1.Items.RemoveAt(0);
}
12. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Figure 5.12a Adding and Removing an Item in the List box output
Explanation:
In this example, we preloaded the list box with four items. It can be accomplished by the
following code:
{
listBox1.Items.Add("Item 1");
listBox1.Items.Add("Item 2");
listBox1.Items.Add("Item 3");
listBox1.Items.Add("Item 4");
textBox1.Text = " ";
}
We also initialize our text box 1 with an empty string so that when we run our program,
the text box is empty. This is the reason why we have this code at the Form_Load
method:
You will notice, that in our figure, the user types the “Item 5” to be added into the List
box. The user should click the Add to the List button to confirm the input data. Once the
Add to the List button is clicked, the “Item 5” will be added to the preloaded items of the
list box. We can accomplish the task with the following code:
Remember that after we add the item into the list box, we have to clear out the text box to
clear the way to another input to be typed by the user. So we initialize again the text box
1 with an empty string. Then we have to set the focus of the cursor at the text box, so that
the user can type right away the next item to be added. We can accomplish the task with
the following code:
Now if we want to remove the items in the list box, starting from the top, down to the
bottom, we will have to click the Remove from the List button to do it. The code that can
accomplish this task is the following:
if (listBox1.Items.Count== 0)
MessageBox.Show("No More Item!");
else
listBox1.Items.RemoveAt(0);
}
163
You will notice that we remove the item starting from zero (0), so that the item which is
located at location zero (means the first item in the list box) will be removed. And any
item which is located on that location is a candidate for removal. When the list box is
running out of items, we have to display a warning message using the Message Box
statement. To know if the list box is empty, we have the command:
.
.
.
if (listBox1.Items.Count== 0)
MessageBox.Show("No More Item!");
else
listBox1.Items.RemoveAt(0);
.
.
because the Items.Count is the property we use to determine the number of items in the
List box. If it equals to zero, then the list box is already empty. This is the time that we
will display the message: “No More Item!”.
Removing an item from the top to bottom is not really a good idea. First, when we want
to remove an item, we usually select one or two from the list of items presented. So the
program above cannot satisfy on what we want. With this reason, we will come up with
an example that will accomplish the task. Here it is!
Example 15:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The user should be able to remove a selected item on the list, one
at a time. Follow the given figure below in designing and developing the application
program.
vbListbox4
Note:
When the user selects by clicking an item at the List box, that particular item must be
deleted from the displayed list.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox4. Now click the OK button.
4. Set the Form’s Text property to vbListbox4.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Preloaded with Items.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Lastly, click, drag and drop another Label and set its Text property to Click an
Item to Remove it from the List!
8. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
10. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
165
Sample Output:
Explanation:
First, we load the list box with items, using the following code:
It’s seems so simple, isn’t it? Well, because we know how to do it. Let us dissect the code
further. We apply here the Items.Remove method to remove the selected item from the list
box. Now to get exactly the currently selected item, we use the SelectedItem property.
166
What if we want to highlight first, an item before confirming to delete it using a Button?
That is a good idea to act! Consider the graphical user-interface (GUI) design in our next
example.
Example 16:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The program should be able to remove a selected item on the list,
one at a time but with a confirmation using a button. Follow the given figure below in
designing and developing the application program.
vbListbox5
Click to select:
Sizzling beef
Pork tonkatsu
Chicken torikatsu
Fish tempura List box
Miso soup
Coffee jelly
Yukiudon
Gyoza
Remove
selected/highlighted
Item
Button
Figure 5.14 Removing a selected item using Button
Note:
The user should select first an item at the List box by highlighting it, before the user can
finally remove it by clicking the Remove selected/highlighted Item button.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox5. Now click the OK button.
4. Set the Form’s Text property to vbListbox5.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Click to select.
167
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Lastly, click, drag and drop a Button, then set its Text property to Remove
Selected/Highlighted Item.
8. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
10. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
168
Explanation:
When the user selects an item in the list box by highlighting it through a mouse-click,
that item is selected to be deleted. So the user will confirm to remove it finally by
clicking the Remove Selected/Highlighted Item Button. Now what we would do in our
program is to transfer simply the code of the method ListBox1_DblClick( ) to the
Button1_Click( ) method this way:
See? The modification in our program is so easy! Well, if we know how to do it, buddy.
What we need is a simple analysis and apply our analysis to the program we create.
There are times that when we select an item, we want to display that selected item into
another list box. We will do this kind of program in our next example. Are you ready?
Example 17:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The program should be able to display one or more selected items
on another list box. Follow the given figure below in designing and developing the
application program.
vbListbox6
Hamburger
Cheeseburger
Chickenburger List box 1
Mashed Potato
Spaghetti
Honeybun
Macaroni Salad
Cherry Pie
Hamburger
Spaghetti
Honeybun List box 2
169
Figure 5.17 Display one or more items to the other list box
Note:
When the user selects by clicking an item at the List box 1, that particular item must be
displayed at the List box 2.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox6. Now click the OK button.
4. Set the Form’s Text property to vbListbox6.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Click an item to display into List box 2.
6. Click, drag and drop 2 List boxes from the Toolbox to add them into the Form.
7. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Hamburger");
listBox1.Items.Add("Cheeseburger");
listBox1.Items.Add("Chickenburger");
listBox1.Items.Add("Mashed Potatoe");
listBox1.Items.Add("Spaghetti");
listBox1.Items.Add("Honeybun");
listBox1.Items.Add("Macaroni Salad");
listBox1.Items.Add("Cherry Pie");
}
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
170
Sample Output:
Figure 5.17a Display one or more items to the other list box output
Explanation:
Here in our example, the user selected and double-clicked the items “Cheeseburger”,
“Spaghetti”, and “Honeybun” in list box 1. That is why they are displayed at list box 2.
When the user selects and double-clicks other collection of items from list box 1, this
particular collection of items will be displayed at the list box 2.
As what we have done before, we preloaded our list box 1 with items on it, using the
following code:
Next, we add the selected items from List box 1 into List box 2, using the following
code:
{
//Add item to List box 2
listBox2.Items.Add(listBox1.Text);
}
Example 18:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The program should be able to transfer one or more selected
items on another list box. Follow the given figure below in designing and developing the
application program
vbListbox7
Java
C++
Perl
Basic
FoxPro List box 1
Pascal
COBOL
HTML
XML
Fortran List box 2
Figure 5.18 Transfer one or more items to the other list box
Note:
When the user selects by clicking an item at the List box 1, that particular item must be
transferred into List box 2.
172
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox7. Now click the OK button.
4. Set the Form’s Text property to vbListbox7.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Click an Item to transfer to other List box:.
6. Click, drag and drop 2 List boxes from the Toolbox to add them into the Form.
7. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
10. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Figure 5.18a Transfer one or more items to the other Listbox output
Explanation:
Here in our example, the user clicks the items “XML” and “Fortran” in list box 1. That is
why these items are transferred to list box 2, as what we can see in the figure. Now if the
user double-clicks again an item in list box 1, this particular item will be transferred to
list box 2. In the case where the user double-clicks an item in list box 2, this particular
item will be transferred to list box 1. You can try it, to see for yourself how this program
works.
As what we have done previously in our program, to preload the list box with items upon
running, we use the following code:
listBox1.Items.Add("COBOL");
listBox1.Items.Add("HTML");
listBox1.Items.Add("XML");
listBox1.Items.Add("Fortran");
}
Then we embed the following code at List box 1 object and in its Double-click event:
to add the selected items from list box 1 into list box 2. At the same time, we have to
remove that selected item from the list box 1 using the Items.Remove method and the
SelectedItem property of the List object.
You will notice that this code is similarly applied to List box 2, as what we can see here
in the following code that can be found at List box 2 method:
We did this so that vice versa, they will work the same such as when we transfer an item
from list box 1 into list box 2, the selected item will also be deleted from list box 1. Now
if we want to transfer an item from list box 2 into list box 1, the selected item will also be
deleted from list box 2.
In the next example, we will know what particular item is currently selected by the user
at the List box. Then we will confirm it by displaying a description of that particular item
at the text box.
Example 19:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The program should be able to get the value of the currently
selected item in the list box. The selected item should display its corresponding
175
description at the text box. Follow the given figure below in designing and developing
the application program:
vbListbox8
List of Countries:
Germany
Philippines
Singapore
Japan
Alaska List box
California
Italy
France
Alabama
Brazil
Venezuela
Description:
Germany is in Europe Text box
Note:
When the user clicks one of the items in the List box, the description of that item is
displayed at the text box.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox8. Now click the OK button.
4. Set the Form’s Text property to vbListbox8.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to List of Countries:.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Click, drag and drop a Text box from the Toolbox to add it into the Form.
8. Lastly, click, drag and drop a Label , then set its Text property to Description:.
9. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
176
11. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
In this example, the user selected the item Germany in the list box, thus the description
displayed at the text box is “Germany is in Europe”. Now when the user selects another
item, its corresponding description will also be displayed at the text box. The code behind
how this one happens is here below:
{
textBox1.Text = " ";
textBox1.Text = "Alabama is in North America";
}
else if (listBox1.Text == "Brazil")
{
textBox1.Text = " ";
textBox1.Text = "Brazil is in Latin America";
}
else if (listBox1.Text == "Venezuela")
{
textBox1.Text = " ";
textBox1.Text = "Venezuela is in Latin America";
}
using the conditional else if statement. The Text property of the list box item always
corresponds to a list item a user selects at run time. In other words, the Text property
contains the currently selected item in the list box. The else if code above checks to see if
“Germany” has been selected by the user, and if so, displays the description in the text
box.
You will notice also that every time we display another description at the text box, we
will initialize it with an empty string. We did this to clear entirely the text box, before
another description will be displayed. Otherwise, the previous string which has a longer
length than the present one might display the last part of it (as though it is concatenated to
the new string).
In our next example, we will present a better idea in presenting a list of items and in how
to add or remove them easily with confirmation using Buttons. Here it is now!
Example 20:
Design and develop a simple program that should apply the Items.Add, Items.Remove,
and Clear methods with the SelectedIndex and Items.Count properties to add, remove and
clear the list entries in the List box at run time. Follow the given figure below in
designing and developing the application program:
180
vbListbox9
Item to add:
Delete
Buttons
List box
Clear
Exit
No. of Items:
Text box 2
Figure 5.20 Adding, Removing and Clearing an item in the list box
Note:
The user will enter an item first at text box 1 and then clicks the Add button to add the
inputted item in the List box. Now when the user wants to remove an item from the list,
the user should highlight it first, then clicks the Remove button to finally delete it.
Clicking the Clear button will wipe out all the items in the List box.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox9. Now click the OK button.
4. Set the Form’s Text property to vbListbox9.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Item to add:.
6. Click, drag and drop a Text box (Text box 1) from the Toolbox to add it into the
Form.
7. Click, drag and drop a List box from the Toolbox to add it into the Form.
8. Click, drag and drop another Label, then set its Text property to No. of items:.
9. Click, drag and drop another Text box (Text box 2) from the Toolbox to add it
into the Form.
181
10. This time, click, drag and drop 4 Buttons and set their respective Text property as
Add, Delete, Clear, and Exit, and their respective Name property as btnAdd,
btnDelete, btnClear, and btnExit, like the summary of their property settings
below:
It is very hard to track what Button is currently in use in our program because there
are four of them. So we have to assign an object name for each Button to easily
identify them inside our code. We prefix the object or control name with the word btn
to signify that it is a button control. This prefixing technique is also important aside
from the object identification, it is also used so that there is no conflict with existing
built-in object name, such as in the case of the name of the built-in object Exit in
Visual C#. Without the use of the prefixing technique, assigning our button with the
Name as Exit will produce an error in the design stage. You can try it yourself to
know how this would happen.
You will assign the object name and its respective text properties at the Property box.
11. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
13. Double-click now the Text box 1 on the Form to display the
TextBox1_TextChanged event method. Embed the following lines of code (in
bold only) to the method:
14. Double-click now the Add button on the Form to display the btnAdd_Click event
method. Embed the following lines of code (in bold only) to the method:
15. Double-click now the Delete button on the Form to display the btnDelete_Click
event method. Embed the following lines of code (in bold only) to the method:
16. Double-click now the Clear button on the Form to display the btnClear_Click
event method. Embed the following lines of code (in bold only) to the method:
private void btnClear_Click(object sender, EventArgs e)
{
//Empty the List box
listBox1.Items.Clear();
//Disable Delete button
btnDelete.Enabled = false;
//Display the number of items
//to the text box 2
textBox2.Text = Convert.ToString(listBox1.Items.Count);
}
17. Double-click now the Exit button on the Form to display the btnExit_Click event
method. Embed the following lines of code (in bold only) to the method:
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
18. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
184
Figure 5.18a Adding, Removing and Clearing an item in the list box output
Explanation:
Our program is a little bit long and complex. To understand it, demands patience and
tenacity. We will dissect it so that we can divide the complexity into manageable pieces
and hopefully we can conquer it piece by piece. Let us start it now. First, we will learn
how the code behind the Button works, because this is the first object that we will click
with, after entering an item at the text box and finally add it into a List box. Here is its
code below:
You will notice that we will simply add the item entered at text box 1 into the List box
with the following code:
listBox1.Items.Add(textBox1.Text);
After adding the item into the list box, we will clear the text box for another item to be
entered by the user. This can be accomplished simply with the following code:
Now we need to set the focus of the cursor at text box 1, so that the user can keep on
typing any items she wants to enter (otherwise the cursor will position itself at the next
object that follows the text box, which we don’t want to happen). Here is the code that
can accomplish that task:
textBox1.Focus( );
Finally, we can determine how many items are already added at the List box using the
Items.Count property of List box object. We will display the number of items at text box
2 using the following code:
textBox2.Text = Convert.ToString(listBox1.Items.Count);
This time, we will dissect the Delete button and study how the code behind it works. Here
is its code:
If we want to know the position of the selected item in a list box, we use the
SelectedIndex property. This property sets or returns the index of the currently selected
item in the List box and is available only at run time. The value of this property is 0 if
the first or top item in the List box is selected. It is 1 if the next item down is selected,
and so on. The value of SelectedIndex is -1 (negative one) if no item is selected.
Here we test if the list box contains any item with the following code:
Ind = listBox1.SelectedIndex;
if (Ind >= 0)
We know that the first or top item has a List index number of 0, therefore if the List index
of a list box is greater than or equal to zero, it has an item or items on it. So we can delete
it. We can delete the selected item using the following code:
listBox1.Items.RemoveAt(Ind);
where Ind is the List index number and at the same time the currently selected item in the
List box. This is actually the item selected by the user by highlighting it.
After removing an item at the list box, we need to update the number of items remaining
to text box 2 with the following code:
textBox2.Text = Convert.ToString(listBox1.Items.Count);
Remember that the Items.Count property returns the number of items in a list box, so
that’s what we are using here to be stored at text box 2.
Now if the list box is running out of items inside it, we should generate a warning sound
using the Beep command. And finally we have to dim the Delete Button, meaning it is
disabled so that the user can no longer click it or use it, using the following code:
expression
If the above expression is False, then the button Delete will be disabled. In other words,
the Delete button is like being hard-coded with the following code:
btnDelete.Enabled = false
Next, we will examine the code behind the Clear Button. Here is it!
Using the Clear property of the list box, we can wipe out all the items in the list box.
Since the list box is now empty, we have to disable the Button Delete so that the user is
restricted to use or click it. At the same time, we have to update text box 2 with the
number of items in the list box. In this case, since all the items are wiped out, the number
0 is displayed at text box 2. Try it!
This time, we will go to the code behind the Exit Button. We have here its code below:
It’s very simple, isn’t it? The Close( ) method simply closes the current object (Control)
which is in this case - is the Form.
Now we will examine the code behind the text box 1 object. Here is its code:
if (nLen > 0)
{
// Enable the Add button if at least
// one character in the text box 1
btnAdd.Enabled = true;
}
}
Here, we simply enable the button Add if the text box 1 contains at least one character.
Meaning the user is at least entering something in text box 1 which triggers the program
to enable the Add button. Enabling the Add button makes it available for the user to click
it.
Now we need to know also that the user has selected an item in the list box. To determine
it, we put the following code in the application program:
The expression above must be evaluated to True for the button Delete to be enabled,
otherwise that Button is dimmed (meaning disabled), thus the user cannot use or click it.
Now remember that in our previous discussion, the -1 (negative one) means there is no
currently selected item in the list box. So if the SelectedIndex property is not equal to -1
(negative one), then the user has selected an item.
Here in our code below, we simply initialize the Text box and List box with an empty
string so that at run time, they contain nothing (or simply they are both blank).
The code above will be executed upon loading the application program. Finally, we have
ended our lengthy and very challenging discussion. I hope you enjoyed it, buddy!
What we have is a program that can select an item at the List box, one at a time. How
about a program that can select two or more items in the list box at once? That will be our
topic in the next example. Are you now excited to learn it?
Example 21:
Design and develop a simple program that should be able to select two or more items in
the List box at once and be able to transfer the collection of selected items to another list
box simultaneously. Follow the given figure below in designing and developing the
application program:
189
vbListbox10
Exit
List box 2
Figure 5.21 Selecting and Transferring multiple items at the same time
Note:
The user will first click the first item to select, then use the Shift and Arrow keys to select
other multiple items at the list box 1. Then clicking the Transfer button will copy the
collection of selected items into the list box 2.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox10. Now click the OK button.
4. Set the Form’s Text property to vbListbox10.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Press Shift and Arrow keys.
6. Click, drag and drop another Label (to be used in continuing the text) and set its
Text property to select multiple items:.
7. Click, drag and drop 2 List boxes from the Toolbox to add them into the Form.
8. This time, click, drag and drop 3 Buttons and set their respective Text property as
Transfer, Clear, and Exit, while their respective Name property as
btnTransfer, btnClear, and btnExit, like the summary of their property settings
below:
190
It is very hard to track what Button is currently in use in our program because there
are three of them. So we have to assign an object name for each Button to easily
identify them inside our code. You will assign the object name and its respective Text
property at the Property box.
9. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
btnTransfer.Enabled = true;
}
11. Double-click now the Transfer button on the Form to display the
btnTransfer_Click event method. Embed the following lines of code (in bold
only) to the method:
12. Double-click now the Clear button on the Form to display the btnClear_Click
event method. Embed the following lines of code (in bold only) to the method:
13. Double-click now the Exit button on the Form to display the btnExit_Click event
method. Embed the following lines of code (in bold only) to the method:
14.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Warning!
Don’t forget to set the Multi-Select property of list box 1 with the 2-Extended setting. It is
very important, otherwise our program will not run on our intended purpose.
192
Sample Output:
Figure 5.19a Selecting and Transferring multiple items at the same time output
Explanation:
In this program, we preselected three items, they are items 1, 3, and 5 at the top of the list
in our list box. To accomplish this task, we use the following code:
We are using here the SetSelected( ) property which is a Boolean array containing the
selection status of a list box - to determine which items are preselected. Each entry in the
array corresponds to a list item and is set to True if the item is selected, or False if it is
not selected. After the user selects items from the list box 1, each array entry is checked
to see if it is set (meaning it is True). If so, the entry is added to the list box 2. You can
try clicking the Transfer Button to see the effect of these preselected items. You will see
that the three pre-selected items in the list box 1 will be transferred or copied into list box
2.
Next, we will examine the code behind the Transfer Button:
In the code above, we apply the foreach loop statement to determine if the items in list
box 1 are selected. This loop statement will navigate the entire content of list box 1 and
check if the item or items are selected. If so, then they will be copied to list box 2. We
also set the Clear button to True so that the user can click it. Clicking the Clear button
will wipe out all the items in list box 2.
Now let us examine the code behind the Clear button:
Using the Clear property of the list box, we can wipe out all the items loaded at the list
box at once. We need also to disable the Clear button after we wiped out all the items, so
that the user is restricted to click it. We can accomplish this by setting its value to False.
If the user would like to select again an item at List box 1, we need to re-enable the
Transfer button by doing this code:
The Close( ) method simply closes the current object (Control) which is in this case is the
Form.
The words combo box are derived from the words “combination box”, meaning it
combines the features of both a text box and a list box. This control allows the user to
select an item either by typing text into the combo box, or by selecting it from the list. In
other words, it allows us to select a predefined item from a list or to enter a new item
which is not in the list. Like a list box, a combo box present a list of choices to the user. If
the number of items exceeds what can be displayed in the combo box, scroll bars will
automatically appear on the control. We can then scroll up and down or left to right
through the list to navigate it.
A potential problem with a list box is that in some situations, you are stuck with the
entries displayed. You can’t directly edit an item in the list or select an entry that’s not
already there. Though its big advantage compared to combo box is that if you want to
restrict the user, then a list box is best suited in this situation. While the strength of a
combo box is that it takes less room on a form than a normal list box, because the full list
is not displayed until the user clicks the down arrow. In other words, a combo box can
easily fit in a small space where a list box would not fit. Moreover, a combo box contains
an edit field, so choices not on the list can be typed in this field by the user.
In most program development situations, a combo box is appropriate when there is a list
of suggested choices, and a list box is appropriate when you want to limit input to what is
on the list.
195
Example 22:
Design and develop a simple application system that preloads a combo box with items.
The user can select an item from the list to be displayed at the text box. Follow the given
figure below in designing and developing the application program:
vbCombobox1
Note:
When the user selects an item at the Combo box by clicking on it, this item will be
displayed at the text box. The user must click the down arrow (found at the right corner
of the combo box) to be able to see the preloaded list of items .
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csCombobox1. Now click the OK button.
4. Set the Form’s Text property to vbCombobox1.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Just click to choose:.
6. Click, drag and drop a Combo box from the Toolbox to add it into the Form.
7. Click, drag and drop another Label and set its Text property to The Item you
choose is:.
8. Next, click, drag and drop a Text box from the Toolbox to add it into the Form.
196
9. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
11. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
197
Explanation:
In this simple example about combo box, we just simply pre-loaded the Combo box with
items which we want to view, select and finally display into the text box. So we just use
the following code:
You will notice that we initialize the combo box with a “Chicken” as its first string value
and text box as empty by storing an empty string into it. Then we preloaded the combo
box with the list of items using the Items.Add method.
And finally, we display the selected item into the text box with the following code:
We need to reinitialize the text box with an empty string every time another item is
selected, so that the previous displayed item will be completely cleared before the new
item would be displayed. Otherwise, some parts of the previous item with longer string
will appear as though it is concatenated to the new item displayed.
The SelectedItem property of the Combo box control returns the value of the selected
item. This is the reason why the selected item is displayed at text box 1.
198
Example 23:
Design and develop a simple program that demonstrates how to preload a collection of
items into the combo box. The program should be able to display one or more selected
items on a list box. Follow the given figure below in designing and developing the
application program.
vbCombobox5
Products bought:
List box
Figure 5.26 Display one or more items to the other list box
Note:
When the user selects an item at the Combo box by clicking it, this item will be displayed
at the list box. The user must click the down arrow (found at the right corner of the
combo box) to be able to see the preloaded list of items.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csCombobox5. Now click the OK button.
4. Set the Form’s Text property to vbCombobox5.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Choose a product to buy:.
6. Click, drag and drop a Combo box from the Toolbox to add it into the Form.
7. Click, drag and drop another Label and set its Text property to Products bought:.
8. Next, click, drag and drop a List box from the Toolbox to add it into the Form.
199
9. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
11. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
200
Figure 5.21a Display one or more items to the other list box output
Explanation:
In this simple example about combo box, we just simply pre-loaded the Combo box with
items which we want to view, select, and finally display into the list box. So we just use
the following code:
You will notice that we initialize the combo box with a “Banana Split” as its first string
value and text box as empty by storing an empty string into it. Then we preloaded the
combo box with the list of items using the Items.Add method.
And finally, we display the selected item into the list box with the following code:
The SelectedItem property of the Combo box control returns the value of the selected
item. This is the reason why the selected item is displayed at the list box.
There is no need for us to clear the list box, since we just simply add an item into it. That
is the reason why there is no reinitialization every time a user selects an item at the
combo box (unlike using a text box to display the item selected).
Example 24:
Design and develop a simple program that demonstrates how to preload a collection of
items into the combo box. The program should be able to display one or more selected
items on a list box with a confirmation using the button. Follow the given figure below in
designing and developing the application program.
vbCombobox6
Products to Buy:
Add to List Button
List box
Figure 5.27 Display one or more items to the other list box
Note:
When the user selects an item at the Combo box and would like to buy it, she has to click
the Add button to confirm it. Clicking the Add button will display the selected items at
the list box.
202
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csCombobox6. Now click the OK button.
4. Set the Form’s Text property to vbCombobox6.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Products to buy:.
6. Click, drag and drop a Combo box from the Toolbox to add it into the Form.
7. Click, drag and drop a Button and set its Text property to Add to List.
8. Click, drag and drop another Label and set its Text property to List of Products
bought:.
9. Next, click, drag and drop a List box from the Toolbox to add it into the Form.
10. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
11. Double-click now the Add to List button on the Form to display the
Button1_Click event method. Embed the following lines of code (in bold only) to
the method:
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(comboBox1.Text);
}
12. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
203
Figure 5.22a Display one or more items to the other list box output
Explanation:
Again, we preloaded our combo box with items using the following code:
When the user selects an item at the combo box and clicks the Add to List Button, that
particular item will be displayed at the list box. The code that accomplishes this task is
the following:
I think we have accomplished a lot of things in the previous examples, and it’s time for us
to go to the next chapter for another topic to learn more. Are you ready for the next
chapter? But before that, we will have first our Lab Activity Test that will test our ability
to comprehend and understand the examples presented in this chapter.
As we end this chapter, I would like to introduce a topic that probably trigger’s your
curiosity why our examples here does not introduce a this.listBox1.DoubleClick event
method. Probably, you would noticed that in my Introduction To Visual Basic 2012
Programming book, I extensively present this event method. The main reason for this is
that, in C#, this method requires different way of accomplishing it. As I observed, one
way of accomplishing this event method is to write it directly into the
InitializeComponent( ) part of our code. To expound my presentation about this issue, I
have here some examples for you to try, before you’ll go to your Lab Activity Test 4.
This is for the sake of curiosity, only.
I have here three examples, which will demonstrate how to hardcode the
this.listBox1.DoubleClick event method!
Example 1:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The user should be able to remove a selected item on the list, one
at a time, by selecting and double-clicking it. Follow the given figure below in designing
and developing the application program.
csListbox4a
Note:
When the user selects and double-clicks an item at the List box, that particular item must
be deleted from the displayed list.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox4a. Now click the OK button.
4. Set the Form’s Text property to csListbox4a.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Preloaded with Items.
6. Click, drag and drop a List box from the Toolbox to add it into the Form.
7. Lastly, click, drag and drop another Label and set its Text property to Double
click an Item to Remove it from the List!
8. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
9.Let us now hard-code our listBox1_DoubleClick event method (by emulating the
syntax of listBox1_SelectedIndexChange( ) event method. It is very easy to get this
blank method. You just simply double-click the List box control in our Form. Can you
see now the blank event method?
}
private void listBox1_DoubleClick(object sender, EventArgs e)
206
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
.
.
.
private void InitializeComponent()
{
.
.
.
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(86, 38);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 121);
this.listBox1.TabIndex = 1;
this.listBox1.SelectedIndexChanged += new
System.EventHandler(this.listBox1_SelectedIndexChanged);
this.listBox1.DoubleClick += new
System.EventHandler(this.listBox1_DoubleClick);
//
// label2
//
.
.
.
}
11.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Tip:
To alternatively and easily go right up there at the InitializeComponent( ) part of our program, you just
simply delete our blank event method which is the following code:
}
207
Then after deleting it, compile our program by clicking the Start debugging icon or the green arrow icon
(color green). This will trigger a runtime error, which in turn, will brought us right at the heart of the
InitializeComponent ( ) part of our program. Now, you just simply put a comment before the initialization
code of our listBox1_SelectedIndexChanged ( ) component, using this symbol: / /, as you can see below:
.
.
.
//this.listBox1.SelectedIndexChanged += new
//System.EventHandler(this.listBox1_SelectedIndexChanged);
.
.
.
Then next, you have to hardcode our listBox1.DoubleClick( ) component initialization by emulating the
syntax of the commented listBox1.SelectedIndexChanged( ) initialized component, like the following
code below:
this.listBox1.DoubleClick += new
System.EventHandler(this.listBox1_DoubleClick);
After that, compile and run our program by clicking the Start debugging icon. Will it work? I fervently
hope.
Sample Output:
Explanation:
First, we load the list box with items, using the following code:
208
Since, we cannot easily select the listBox1_DoubleClick( ) event method within our Code
Designer, we have to hardcode it, by emulating the blank event method of
listBox1_SelectedIndexChanged( ) event method:
We apply here the Items.Remove method to remove the selected item from the list box.
Now to get exactly the currently selected item, we use the SelectedItem property.
this.listBox1.SelectedIndexChanged += new
System.EventHandler(this.listBox1_SelectedIndexChanged);
this.listBox1.DoubleClick += new
System.EventHandler(this.listBox1_DoubleClick);
//
// label2
//
.
.
.
}
If you have been programming in Visual Basic, you can really say how easy it is to
implement a listBox1_DoubleClick( ) event method with that programming language.
With Visual Basic, we can simply accomplished it by just choosing the DoubleClick
event right at the code designer. No other requirements are needed. Our program will run
right away!
Example 2:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The program should be able to display one or more selected items
on another list box. Follow the given figure below in designing and developing the
application program.
csListbox6a
Hamburger
Cheeseburger
Chickenburger List box 1
Mashed Potato
Spaghetti
Honeybun
Macaroni Salad
Cherry Pie
You displayed:
Figure 5.24 Display one or more items to the other list box
Note:
When the user selects and double-clicks an item at the List box 1, that particular item
must be displayed at the List box 2.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox6a. Now click the OK button.
4. Set the Form’s Text property to csListbox6a.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Double click an item to display into list box 2.
6. Click, drag and drop 2 List boxes from the Toolbox to add them into the Form.
7. Lastly, click, drag and drop another Label , then set its Text property to You
displayed:.
8. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
9.Let us now hard-code our listBox1_DoubleClick event method (by emulating the
syntax of listBox1_SelectedIndexChange( ) event method. It is very easy to get this
blank method. You just simply double-click the List box control in our Form. Can you
see now the blank event method?
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
//Add item to List box 2
listBox2.Items.Add(listBox1.Text);
}
211
.
.
.
private void InitializeComponent()
{
.
.
.
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(37, 36);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 95);
this.listBox1.TabIndex = 1;
this.listBox1.SelectedIndexChanged += new
System.EventHandler(this.listBox1_SelectedIndexChanged);
this.listBox1.DoubleClick += new
System.EventHandler(this.listBox1_DoubleClick);
//
// label2
//
.
.
.
}
11.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
212
Figure 5.24a Display one or more items to the other list box output
Tip:
To alternatively and easily go right up there at the InitializeComponent( ) part of our program, you just
simply delete our blank event method which is the following code:
Then after deleting it, compile our program by clicking the Start debugging icon or the green arrow icon
(color green). This will trigger a runtime error, which in turn, will brought us right at the heart of the
InitializeComponent ( ) part of our program. Now, you just simply put a comment before the initialization
code of our listBox1_SelectedIndexChanged ( ) component, using this symbol: / /, as you can see below:
.
.
.
//this.listBox1.SelectedIndexChanged += new
//System.EventHandler(this.listBox1_SelectedIndexChanged);
.
.
.
Then next, you have to hardcode our listBox1.DoubleClick( ) component initialization by emulating the
syntax of the commented listBox1.SelectedIndexChanged( ) initialized component, like the following
code below:
After that, compile and run our program by clicking the Start debugging icon. Will it work? I fervently
hope.
213
Explanation:
Here in our example, the user selected and double-clicked the items “Cheeseburger”,
“Spaghetti”, and “Honeybun” in list box 1. That is why they are displayed at list box 2.
When the user selects and double-clicks other collection of items from list box 1, these
particular collection of items will be displayed at the list box 2.
As what we have done before, we preloaded our list box 1 with items on it, using the
following code:
Next, we add the selected items from List box 1 into List box 2, using the following
code:
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
//Add item to List box 2
listBox2.Items.Add(listBox1.Text);
}
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(37, 36);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 95);
this.listBox1.TabIndex = 1;
this.listBox1.SelectedIndexChanged += new
System.EventHandler(this.listBox1_SelectedIndexChanged);
this.listBox1.DoubleClick += new System.EventHandler(this.listBox1_DoubleClick);
//
// label2
//
.
.
.
}
If you have been programming in Visual Basic, you can really say how easy it is to
implement a listBox1_DoubleClick( ) event method with that programming language.
With Visual Basic, we can simply accomplished it by just choosing the DoubleClick
event right at the code designer. No other requirements are needed. Our program will run
right away!
Example 3:
Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The program should be able to transfer one or more selected
items on another list box. Follow the given figure below in designing and developing the
application program:
csListbox7a
Java
C++
Perl
Basic
FoxPro List box 1
HTML
List box 2
215
Figure 5.25 Transfer one or more items to the other list box
Note:
When the user selects and double-clicks an item at the List box 1, that particular item
must be transferred into List box 2.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csListbox7a. Now click the OK button.
4. Set the Form’s Text property to csListbox7a.
5. Click, drag and drop a Label from the Toolbox to add it into the Form, and set its
Text property to Double click an item to transfer to other List box.
6. Click, drag and drop 2 List boxes from the Toolbox to add them into the Form.
7. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
8.Let us now hard-code our listBox1_DoubleClick event method (by emulating the
syntax of listBox1_SelectedIndexChange( ) event method. It is very easy to get this
blank method. You just simply double-click the List box control in our Form. Can you
see now the blank event method?
}
private void listBox1_DoubleClick(object sender, EventArgs e)
216
{
//Add the item to the other List box
listBox2.Items.Add(listBox1.Text);
listBox2.Items.Remove(listBox2.Text);
//Remove the item from this List box
listBox1.Items.Remove(listBox1.SelectedItem);
}
9.This time, we have to hard-code our listBox2_DoubleClick event method (by emulating
the syntax of listBox1_SelectedIndexChange( ) event method. It is very easy to get this
blank method. You just simply double-click the List box control in our Form. Can you
see now the blank event method?
.
.
.
private void InitializeComponent()
{
.
.
.
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(12, 25);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 95);
this.listBox1.TabIndex = 1;
this.listBox1.SelectedIndexChanged += new
System.EventHandler(this.listBox1_SelectedIndexChanged);
this.listBox1.DoubleClick += new
System.EventHandler(this.listBox1_DoubleClick);
this.listBox2.DoubleClick += new
System.EventHandler(this.listBox2_DoubleClick);
//
217
// listBox2
//
.
.
.
}
11.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Figure 5.16a Transfer one or more items to the other list box output
Tip:
To alternatively and easily go right up there at the InitializeComponent( ) part of our program, you just
simply delete our blank event method which is the following code:
Then after deleting it, compile our program by clicking the Start debugging icon or the green arrow icon
(color green). This will trigger a runtime error, which in turn, will brought us right at the heart of the
InitializeComponent ( ) part of our program. Now, you just simply put a comment before the initialization
code of our listBox1_SelectedIndexChanged ( ) component, using this symbol: / /, as you can see below:
.
.
.
218
//this.listBox1.SelectedIndexChanged += new
//System.EventHandler(this.listBox1_SelectedIndexChanged);
.
.
.
Then next, you have to hardcode our listBox1.DoubleClick( ) component initialization by emulating the
syntax of the commented listBox1.SelectedIndexChanged( ) initialized component, like the following
code below:
this.listBox1.DoubleClick += new
System.EventHandler(this.listBox1_DoubleClick);
After that, compile and run our program by clicking the Start debugging icon. Will it work? I fervently
hope.
Explanation:
Here in our example, the user double-clicks the items “XML” and “Fortran” in list box 1.
That is why these items are transferred to list box 2, as what we can see in the figure.
Now if the user double-clicks again an item in list box 1, this particular item will be
transferred to list box 2. In the case where the user double-clicks an item in list box 2, this
particular item will be transferred to list box 1. You can try it, to see for yourself how this
program works.
As what we have done previously in our program, to preload the list box with items upon
running, we use the following code:
Then we embed the following code at the List box 1 object and in its Double-click event:
}
private void listBox1_DoubleClick(object sender, EventArgs e)
{
//Add the item to the other List box
listBox2.Items.Add(listBox1.Text);
219
listBox2.Items.Remove(listBox2.Text);
//Remove the item from this List box
listBox1.Items.Remove(listBox1.SelectedItem);
}
to add the selected items from list box 1 into list box 2. At the same time, we have to
remove that selected item from the list box 1 using the Items.Remove method and the
SelectedItem property of the List object.
You will notice that this code is similarly applied to List box 2, as what we can see here
in the following code that can be found at List box 2 method:
We did this so that vice versa, they will work the same such as when we transfer an item
from list box 1 into list box 2, the selected item will also be deleted from list box 1. Now
if we want to transfer an item from list box 2 into list box 1, the selected item will also be
deleted from list box 2.
//
.
.
.
}
If you have been programming in Visual Basic, you can really say how easy it is to
implement the listBox1_DoubleClick( ) and listBox2_DoubleClick( ) event methods
with that programming language. With Visual Basic, we can simply accomplished it by
just choosing the DoubleClick event right at the code designer. No other requirements are
needed. Our program will run right away!
With the foregoing three examples above that demonstrates about how to hardcode the
List box DoubleClick event method, I am pretty sure that you already gained a solid
foundation on how to make it on your own. So what I can say more, buddy? But, good
luck to you!
221
LAB ACTIVITY
TEST 4
1. Design and develop a simple looping statement program that generates the given
sequence numbers. Follow the given figure below in designing and developing the
application program:
csLoopExam1
1 5
2 Click Me! 4
3 3
4 2
5 1
Button
Note:
When the user clicks the Click Me! button, the sequence numbers will be generated and
displayed at the two List boxes.
2. Design and develop a simple looping statement program that generates the given
sequence numbers. Follow the given figure below in designing and developing the
application program:
csLoopExam2
5 1
4 Click Me! 2
3 3
2 4
1 5
Button
222
Note:
When the user clicks the Click Me! button, the sequence numbers will be generated and
displayed at the two List boxes.
3. Design and develop a simple looping statement program that generates the given
sequence numbers. Follow the given figure below in designing and developing the
application program:
csLoopExam3
1 1
2 4
Click Me! 9
3
4 16
5 25
Note:
When the user clicks the Click Me! button, the sequence and squared numbers will be
generated and displayed at List box 1 and List box 2.
4. Design and develop a simple looping statement program that generates the given
sequence numbers. Follow the given figure below in designing and developing the
application program:
csLoopExam4
Increment by 3:
3
6 Click Me!
9
12
15
18
21
24
Note:
When the user clicks the Click Me! button, the sequence numbers will be generated and
displayed at the List box.
5. Design and develop a simple looping statement program that generates the given
sequence numbers. Follow the given figure below in designing and developing the
application program:
csLoopExam5
Decrement by 3:
24
21 Click Me!
18
15
12
9
6
3
Note:
When the user clicks the Click Me! button, the sequence numbers will be generated and
displayed at the List box.
6.Design and develop a simple program that demonstrates how to use the For Each loop
syntax that counts how many objects are there in a Form. Follow the given figure below
in designing and developing the application program:
csLoopExam6
Command1 Button
Hint:
There are: text is a Label.
6 number is a Label.
controls in this Form! is a Label.
7.Design and develop a simple program that demonstrates how to preload the List box
with items. When the user chooses an item at the list box by double-clicking it, that
particular item will be displayed at the text box. Follow the given figure below in
designing and developing the application program:
csListboxExam1
Snacks To Choose:
Hamburger
Spaghetti
Chicken
Steak List box
Macaroni
Coleslaw
Cherry
Note:
Here in the figure above, the Steak was selected by the user through double-clicking it.
That is why the Steak is displayed at the text box.
Add the following items into the List box using the Items.Add method at the Form_Load
method:
Hamburger
Spaghetti
Chicken
Steak
Macaroni
Coleslaw
Cherry
csListboxExam2
Cappuccino
Macchiato
Americano
Chocolate List box
Tea
Café Au Lait
Espresso
Brewed Coffe
Add the following items into the List box using the Items.Add method at the Form_Load
method:
Cappuccino
Macchiato
Americano
Chocolate
Tea
Café Au Lait
Espresso
Brewed Coffe
Iced Coffee
Iced Cappuccino
Iced Mocha
Iced Latte
Iced Tea List box
Chilled Milk
Coffee Float
Choco Smoothie
Remove
226
Button
Note:
The user should select first an item at the List box by highlighting it, before the user can
finally remove it by clicking the Remove Button.
Add the following items into the List box using the Items.Add method at the Form_Load
method:
Iced Coffee
Iced Cappuccino
Iced Mocha
Iced Latte
Iced Tea
Chilled Milk
Coffee Float
Choco Smoothie
10.Design and develop a simple program that demonstrates how to preload a collection of
items into List box 1. The program should be able to display one or more selected items
on another list box. Follow the given figure below in designing and developing the
application program:
csListboxExam4
Strawberry
Chocolate Vanilla
Cappuccino Decaf
Coffee Float List box 1
Evian
Viva
Orangina
Snapple
Sola
Snapple
Viva
Evian List box 2
227
Note:
When the user selects and double-clicks an item at the List box 1, that particular item
must be displayed at the List box 2.
Add the following items into the List box 1 using the Items.Add method at the
Form_Load method:
Strawberry
Chocolate Vanilla
Cappuccino Decaf
Coffee Float
Evian
Viva
Orangina
Snapple
Sola
11.Design and develop a simple program that demonstrates how to preload a collection of
items into List box 1. The program should be able to transfer one or more selected items
on another list box. Follow the given figure below in designing and developing the
application program:
csListboxExam5
Muffins
Banana Muffin
Carrot Loaf
Banana Crunch
Cookies List box 1
Pecan Bar
Figaro Bar
Cake Danish
Zebra Brownies
Carrot Cake
Marzipan Danish
Butter Cake List box 2
228
Note:
When the user selects and double-clicks an item at List box 1, that particular item must
be transferred into List box 2.
Add the following items into the List box 1 using the Items.Add method at the
Form_Load method:
Muffins
Banana Muffin
Carrot Loaf
Banana Crunch
Cookies
Pecan Bar
Figaro Bar
Cake Danish
Zebra Brownies
Carrot Cake
Marzipan Danish
Butter Cake
12.Design and develop a simple program that demonstrates how to preload a collection of
items into the List box. The program should be able to get the value of the currently
selected item in the list box. Follow the given figure below in designing and developing
the application program:
csListboxExam6
List of Provinces:
Isabela
Cebu
Tarlac
Bulacan
Negros List box
Bohol
Cotabato
Davao
Zamboanga
It’s Region:
Note:
The user selects Cebu by double-clicking it at the list box. This is also the reason why its
region was displayed at the text box. Here are the group regions for each provinces:
229
NCR Region:
Isabela
Tarlac
Bulacan
Visayan Region:
Cebu
Bohol
Negros
Mindanao Region:
Davao
Cotabato
Zamboanga
Add the following items into the List box using the Items.Add method at the Form_Load
method:
Isabela
Cebu
Tarlac
Bulacan
Negros
Bohol
Cotabato
Davao
Zamboanga
230
csListboxExam7
Add
List box
Remove
Buttons
Delete All
Close
Number of products:
Text box 2
Note:
The user will enter an item first at text box 1 and then clicks the Add button to add the
inputted item in the List box. Now when the user wants to remove an item from the list,
the user should highlight it first, then clicks the Remove button to finally delete it.
Clicking the Delete All button will wipe out all the items in the list box.
14. Design and develop a simple program that should be able to select two or more items
in the list box at once and be able to transfer the collection of selected items to another
list box simultaneously. Follow the given figure below in designing and developing the
application program:
231
List box 1
csListboxExam8
Close
List box 2
Note:
The user will click first an item located at the top portion of the list box, then use the
Shift and Arrow keys to select down other multiple items at list box 1. Clicking the
Transfer button will copy the collection of selected items into the list box 2.
Preselect the first two items at the list box 1 using the SelectedItem statement of the List
Box 1 control.
Add the following items into the List box 1 using the Items.Add method at the
Form_Load method:
Iced Coffee
Iced Cappuccino
Iced Mocha
Iced Latte
Iced Tea
Ice Chocolate
Grilled Eggplant
Grilled Chicken
Grilled Ham
Grilled Beef
Grilled Fish
232
15. Design and develop a simple application system that preloads a Combo box with
items. The user can select an item from the list to be displayed at the text box. The user
must click the down arrow (found at the right corner of the combo box) to be able to see
the list of preloaded items. Follow the given figure below in designing and developing
the application program:
csComboExam4
Text box
Note:
When the user selects an item at the Combo box by clicking it, this item will be displayed
at the text box.
Add the following items into the Combo box using the Items.Add method at the
Form_Load method:
Dilly Bar
Plain Dog
Cheese Dog
Chilimelt Dog
Relish Dog
Bacon n Cheese
Fudge Brownie
Banana Split
Peanut Buster
16.Design and develop a simple application system that preloads a Combo box with
items. The user can select an item from the list to be displayed at the list box. The user
must click the down arrow (found at the right corner of the combo box) to be able to see
the list of preloaded items. Follow the given figure below in designing and developing
the application program:
233
csComboboxExam5
List box
Note:
When the user selects an item at the Combo box by clicking it, this item will be displayed
at the list box.
Add the following items into the Combo box using the Items.Add method at the
Form_Load method:
Al Tonno
Chorizo
Arrabiata
Pesto
Carbonara
Mushroom Sauce
Pasta
Mexicali
Veggies Heaven
Mushroom Galore
Neptune’s Fancy
17.Design and develop a simple application system that preloads a Combo box with
items. The user can select an item from the list to be displayed at the list box with a
confirmation using the Button. The user must click the down arrow (found at the right
corner of the combo box) to be able to see the list of preloaded items. Follow the given
figure below in designing and developing the application program:
234
csComboboxExam6
List box
Note:
When the user selects an item at the Combo box and would like to order it, she has to
click the Order Button to display the selected item into the list box.
Add the following items into the Combo box using the Items.Add method at the
Form_Load method:
Cheese Tempura
Caesar’s Salad
Cajun Burger
Citrus Pork
Burger Steak
Café Mocha
Café Latte
Cappuccino
Steamed Milk
Espresso
Brewed Coffee
235
Chapter 6
Other Basic Controls
In this chapter, we will learn how to use some other important basic controls of Visual C#
language. We already know that the Toolbox contains the tools we use to draw or design
controls on our forms. You will notice that there are still other controls we haven’t yet
used or included in our previous application system. The reason for this is that they are
not yet needed in our simple application system and putting them early on, is not
appropriate for the requirements of our application system.
Surely, we will not cover every other controls left at the Toolbox on this chapter.
However, we will try our very best to choose those controls which we think are much
needed in a real-world business application system that we would like to design and
develop in the near future. So let us start studying them now.
The Timer control can check and display the computer system clock. Some actual
application of a timer control is to check the system clock if it is time to display an
important message such as, “It’s 12 noon, time to go to lunch!”. Or a time to accomplish
a certain task such as giving a list of a burger chain products to be sold at 30 percent
discount because they are not sold within 30 minutes after they were cooked. You can
think of some real-world application too. What we will do now is to come up with a
simple example of this timer control.
Example 1:
Design and develop a simple timer-control application system that demonstrates how it
works with Label control. Follow the given figure below in designing and developing the
application program:
csTimer1
vbTimer1
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csTimer1. Now click the OK button.
4. Set the Form’s Text property to vbTimer1.
5. Click, drag and drop two Labels from the Toolbox to add them into the Form. Set
the Text property of the first Label as The Time now is:. Then, just leave the
second Label unset.
6. This time, click, drag and drop a Timer from the Toolbox to add it into the Form.
7. Follow the property settings for Timer control below:
8. Double-click the Timer control to display the Timer1_Tick event method. Embed
the following lines of code (in bold only) to the method:
private void timer1_Tick(object sender, EventArgs e)
{
label2.Text =DateTime.Now.ToLongTimeString();
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
237
Warning!
Don’t forget to set the Enabled property of Timer1 control to True, otherwise, your program will not
display the clock (as though your program is not working).
Sample Output:
Explanation:
Here in our very simple Timer program, we simply display the time of the day which we
can easily get from the computer system’s internal clock using the following code:
In this Timer control example, we simply display the clock at our Label 2 control, as you
could observed in our code above.
To come up with bigger display of our digital clock, just simply adjust the Label’s Font
size property. For example, you can set the size of the Font to 16. Like the figure we have
below:
238
Example 2:
Design and develop a simple timer-control application system that demonstrates how it
works with a Text box control. Follow the given figure below in designing and
developing the application program:
vbTimer2
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
239
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csTimer2. Now click the OK button.
4. Set the Form’s Text property to vbTimer2.
5. Click, drag and drop a Label and a Text box from the Toolbox to add them into
the Form. Set the Text property of the Label as The Time now is:.
6. This time, click, drag and drop a Timer from the Toolbox to add it into the Form.
7. Follow the property settings for Timer control below:
8. Double-click the Timer control to display the Timer1_Tick event method. Embed
the following lines of code (in bold only) to the method:
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = DateTime.Now.ToLongTimeString();
}
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Warning!
Don’t forget to set the Enabled property of Timer1 control to True, otherwise, your program will not
display the clock (as though your program is not working).
Sample Output:
Figure 6.2b Using Timer control within Text box control output
240
Explanation:
Here in our very simple Timer program, we simply display the time of the day which we
can easily get from the computer system’s internal clock using the following code:
In this second example of our Timer control, we used a Text box control where we
displayed our digital clock.
Example 3:
Design and develop a simple date- time picker control application system that
demonstrates how it works. Follow the given figure below in designing and developing
the application program:
vbDateTimer2
Date Time
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csDateTimer2. Now click the OK button.
4. Set the Form’s Text property to vbDateTimer2.
5. Click, drag and drop two Labels from the Toolbox to add them into the Form. Set
their Text property as Date and Time, respectively.
6. This time, click, drag and drop a DateTimePicker control from the Toolbox to add
it into the Form.
7. Click, drag and drop another Label control, then set its Text property as The Date
you selected is:.
8. Lastly, click, drag and drop a Text box control from the Toolbox to add it into the
Form.
9. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
11. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
242
Explanation:
The particular event that handles on the date that we selected is the Value_Changed of
the DateTimePicker control, since there is some value that changes in the calendar that
happened. Remember, that by default, the calendar date is the current date of the day. For
example, if today is February 14, 2010, then choosing another date value will trigger a
Value_Changed event to execute.
A scroll bar is typically used to increase or decrease a value such as when we want to
change the color setting of our computer’s monitor through the Control Panel’s Display
object or to increase or decrease the volume of our computer’s digital audio speaker. The
scroll bar acts as a sliding scale with a starting point and ending point, including the
values in between.
Example 4:
Design and develop a simple Horizontal scroll-bar application system that demonstrates
how it works. Follow the given figure below in designing and developing the application
program:
vbScrollbar1
HScrolBar
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
244
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csHScrolbar1. Now click the OK button.
4. Set the Form’s Text property to vbScro1lbar1.
5. Click, drag and drop a Horizontal Scroll bar from the Toolbox to add it into the
Form. Then, set its Maximum property to 100.
6. Click, drag and drop a Label control, then set its Text property as The Scroolbar
position is:.
7. Lastly, click, drag and drop a Text box control from the Toolbox to add it into the
Form.
8. Double-click the Scrollbar control to display the HScrollbar1_Scroll event
method. Embed the following lines of code (in bold only) to the method:
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
Since we set the Horizontal scroll bar Maximum property to 100, the ending point of our
scroll bar is 91 only, and its starting point is 0 (since 0 is the default Minimum property).
It’s always minus 10 from the Maximum property. The question is, “If it is minus 10,
then the maximum scrollable point should be 90”. It is 91, because we started our
Minimum scrollable point with 0 (zero), remember?
In order for us to display the current position of our scrollbar, we have the following
code:
We simply put the new value of the current position of the scrollbar into Text box 1.
If we want to generate the scroll event as the user drags the scroll box, then we must call
the Scroll( ) event method. This is what we have done here in this example, because the
Scroll( ) event is continually triggered as the user drags the scroll box.
Example 5:
Design and develop a simple Horizontal scroll-bar application system that demonstrates
how it works. The value of the scroll bar will be updated automatically while the user
drags it. Follow the given figure below in designing and developing the application
program:
vbScrollbar2
HScrollbar 2
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csHScrolbar2. Now click the OK button.
4. Set the Form’s Text property to vbScro1lbar2.
5. Click, drag and drop two Horizontal Scroll bars from the Toolbox to add them
into the Form. Then set their both Maximum property to 100.
6. Click, drag and drop a Label control, then set its Text property as The position
for both scrollbars is:.
7. Lastly, click, drag and drop a Text box control from the Toolbox to add it into the
Form.
8. Double-click the first Scrollbar (HScrollBar1) control to display the
HScrollbar1_Scroll event method. Embed the following lines of code (in bold
only) to the method:
10. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
247
Explanation:
Since we set the Horizontal scroll bar Maximum property to 100, the ending point of our
scroll bar is 91 only, and its starting point is 0 (since 0 is the default Minimum property).
It’s always minus 10 from the Maximum property. The question is, “If it is minus 10,
then the maximum scrollable point should be 90”. It is 91, because we started our
Minimum scrollable point with 0 (zero), remember?
In order for us to be able to coordinate or synchronize the position of the two horizontal
scrollbars, we have to update the new value of the scrollbar position to each scroll( )
event of both horizontal scrollbars, as we can now see at the actual code below:
If we want to generate the scroll event as the user drags the scroll box, then we must call
the Scroll( ) event method . This is what we have done here in this example, because the
Scroll( ) event is continually triggered as the user drags the scroll box.
Example 6:
Design and develop a simple Vertical scroll-bar application system that demonstrates
how it works. Follow the given figure below in designing and developing the application
program:
vbVScrollbar1
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csVScrollbar1. Now click the OK button.
4. Set the Form’s Text property to vbVScrollbar1.
5. Click, drag and drop a Vertical Scroll bar from the Toolbox to add it into the
Form. Then set its Maximum property to 100.
6. Click, drag and drop a Label control, then set its Text property as The scrollbars
position is:.
249
7. Lastly, click, drag and drop a Text box control from the Toolbox to add it into the
Form.
8. Double-click the Vertical Scrollbar (VScrollBar1) control to display the
VScrollbar1_Scroll event method. Embed the following lines of code (in bold
only) to the method:
private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
{
textBox1.Text = Convert.ToString(vScrollBar1.Value);
}
9. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
Since we set the Vertical scroll bar Maximum property to 100, the ending point of our
scroll bar is 91 only, and its starting point is 0 (since 0 is the default Minimum property).
It’s always minus 10 from the Maximum property. The question is, “If it is minus 10,
then the maximum scrollable point should be 90”. It is 91, because we started our
Minimum scrollable point with 0 (zero), remember?
In order for us to display the current position of our scrollbar, we have the following
code:
250
If we want to generate the scroll event as the user drags the scroll box, then we must call
the Scroll( ) event method. This is what we have done here in this example, because the
Scroll( ) event is continually triggered as the user drags the scroll box.
Example 7:
Design and develop a simple Picture box control application system that demonstrates
how it works. Follow the given figure below in designing and developing the application
program:
vbPicture1
Picture Box1
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csPicture1. Now click the OK button.
4. Set the Form’s Text property to vbPicture1.
5. Click, drag and drop a Picture Box control from the Toolbox to add it into the
Form. This time, run the Paint software and press the prt sc (Print Screen) key on
your keyboard to save your current Desktop background picture. Then, save the
file at the My Pictures folder and named it: DesktopPic1.png.
6. Now click, drag and drop a Button, then set its Text property to Display Now the
Picture!.
7. Double-click the Button control to display the Button1_Click event method.
Embed the following lines of code (in bold only) to the method:
(Warning: However, I have used here my own desktop picture. In your case, you
need to change the Location (Disk Drive and the corresponding Directories and
Folder to where you have stored your desktop picture). Understood???
private void button1_Click(object sender, EventArgs e)
{
// Don't forget to set the SizeMode
// property of the Picture Box to CenterImage
pictureBox1.Image =
Image.FromFile("C:/Users/coper/Pictures/VB2012bmps/DesktopPic1.png");
}
8. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Tip!
In my own desktop picture, I store it in this Location:
"C:\Users\coper\Pictures\VB2012bmps\DesktopPic1.png")
Absolutely, in your case - you stored your desktop picture somewhere else. So, you need to change its
corresponding Location to make your program run as you expected it to be. Got it???
Sample Output:
252
Explanation:
The syntax of loading the picture in our Picture box control is so simple. Here is its code
below:
The DesktopPic1.png image is the screen-shot that we saved through prt sc (Print Screen)
key in our keyboard. Then, we simply pasted it into the Paint software and finally saved it
with a name: DesktopPic1.png. Using the Image.FromFile( ) method, we can display the
image at PictureBox1 object, or alternatively, we can display the image directly by
setting the PictureBox1 Image property.
Warning:
Don't forget to set the SizeMode property of the Picture Box control to CenterImage so that you can get the
exact center image of your saved image file (picture) like the one you see here in our example. Got it??? I
hope so!
253
This is the end of our discussion about the other basic controls of Visual Basic. I hope
that you have learned a lot from these examples.
Example 8:
Design and develop a simple LinkLabel control application system that demonstrates
how it works. If the user clicks that linklabel, it will activate its Hyperlink capability, thus
it will surf the specified website. Follow the given figure below in designing and
developing the application program:
vbLinkLabel1
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csLinkLabe1. Now click the OK button.
4. Set the Form’s Text property to vbLinkLabel1, too.
5. Click, drag and drop a LinkLabel control from the Toolbox to add it into the
Form. Set its Text property to “Do you want to go to Yahoo website?”. Then, go
to the LinkArea property to select (highlight) a range of text to make your link :
Yahoo website?. Now, click the OK button. Lastly, set the LinkVisited property
to True.
254
7. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
Once we click the Yahoo website?, hyperlink text, the Yahoo website will be surfed, thus
will make our default web browser to be activated. If you are connected to the Internet,
the Yahoo homepage will be displayed for you; now if not, then your web browser will
simply display a message which tells, “You’re not connected to a network”.
And we just have the following simple program code to accomplish this amazing task:
Well, I guess you would agree with me on how simple the program code is.
255
Note:
Although the Panel control is similar to GroupBox control, however only the Panel can
have scroll bars, and only the GroupBox can display a caption within it.
Example 9:
Design and develop a simple Panel control application system that demonstrates how it
works. We have two panels here: the first one contains 5 ordinary check boxes and the
other one contains 5 radio buttons. Now, when the user clicks any check box or radio
button in the Panel, that particular check box or radio button will be reported as being
clicked in the text box. Follow the given figure below in designing and developing the
application program:
vbPanel1
Panel 1 Panel 2
CheckBox1 RadioButton1
CheckBox2 RadioButton2
CheckBox3 RadioButton3
CheckBox4 RadioButton4
CheckBox5 RadioButton5
Text box
Figure 6. 9 Using the Panel control
256
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking
the Start tab at your Windows 8 operating system. Now Start a New Project.
Select the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csPane1. Now click the OK button.
4. Set the Form’s Text property to vbPanel1, too.
5. Click, drag and drop two Panel controls from the Toolbox to add it into the
Form. Set their respective BorderStyle property to Fixed3D and their
respective AutoScroll property to True .
6. Put 5 Check Boxes in one Panel, and 5 Radio Buttons in another Panel. Then,
click, drag and drop a Text Box control into the Form.
Lastly, label all the controls accordingly.
7. Double-click all Check Boxes and Radio Buttons one by one to display their
CheckedChanged event method. Embed the following lines of code (in bold
only) to the method:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "checkBox1!";
}
textBox1.Text = "radioButton2!";
}
8. Build and execute the application system by clicking the Start debugging icon
(or press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
When the user clicks any of the check boxes or radio buttons in our two panels, that
particular check box or radio button will be reported as being clicked at the text box. To
accomplish this task is very simple. We just have the following program code fragments:
textBox1.Text = "checkBox1!";
}
….
….
private void radioButton5_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "radioButton5!";
}
to understand it all.
Example 10:
Design and develop a Track Bar control application system that demonstrates how it
works. Follow the given figure below in designing and developing the application
program:
vbTrackBar1
Track Bar
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csTrackBar1. Now click the OK button.
4. Set the Form’s Text property to vbTrackBar1, too.
5. Click, drag and drop a TrackBar control from the Toolbox to add it into the Form.
Then, click, drag and drop a Text Box into the Form and label it accordingly.
6. Double-click the TrackBar control to display the TrackBar1_Scroll event method.
Embed the following lines of code (in bold only) to the method:
private void trackBar1_Scroll(object sender, EventArgs e)
{
textBox1.Text = Convert.ToString(trackBar1.Value);
}
7. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
260
Explanation:
We can observed that a track bar works much like scroll bars, but it is different in
appearance. And it resembles also like a control we can see in a stereo. We can display
the value of the track bar in a text box with the following simple program code:
Now, we need to convert the numeric value of track bar into string value before we can
display it in our text box.
See? Very simple.
Warning!
In C#, unlike in Visual Basic syntax, there is no automatic conversion of numeric value
into its equivalent string value.
Example 11:
Design and develop a Track Bar control application system that demonstrates how it
works. Follow the given figure below in designing and developing the application
program:
vbProgressBar1
Progress Bar
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csProgressBar1. Now click the OK button.
4. Set the Form’s Text property to vbProgressBar1, too.
5. Click, drag and drop a ProgressBar control from the Toolbox to add it into the
Form.
6. Now click, drag and drop a Timer control (by clicking first the All Windows
Forms tab, then the Components tab) from the Toolbox to add it into the form.
7. Next click, drag and drop a Text Box and two Buttons into the Form. Then, label
them accordingly.
8. Double-click the Timer control to display the Timer1_Tick event method. Embed
the following lines of code (in bold only) to the method:
private void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Value += 1;
textBox1.Text = Convert.ToString(progressBar1.Value);
if (progressBar1.Value == progressBar1.Maximum)
timer1.Enabled = false;
}
9. This time, double-click the Button1 (Start Moving Now! button) control to
display the Button1_Click event method. Embed the following lines of code (in
bold only) to the method:
10. This time, double-click the Button2 (Clear the Value of ProgressBar! button)
control to display the Button2_Click event method. Embed the following lines of
code (in bold only) to the method:
11. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
Once the user clicks the Start Moving Now! (Button1) button control, we just activating
the Timer control by setting simply its Enabled property to True. Thus, we have this
simple program code below:
progressBar1.Value += 1;
Next, we display this incrementation operation (as it runs) into our Text Box:
263
textBox1.Text = Convert.ToString(progressBar1.Value);
Finally, if and when the maximum value of the Progress Bar was reached (caused by our
incrementation operation), we simply stop the Timer-tick to keep on ticking (counting)
by just setting the Timer1 Enabled property to False.
if (progressBar1.Value == progressBar1.Maximum)
timer1.Enabled = false;
To sum up all our discussion within the Timer control, we just present its complete event
method code here:
To clear the maximum value of the Progress Bar, we simply store its minimum value
(which in our case it is zero). Then, we display this minimum value into the Text Box, as
you could observe it in our program code below:
This control is so very useful, most especially when your computerized business
application system needs something to gauge or measure such as a live sales-quota
performance wherein every minute of sales transaction should be recorded and be
reflected in real-time through the use of Progress Bar. Imagine, you can see the Progress
Bar moving as the customers buy their products and pay their purchases to the cashiers’
counter? And you can see it in your bare eyes that you and your team are almost reaching
the sales quota of the month, even if you are still a week ahead from the ending date?
Exciting, isn’t it?
264
Postscript
Actually, I started the experimentation about this online live-sales data back in 1994 at
AMA Computer University using the Clipper database software in a LAN-based
environment. Then in 1995, I presented this idea as a seminar to the computer
engineering (CoE) and electronics and communication engineering (ECE) students at the
Mapua Institute of Technology (MIT) – Intramuros, Manila Campus. I sell them the idea
that with the application of wireless technology (currently applied in the cellular phone
communication on that time) and a Novell Mobile Netware (the network software used to
access the database remotely), a top executive can see all the real-time online sales-data,
anytime he or she wants and anywhere he or she is around the globe. Even if he or she is
presently in a vacation in Boracay or even he or she is in an airplane – as long as there is
a presence of cellular-phone signal. They just simply use the computerized system that I
designed. The students were so amazed that they throw me a lot of questions even if I just
got started presenting my topic in less than 5 minutes. And they continue asking
questions until past noon. I just wondered why these students forgot that it’s already time
for them to eat their lunch. After I took my lunch, the students were still waiting for me -
just to get their free copy of my program and continue digging more questions. I said,
“Wow, unbelievable!” This story of my seminar never ends there, because on the
following year, the graduating students of ECE at MIT had me to present again the same
topic of seminar that should be presented only and exclusively for them.
That’s my story about the Progress Bar. And I just hope that we too will have this kind of
“progress bar” in life, where we can gauge our own performance. And in the process, we
would know our position where we currently are – in our ladder of success.
LAB ACTIVITY
TEST 5
csClock1
System Clock:
Text box
4:28:40 PM
4:28:40 PM
Label
csHScrollbar 5
Note:
Set the Max property of the Horizontal Scroll bar to 109.
Down 0
50 Label 1
Up 109
Note:
Set the Max property of the Vertical Scroll bar to 109.
4. Design and develop the Horizontal and Vertical scroll bars application system that
demonstrate how they work. Follow the given figure below in designing and developing
the application program:
csHVScrollbar5
Low
Middle 50
50
High
267
Note:
Set the Max property of the Horizontal and Vertical Scroll bars to 109.
5. Design and develop a simple Picture box control application system that demonstrates
how it works. Just put any picture you want. Follow the given figure below in designing
and developing the application program:
csPicture2
Picture 1: Picture 2:
Picture1 &
Picture2
6.Design and develop a simple Panel control application system that demonstrates how it
works. We have two panels here: the first one contains 5 check boxes and the other one
contains 5 radio buttons. The two panels are grouped into a panel of animals and a panel
of fruits. Now, when the user clicks any check box or radio button in the Panel, the text
value of that particular check box or radio button will be reported as being clicked in the
text box. Follow the given figure below in designing and developing the application
program:
csPanel2
Dog Banana
Cat Apple
Lion Mango
Tiger Orange
Zebra Melon
Text box
268
7.Design and develop a simple LinkLabel control application system that demonstrates
how it works. If the user clicks that linklabel, it will activate its Hyperlink capability, thus
it will surf the specified website. Follow the given figure below in designing and
developing the application program:
csLinkLabel2
Like us on Facebook!
And
Follow us on Twitter!
8.Design and develop a Track Bar control application system that demonstrates how it
works. Follow the given figure below in designing and developing the application
program:
csTrackBar2
Track Bar
9.Design and develop a Track Bar control application system that demonstrates how it
works. Follow the given figure below in designing and developing the application
program:
269
csProgressBar2
Progress Bar
Chapter 7
Designing and Developing Menus
Usually, Microsoft Windows application systems menu consist of one or more of the
following features:
• Menus – are the first or top-level menu items that are immediately visible at the
menu bar. Examples of these top-level menus are File, View and Help.
• Menu items – are additional menu items residing under menus, each of which
represents a choice for a user to make.
271
• Submenus – are collection of menu items accessed through a parent menu item.
We can identify submenus by the black arrow on the right end of the menu item
that provides access to them.
• Access keys – are keyboard keys that are used in conjunction with the Alt key
which will trigger a menu or menu item to activate when pressed simultaneously.
• Shortcuts – are special keyboard keys with specific function such as F5 (for Start
debugging) or F1 (for Help).
• Separators – are horizontal lines used to organize menu items into logical
groups.
Adding Menus
The MenuStrip control is a tool we used to add menus into the Form. The
MenuStrip can be found in our Toolbox under the Menus & Toolbars group.
With MenuStrip, we can add new menus, modify or reorder existing menus, or delete old
menus. We can enhance also our menus with special effects such as keyboards shortcuts,
access keys, and check marks. We can design a professional-looking menus, however, we
still need to provide the code behind each menu items so that they would work in
accordance to our wishes.
Let us now have a working example about this menu design and development.
Example 1:
Design and develop a simple menu-based application system that demonstrates how to
create a simple menu system with the following menu title: Menu1, Menu2, and Menu3.
Follow the given figures below in designing and developing the application program:
Form1
Form1
Menu title
Menu1 Menu2 Menu3
M2 Item1
Menu items M2 Item2
M2 Item3
Form1
Note:
When the user clicks the Menu 1 - Item 1, the message “M1 Item1 clicked!” will be
displayed at the Message box; when the user clicks the Menu1 – Item 2, the message
“M1 Item2 clicked!” will be displayed at the Message box, and so on with Menu1. When
the Exit item of Menu 1 is clicked by the user, the menu program will exit right away.
When the user clicks the Menu 2 – Item 1, the message “M2 Item 1 clicked!” will be
displayed at the Message box, when the user clicks the Menu2 – Item 2, the message
“M2 Item2 clicked!” will be displayed at the Message box, and so on with Menu2. Do the
same with Menu3.
Tip:
The Code editor is also commonly called Code Designer.
273
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMyMenu1. Now click the OK button.
4. Set the Form’s Text property to vbMyMenu1.
5. Click, drag and drop a MenuStrip control (click All Windows Forms) from the
Toolbox, to add it to the Form.
6. Click the Type Here tag, type Menu1, and then press the Enter key.
7. Now, under the Menu1, type M1 Item1 as your first item at Menu 1. Next, type
M1 Item 2 as your second item for Menu 1, then type M1 Item 3, M1 Item 4,
and Exit. (See the given figure above to easily compare your work).
8. This time, you have to type Menu2 beside Menu1, and then press the Enter key.
9. Now, under the Menu2, type M2 Item 1 as your first item at Menu 2. Next, type
M2 Item 2 as your second item for Menu 2, and lastly, type M2 Item 3. (See the
given figure above to easily compare your work).
10. At the side of Menu2, type Menu3, and then press the Enter key. Under the
Menu3, type M3 Item 1, and M3 Item 2. (See the given figure above to easily
compare your work).
11. Double-click now the Menu1 Item 1 (M1 Item1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu1 Item1 clicked!");
}
12. Double-click now the Menu1 Item 2 (M1 Item 2) to display the Code editor.
Embed the following code to the menu item Click event method:
private void m1Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu1 Item2 clicked!");
}
13. Double-click now the Menu1 Item 3 (M1 Item 3) to display the Code designer.
Embed the following code to the method:
private void m1Item3ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu1 Item3 clicked!");
}
14. Double-click now the Menu1 Item 4 (M1 Item 4) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1Item4ToolStripMenuItem_Click(object sender, EventArgs e)
274
{
MessageBox.Show("Menu1 Item4 clicked!");
}
15. Double-click now the Menu1 Item 5 (Exit) to display the Code designer. Embed
the following code to the menu item Click event method:
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
16. Double-click now the Menu2 Item 1 (M2 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m2Item1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu2 Item1 clicked!");
}
17. Double-click now the Menu2 Item 2 (M2 Item 2) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m2Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu2 Item2 clicked!");
}
18. Double-click now the Menu2 Item 3 (M2 Item 3) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m2Item3ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu2 Item3 clicked!");
}
19. Double-click now the Menu3 Item 1 (M3 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m3Item1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu3 Item1 clicked!");
}
20. Double-click now the Menu3 Item 2 (M3 Item 2) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m3Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu3 Item2 clicked!");
}
275
21. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Then try to click each menu item in each menu title and see for yourself how the menu is
responding. I hope it responds positively.
Sample Output:
Explanation:
In this simple menu system, we can see that if the user selects and clicks a particular
menu item, a corresponding Message Box will appear and displays the message on what
particular menu item the user was clicking and in what menu it was under. For example,
the user selects and clicks the M2 Item3 menu item, so the Message Box will display the
message “ Menu2 Item3 clicked!”. This will also apply to other menu items when the
user selects them.
Example 2:
Design and develop a simple menu-based application system that demonstrates how to
create a simple menu system with the following menu title: Menu1, Menu2, and Menu3.
Follow the given figures below in designing and developing the application program:
276
vbMyMenu5
Form1
Menu title
Menu1 Menu2 Menu3
M2 Item1
Menu items M2 Item2
M2 Item3
Form1
Note:
M3 Item 2 is intentionally hidden,
to see it, just click the M3 Item 1!
To enable M2 Item 2, just click the M3 Item 2.
Note:
Between Menu 1 Item 4 (M1 Item4) and Exit menu item is a Line Separator.
277
Menu 2 Item 1 (M2 Item1) and Menu 2 Item 3 (M2 Item3) are checked, while Menu 2
Item 2 was disabled by default. This will be enabled once the Menu3 Item2 is clicked.
Once the Menu 3 Item 1 (M3 Item1) is clicked, the hidden Menu3 Item2 (M3 Item2) will
appear suddenly.
Warning!
Be sure that the Property of the Controls are properly set, to reflect the needed and actual requirements of
the output such as Line Separator, it must be present in your design. The M2 Item1 and M2 Item3 should
be check-marked, M2 Item2 should be disabled by default, M3 Item 2 must be hidden.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMyMenu5. Now click the OK button.
4. Set the Form’s Text property to vbMyMenu5.
5. Click, drag and drop a MenuStrip control (click the All Windows Forms) from the
Toolbox, to add it to the Form.
6. Click the Type Here tag, type Menu1, and then press the Enter key.
7. Now, under the Menu1, type M1 Item 1 as your first item at Menu 1. Next, type
M1 Item2 as your second item for Menu 1, then type M1 Item 3, M1 Item 4, and
Exit. (See the given figure above to easily compare your work). Now, put a Line
separator between M1 Item4 and Exit. To do that, you have to point the mouse at
the Exit menu item, then right-click the mouse to select the Insert contextmenu
item, and finally click the Separator contextmenu item. Now at the M1 Item4,
you have to add a submenu under it. You have to name them as Say “Hello!” and
Say “Goodbye?”.
8. Now, point or select the Exit now, then right-click the mouse to see the Context
menu where you choose to put a Line Separator. Choose it now. Now, set the
Shortcutkeys property of M1 Item 1 to F3, M1 Item 2 to Ctr+W, and M1 Item 3
to Alt+F9, respectively.
9. This time, you have to type Menu2 beside Menu1, and then press the Enter key.
10. Now, under the Menu2, type M2 Item 1 as your first item at Menu 2. Next, type
M2 Item 2 as your second item for Menu 2, and lastly, type M2 Item 3. (See the
given figure above to easily compare your work). You should set a Check-mark to
M2 Item1 and M2 Item3 respectively. To do that, you have to right-click the
mouse to select the Checked contextmenu item for both of them. However, you
should set the M2 Item2 to Disabled. To disable it, simply right click the mouse so
that the Context menu will appear where you can deselect the Enabled option.
Can you see now the effect? Your M2 Item2 should be dimmed.
278
11. At the side of Menu2, type Menu3, and then press the Enter key. Under the
Menu3, type M3 Item 1, and M3 Item 2. (See the given figure above to easily
compare your work). The M3 Item1 and M3 Item2 should contain a ToolTipText.
Refer to the design Note above to get the exact tooltip messages.
12. Double-click now the Menu1 Item 1 (M1 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1Item1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu1 Item1 clicked!");
}
13. Double-click now the Menu1 Item 2 (M1 Item 2) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu1 Item2 clicked!");
}
14. Double-click now the Menu1 Item 3 (M1 Item 3) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1Item3ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu1 Item3 clicked!");
}
15. Double-click now the Menu1 Item 4 Submenu Item 1 (Say “Hello!”) to display
the Code designer. Embed the following code to the menu item Click event
method:
private void sayHelloToolStripMenuItem_Click(object sender, EventArgs
e)
{
MessageBox.Show("Say 'Hello!' Submenu Item 1 clicked!");
}
16. Double-click now the Menu1 Item 4 Submenu Item 2 (Say “Goodbye?”) to
display the Code designer. Embed the following code to the menu item Click
event method:
private void sayGoodbyeToolStripMenuItem_Click(object sender, EventArgs
e)
{
MessageBox.Show("Say 'Goodbye?' Submenu Item 2 clicked!");
}
17. Double-click now the Menu1 Item 5 (Exit) to display the Code designer. Embed
the following code to the menu item Click event method:
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
279
this.Close();
}
18. Double-click now the Menu2 Item 1 (M2 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m2Item1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu2 Item1 clicked!");
}
19. Double-click now the Menu2 Item 2 (M2 Item 2) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m2Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu2 Item2 clicked!");
}
20. Double-click now the Menu2 Item 3 (M2 Item 3) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m2Item3ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu2 Item3 clicked!");
}
21. Double-click now the Menu3 Item 1 (M3 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m3Item1ToolStripMenuItem_Click(object sender, EventArgs e)
{
m3Item2ToolStripMenuItem.Visible = true;
MessageBox.Show("M3 Item2 is now Appearing!");
}
22. Double-click now the Menu3 Item 2 (M3 Item 2) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m3Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
m2Item2ToolStripMenuItem.Enabled = true;
MessageBox.Show("M2 Item 2 is now Enabled!");
}
23. Double-click the Form control to display the Form1_Load event method. Embed
the following lines of code (in bold only) to the method:
private void Form1_Load(object sender, EventArgs e)
{
m3Item2ToolStripMenuItem.Visible = false;
}
280
24. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Then try to click each menu item in each menu title and see for yourself how the menu is
responding. I hope it responds as we expected.
Try to press the shortcut keys such as F3, Ctrl+W, and Alt+F9. Will they correspond to
the menu item where they represent? Like for example, if you press the F3 (function key
3), will the message box that says, “M1 Item 1 clicked!” appears?
Try to click the M3 Item 1 menu item, will it triggers to display the hidden M3 Item 2
menu item? Now if the M3 Item 2 menu item appears, could clicking it triggers the M2
Item 2 to be enabled? All the answers of the above code-test tasks must be YES.
Otherwise, there is something wrong in your program, therefore, you need to debug it.
Sample Output:
Explanation:
Here in this code below, we simply set the Visible property of the M3 Item 2 menu item
to True to make it appear in our menu system:
Because the moment we run our program, we set the Visible property of M3 Item 2 menu
item to False, as what we have done in our Form1_Load event method below:
Now, you could noticed that in the moment the M3 Item 2 appears in our menu system,
we can click it, so that it will enable the M2 Item 2 which is currently Disabled by default
(disabled at design time by deselecting the Enabled option at the Context menu caused by
right-clicking the mouse while the mouse pointer is pointing to M2 Item 2). Here is the
code that accomplishes this task:
Example 3:
Design and develop a simple menu-based application system that demonstrates how to
create a simple menu system with the following menu title: Control, Calculate, and
About. Follow the given figures below in designing and developing the application
program:
Form1
Form1
Add
Subtract
Multiply
Divide
Form1
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMyMenu2. Now click the OK button.
4. Click, drag and drop a MenuStrip control (click All Windows Forms) from the
Toolbox, to add it to the Form.
5. Click the Type Here tag, type Control, and then press the Enter key.
6. Now, under the Control, type Buttons as your first item at Control menu. Next,
type Check boxes as your second item for Control menu, then finally type Radio
buttons. (See the given figure above to easily compare your work).
7. This time, you have to type Calculate beside the Control menu, and then press
the Enter key.
8. Now, under the Calculate menu, type Add as your first item. Next, type Subtract
as your second item, then type Multiply as your third item and lastly, type
Divide. (See the given figure above to easily compare your work).
283
9. At the side of the Calculate menu, type About, and then press the Enter key.
Under the About menu, type Me?, and Close. (See the given figure above to
easily compare your work).
Since our main menu is in Form1, we have to put the Buttons menu item in Dialog1,
while the Check Boxes menu item should be in Dialog2 and the Radio Buttons menu
item should be in Dialog3. All of these menu items are under the Control menu.
Under the Calculate menu, the Add menu item should be in Form2, the Subtract menu
item is in Form3, the Multiply menu item is in Form4 and the Divide menu item should
be in Form5. Let us do it now.
10. Let us add another Form by clicking the Add New Item icon at the Toolbar. You
will be presented a list of items. You have to select the Windows Form item and
finally click the Add button to select it. Design the following specification in
Form2 for our Buttons menu item:
Form2
Button 1
Button 2
Button 3
Buttons
11. After designing the above specs, you have to embed the following code into the
Buttons menu item Click event method:
12. We will add another Form by clicking the Add New Item icon at the Toolbar,
again. You will be presented a list of items. You have to select the Windows
Form item and finally click the Add button to select it. Design the following
specification in Form3 for our Check boxes menu item:
284
Form3
Check box 1
Check box 2
Check box 3
13. After designing the above specs, you have to embed the following code into the
Check boxes menu item Click event method:
14. We will add another Form by clicking the Add New Item icon at the Toolbar,
again. You will be presented a list of items. You have to select the Windows
Form item and finally click the Add button to select it. Design the following
specification in Form4 for our Radio buttons menu item:
Form4
Radio button 1
Radio button 2
Radio button 3
15. After designing the above specs, you have to embed the following code into the
Radio buttons menu item Click event method:
16. In this juncture, under the Calculate menu, let us add another Form by clicking
the Add New Item icon at the Toolbar. You will be presented a list of items. You
have to select the Windows Form item and finally click the Add button to select
it. Design the following specification in Form5 for our Add menu item:
Form5
17. After designing the above specs, you have to embed the following code into the
Add menu item Click event method:
18. Still, under the Calculate menu, let us add the next Form by clicking the Add New
Item icon at the Toolbar. You will be presented a list of items. You have to select
the Windows Form item and finally click the Add button to select it. Design the
following specification in Form6 for our Subtract menu item:
Form6
19. After designing the above specs, you have to embed the following code into the
Subtract menu item Click event method:
private void subtractToolStripMenuItem_Click(object sender,EventArgs e)
{
M2Item3 frmM2Item3 = new M2Item3();
frmM2Item3.Show();
}
20. Still, under the Calculate menu, let us add the next Form by clicking the Add New
Item icon at the Toolbar. You will be presented a list of items. You have to select
the Windows Form item and finally click the Add button to select it. Design the
following specification in Form7 for our Multiply menu item:
Form7
Text box 2
21. After designing the above specs, you have to embed the following code into the
Multiply menu item Click event method:
private void multiplyToolStripMenuItem_Click(object sender,EventArgs e)
{
M2Item2 frmM2Item2 = new M2Item2();
frmM2Item2.Show();
}
22. Lastly, under the Calculate menu, let us add the next Form by clicking the Add
New Item icon at the Toolbar. You will be presented a list of items. You have to
select the Windows Form item and finally click the Add button to select it. Design
the following specification in Form8 for our Divide menu item:
Form8
Text box 2
23. After designing the above specs, you have to embed the following code into the
Divide menu item Click event method:
private void divideToolStripMenuItem_Click(object sender, EventArgs e)
{
M2Item4 frmM2Item4 = new M2Item4();
frmM2Item4.Show();
}
24. Now this time, let us put a ready-made Dialog for our Me? menu item under
About menu title. Where can we find it? It is very easy. Click the Add New Item
icon now at the Toolbar, then select the About Box item and finally click the Add
button to select it.
Warning!
The Design specs below is a ready-made Dialog of Visual C#. So, there is no need for us to design it.
About MyMenu2
MyMenu2
Version 1.0.0.0
25.You have to embed the following code into the Me? menu item Click event method:
26.Double-click now the Close menu item to display the Code designer. Embed the
following code to the menu item Click event method:
288
27.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
Calling the Form to appear once we click a particular menu item, we simply have the
following code:
The same also apply with how we can call the other Form control when we click a
particular menu item:
frmM1Item2.Show();
}
This time, we are now ready to tackle another useful menu programming essential. And
that is designing a Toolbar. So fasten now your seatbelt, for we will take off to this
activity in a matter of seconds.
Designing a Toolbar
The toolbar is located right below the menu titles in almost all application software such
as Microsoft Word, Microsoft Excel, or Microsoft PowerPoint. They are represented by
icons that signify their use such as a blank paper sheet icon for creating new document,
an open folder icon for opening a new document, a picture of a diskette for saving your
document, and a picture of a printer to print your presently typed document.
Through these icons or pictures, a toolbar can provide us a quick access to the most
frequently used menu commands in an application such as opening, saving or printing a
document. This is in the case of the application software. We can imitate this strategy
also in our business application system which we would like to design and develop. That
is why it is important to follow a certain standard in designing menus and toolbars. As
much as possible, the menu and toolbar that we will design and develop should mimic
the existing icons used in most popular software application. In this way, the target user
of our application can easily adapt to it without the need of a manual or an online help.
Let us have our example now on how to design and develop this so called “toolbar”.
Example 4:
Design and develop a simple menu-based application system that demonstrates how to
create a simple toolbar with the following icons: IE icon and Camera icon. Follow the
given figures below in designing and developing the application program:
csMyMenu3
Menu1 Menu2
Toolbar
290
Form1
Menu1 Menu2
M1 Item1
M1 Item 2
Exit
Form1
Menu title
Menu1 Menu2
Tool bars M2 Item1
Menu items Close
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMyMenu3. Now click the OK button.
4. Set the Form’s Text property to csMyMenu3.
5. Click, drag and drop a MenuStrip control (click All Windows Forms) from the
Toolbox, to add it to the Form.
6. Click the Type Here tag, type Menu1, and then press the Enter key.
7. Now, under the Menu1, type M1 Item 1 as your first item at Menu 1. Next, type
M1 Item 2 as your second item for Menu 1, then type Exit. (See the given figure
above to easily compare your work). ). Now, put a Line separator between M1
Item2 and Exit. To do that, you have to point the mouse at the Exit menu item,
291
then right-click the mouse to select the Insert contextmenu item, and finally click
the Separator contextmenu item.
8. This time, you have to type Menu2 beside Menu1, and then press the Enter key.
9. Now, under the Menu2, type M2 Item 1 as your first item at Menu 2. Next, type
Close as your second item for Menu 2. (See the given figure above to easily
compare your work).
10. Double-click now the Menu1 Item 1 (M1 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
11. Double-click now the Menu1 Item 2 (M1 Item 2) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu 1 Item 2 clicked!");
}
12. Double-click now the Menu2 Item 1 (M2 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m2Item1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu 2 Item 1 clicked!");
}
13. Double-click now the Menu2 Item 2 (Close) to display the Code designer. Embed
the following code to the menu item Click event method:
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
14. Let us create a toolbar to enhance the menu we just created in example number
1(with a little modification by making the menu choices shorter and simpler).
If we need to add a toolbar control in our menu system, we will drag and drop a
ToolStrip control (click All Windows Forms) from the Toolbox into our Form1.
15. Next, we have to right-click the toolbar we designed, then we have to select the
Insert at the popup menu and finally select and click the Button. Then insert the
second button in our toolbar.
We need to put an image to the button in our toolbar so that it will look like an
icon that represents what it does. For example, an icon with an image of a diskette
means it is used to save a document, while a folder icon means we use it when we
want to open a document, and a printer icon means we use it for printing a
document. For the sake of simplicity and to easily code our program, we will take
292
a screen-shot from our All apps icons. To accomplish this, click now the Start tab
of our Windows 8, then right-click the mouse. Finally, click the All apps icon,
then press the prt sc (Print Screen) key in our keyboard. Now, activate the Paint
software, then click the Paste icon.
For our first icon, Select, Cut, and Paste, then Save the Internet Explorer icon
(with the big E symbol), and named it: vbIEicon1.png. Saved it at your
MyPictures folder.
For our second icon, Select, Cut, and Paste, then Save the Camera icon, and
named it: vbCameraicon1.png. Saved it at your MyPictures folder.
16. This time, we have to point and right-click our mouse to the first toolbar button,
then select the Set Image submenu item. Then, click the Import button and search
for your saved icons at your MyPictures folder. Do the same with the second
toolbar button with its corresponding icon.
17. Now double-click the first icon which is the vbIEicon1.png, then embed the
following code to the ToolStrip Button1 Click event method:
private void toolStripButton1_Click(object sender, EventArgs e)
{
MessageBox.Show("Internet Explorer icon is clicked!");
}
18. Now double-click the second icon which is the vbCameraicon1.png, then embed
the following code to the ToolStrip Button2 Click event method:
private void toolStripButton2_Click(object sender, EventArgs e)
{
MessageBox.Show("Camera icon is clicked!");
}
19. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Then try to click each menu item in each menu title and see for yourself how the menu is
responding. This time, try to click also the toolbar icons if they too, are responding,
appropriately.
Whew!!! What a long and winding code! But it’s worth the effort, isn’t it?
Note:
The .png file is editable at the Microsoft Paint software. This is an image file where we can use to convey
to the user of our menu system what a particular task a toolbar icon would do. For example, if a toolbar‘s
functionality is about saving a document, we can use a diskette as our image for this particular toolbar
button. If a toolbar button is about printing a document, then we can use the printer image to represent that
task.
Sample Output:
293
Explanation:
Here, we are using the Message Box method to display a message when the user clicks a
particular menu item or a particular toolbar icon. The message tells what particular menu
item or toolbar was clicked and in what particular menu title that menu item belonged to.
Like for instance, when we click the M1 Item 1, the message “Menu1 Item1 clicked!”
will appear in a message box. This can be accomplished with the following code:
The preceding code above has similar effect and code construction with the other code in
our program. So there is no need for us to inspect them in details.
Here in this example, when we click the toolbar icon, the message box that corresponds
to its click event will appear. We can accomplish this task through this code:
The above code has similar effect with the other code in our program. There is no need
for us to explain them in details.
294
Example 5:
Design and develop a simple menu-based application system that demonstrates how to
create a simple toolbar with the following icons: IE, Camera and Mail. Follow the given
figures below in designing and developing the application program:
vbMyContextMenu1
Menu1 Menu2
vbMyContextMenu1
Menu1 Menu2
M1 Item1
icons
M1 Item2
Context TI1
Paste
Context TI3
Note:
When the user clicks the Menu 1 - Item 1, the message “M1 Item1 clicked!” will be
displayed at the Message box; when the user clicks the Menu1 – Item 2, the message
“M1 Item2 clicked!” will be displayed at the Message box, and when the Exit item of
295
Menu 1 is clicked by the user, the menu program will exit right away. When the user
clicks the Menu 2 – Item 1, the About Dialog box will be displayed, and when the user
clicks the Menu2 – Item 2, which is the Close menu item, it will close the application
system. Now, when the user right-click the mouse, the Context Menu will appear. In this
juncture, the user can now select the items in the Context Menu. When the user selects a
particular item on this context menu, the message box will appear with the corresponding
message that tells about that particular item in the context menu. For example, when the
user selects the Context MI1, the message should be, “Context Menu Item 1 with
check-mark clicked!”. This also goes the same with other context menu items.
Note:
To try to know if your Context Menu is working properly, point now to the blank space
of your Form, then right-click the mouse on it. Can you see your Context Menu? If not,
then probably, you need the Warning instruction below
Warning!
Be sure to associate the Context Menu to Form1 control by setting the Form1
ContextMenuStrip property to the name of the Context Menu such as
contextMenuStrip1. Failure to do so will cause the Context Menu not to appear in your
application system.
Tip:
The Code designer is also commonly called the Code Editor.
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csMyContextMenu1. Now click the OK
button.
4. Set the Form’s Text property to vbMyContextMenu1.
5. Click, drag and drop a MenuStrip control (click All Windows Forms) from the
Toolbox, to add it to the Form.
6. Click the Type Here tag, type Menu1, and then press the Enter key.
7. Now, under the Menu1, type M1 Item 1 as your first item at Menu 1. Next, type
M1 Item 2 as your second item for Menu 1, then type Exit. Now point the
mouse-pointer at the Exit menu item then right-click the mouse. After that, select
the Insert item and finally select the Separator to be place between M1 Item 2 and
Exit menu items. (See the given figure above to easily compare your work).
296
8. This time, you have to type Menu2 beside Menu1, and then press the Enter key.
9. Now, under the Menu2, type About Me? as your first item at Menu 2. Next, type
Close as your second item for Menu 2. (See the given figure above to easily
compare your work).
10. Now right-click M1 Item 1 menu item, and set its Image property to
vbIEicon1.png. Import this .png icon file from your MyPictures folder.
11. This time, right-click M1 Item 2 menu item, and set its Image property to
vbCameraicon1.png. Import this .png icon file from your MyPictures folder.
12. Double-click now the Menu1 Item 1 (M1 Item 1) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1Item1ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu 1 Item 1 clicked!");
}
13. Double-click now the Menu1 Item 2 (M1 Item 2) to display the Code designer.
Embed the following code to the menu item Click event method:
private void m1Item2ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu 1 Item 2 clicked!");
}
14. Double-click now the Menu1 Item 3 (Exit) to display the Code designer. Embed
the following code to the menu item Click event method:
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
15. Double-click now the Menu2 Item 1 (About Me?) display the Code designer.
Embed the following code to the method:
private void aboutMeToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutBox1 frmAboutBox1 = new AboutBox1();
frmAboutBox1.Show();
}
16.Double-click now the Menu2 Item 2 (Close) to display the Code designer. Embed the
following code to the menu item Click event method:
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
17.Now double-click the first icon which is the vbIEicon.png, then embed the following
code to the ToolStrip Button1 Click event method:
297
18.Now double-click the second icon which is the vbCameraicon.png, then embed the
following code to the ToolStrip Button2 Click event method:
private void toolStripButton2_Click(object sender, EventArgs e)
{
MessageBox.Show("Camera icon(Toolbar 2) is clicked!");
}
20.This time, we will add a ContextMenu. Let us now click, drag and drop a
ContextMenuStrip control (click All Windows Forms) from the Toolbox to add it into
the Form.
21.This time we have to type all the menu items of the ContextMenu. So, at the Type
Here tag, we will type, Context MI1, then Context MI2, Copy, Cut, and Context TI1,
Paste, and Context TI3, respectively.
22.Point your mouse-pointer at Context MI1, then right-click the mouse and select the
Checked item to put a check beside it.
23.Point your mouse-pointer at Context TI3, then right-click the mouse and select the
Checked item to put a check beside it.
24.Double-click now the ContextMenu Item 1 (Context MI1) to display the Code
designer. Embed the following code to the context menu item Click event method:
private void contextMI1ToolStripMenuItem_Click(object sender, EventArgs
e)
{
MessageBox.Show("Context menu Item 1 clicked!");
}
25.Double-click now the ContextMenu Item 2 (Context MI2) to display the Code
designer. Embed the following code to the context menu item Click event method:
private void contextMI2ToolStripMenuItem_Click(object sender, EventArgs
e)
{
MessageBox.Show("Context menu Item 2 clicked!");
}
26.Double-click now the ContextMenu Item 3 (Copy) to display the Code designer.
Embed the following code to the context menu item Click event method:
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Copy Context menu Item clicked!");
}
27.Double-click now the ContextMenu Item 4 (Cut) to display the Code designer.
Embed the following code to the context menu item Click event method:
298
28.Double-click now the ContextMenu Item 5 (Context TI1) to display the Code
designer. Embed the following code to the context menu item Click event method:
private void contextTI1ToolStripMenuItem_Click(object sender, EventArgs
e)
{
MessageBox.Show("Context menu TI1 clicked!");
}
29.Double-click now the Context Menu Item 6 (Paste) to display the Code editor.
Embed the following code to its respective methods:
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Paste Context menu Item clicked!");
}
30.Double-click now the ContextMenu Item 7 (Context TI3) to display the Code
designer. Embed the following code to the context menu item Click event method:
private void contextTI3ToolStripMenuItem_Click(object sender, EventArgs
e)
{
MessageBox.Show("Context menu TI3 clicked!");
}
31.Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
299
Explanation:
Here, we are using the Message Box method to display a message when the user clicks a
particular menu item or a particular toolbar icon. The message tells what particular menu
item or toolbar was clicked and in what particular menu title that menu item belonged to.
Like for instance, when we click the M1 Item 1, the message “Menu 1 Item1 clicked!”
will appear in a message box. This can be accomplished with the following code:
The preceding code above has similar effect and code construction with the other code in
our program. So there is no need for us to inspect them in details.
Here in this example, when we right-click the mouse, the Context menu will appear. We
can now select some of its items to test if it works. Once we select the Context Menu
Item 2, the message should be, “ ContextMenu Item 2 clicked!”. We can accomplish this
task through the following code:
The above code has similar effect and code with the other code in our program. There is
no need for us to explain them in details.
301
LAB ACTIVITY
TEST 6
1. Design and develop a simple menu-based application system that demonstrates how to
create a simple menu system with the following menu title: Menu1, Menu2, and Help.
Follow the given figures below in designing and developing the application program:
Form1
Note:
When the user clicks the Item One, the Message box will display “Item One clicked!”.
When the user clicks the Item Two, the Message box will display “Item Two clicked!”
and so on. When the user clicks the First Item, the Message box will display “First Item
clicked!”. When the user clicks the Second Item, the Message box will display “Second
Item clicked!” and so on.
When the user clicks the Help 1, the Message box will display “Help 1 clicked!”. And
when the user clicks the Help 2, the Message box will display “Help 2 clicked!”.
Form1
Form1
2. Design and develop a simple menu-based application system that demonstrates how to
create a simple menu system with the following menu title: Box, Button, and Help.
Follow the given figures below in designing and developing the application program:
Form1
Form1
Form1
Note:
When the user clicks the Text box, the Form2 that contains Text boxes will appear. When
the user clicks Check box, the Form3 that contains Check boxes will appear, and so on.
It’s up to you what kind of box design you want, as long as that particular box or button,
will appear when it is selected or clicked! You can also use Dialog boxes if you want,
instead of a Form, as long as your program can satisfy the given minimum requirements.
When the user clicks the Need Help, the Message box will display “Need help? Call
911!” When the user selects About Help, the following About dialog box should appear:
3. Design and develop a simple menu-based application system that demonstrates how to
create a simple toolbar with the following icons: blank paper, open folder, diskette,
printer and arrow key. Follow the given figures below in designing and developing the
application program:
Form1
Note:
When the user clicks the first button at the toolbar of our simple menu system, the
Message box that says “First button clicked!” will be displayed. When the user clicks the
second button at the toolbar, the Message box that says “Second button clicked!” will be
displayed and so on. The icon of the first button (in the toolbar) is a blank paper page, the
304
icon of the second button is an open folder, the icon of the third button is a diskette, the
icon of the fourth button is a printer, and the icon of the fifth button is an arrow key.
4.Design and develop a simple menu-based application system that demonstrates how to
create a simple toolbar with the following icons: blank paper, open folder, diskette, and
printer. This time, once the user clicks the icon in the toolbar, another form will appear.
Follow the given figure below in designing and developing the application program:
Form1
Form2
Grapes
Note:
When the user clicks the first Toolbar button, the Form2 that contains a Combo box
(preloaded with 5 or more items) will be displayed. When the user clicks the second
Toolbar button, the Form3 that contains a List box (preloaded with 5 or more items) will
be displayed. When the user clicks the third Toolbar button, the Form4 that contains both
Combo box and List box (both are preloaded with 5 or more items) will be displayed.
It’s up to you what kind of items you would like to put at the list box and combo box.
These 5 or more items could be a list of your favorite fruits such as Banana, Apple,
Orange, Grapes, Cherries, or Pears. Or a list of your favorite foods: pizza, burger,
sandwich, hotdog, or pie. Indulge now with these foods (joke). Satisfy your hunger (joke,
again). I think I’m hungry now (what do you think?).
5.Design and develop a simple menu-based application system that demonstrates how to
create a simple menu system with the following menu title: Menu1, Menu2, and Menu3.
Follow the given figures below in designing and developing the application program:
305
csYourMenu2
csYourMenu2
Menu title
Menu1 Menu2 Menu3
M2 Item1
Menu items M2 Item2
M2 Item3
M2 Item4
Form1
Note:
Between Menu 1 Item 4 (M1 Item4) and Exit menu item is a Line Separator.
Menu 2 Item 1 (M2 Item1) and Menu 2 Item 3 (M2 Item3) are checked, while Menu 2
Item 2 was disabled by default. This will be enabled once the Menu3 Item2 is clicked.
Once the Menu 3 Item 1 (M3 Item1) is clicked, the hidden Menu3 Item2 (M3 Item2) will
appear suddenly.
The image property of M1 Item 1 should be the Bing icon, while the image property of
Exit should be the Microsoft Excel 2013 (or newer) icon.
The Toolbars should have the following image properties as their respective icon: Travel
for the first Toolbar, Video for the second Toolbar, and Weather for the third Toolbar.
The image property of M2 Item 4 should be the Microsoft Word 2013 (or newer), while
the image property of Exit should be the Microsoft PowerPoint 2013 (or newer). You
can get these icon image (.pngs) through your computer screen-shots (by pressing the prt
sc [Print Screen]) key in your keyboard. And with the help of the Paint software. So, do it
now, buddy!
Warning!
Be sure that the Property of each Control is properly set, to reflect the needed and actual requirements of
the output.
6.Design and develop a simple menu-based application system that demonstrates how to
create a simple ContextMenu. Moreover, your program must be able to demonstrate on
how to put an image or icon beside the menu items, specifically at M1 Item 1, M1 Item 2,
and M1 Item 3 menu items of Menu1. Follow the given figures below in designing and
developing the application program:
csMyContextMenu1
Menu1 Menu2
M1 Item1
icons
M1 Item2
M1 Item3
Restore
Minimize
Exit Cut
Copy
Paste
Close
csMyContextMenu1
Menu1 Menu2
About Me?
Close
Restore
Minimize
Cut
Copy
Paste
Close
Note:
When the user clicks the Menu 1 - Item 1, the message “M1 Item1 with Video icon was
clicked!” will be displayed at the Message box; when the user clicks the Menu1 – Item 2,
the message “M1 Item2 with Weather was clicked!” will be displayed at the Message
box, when the user clicks the Menu1 – Item 3, the message “M1 Item 3 with Sports icon
was clicked!” and when the Exit item of Menu 1 is clicked by the user, the menu program
will exit right away. When the user clicks the Menu 2 – Item 1, the About Dialog box
will be displayed, and when the user clicks the Menu2 – Item 2, which is the Close menu
item, it will close the application system. Now, when the user right-click the mouse, the
Context Menu will appear. In this juncture, the user can now select the items in the
Context Menu. When the user selects a particular item on this context menu, the message
box will appear with the corresponding message that tells about that particular item in the
context menu. For example, when the user selects the ContextMenu Item1, the message
should be, “Restore context menu was clicked!”. This also goes the same with other
context menu items.
Take Note:
To try to know if your Context Menu is working properly, point now to the blank space
of your Form, then right-click the mouse on it. Can you see your Context Menu? If not,
then probably, you need the Warning instruction below
Warning!
Be sure to associate the Context Menu to Form1 control by setting the Form1
ContextMenuStrip property to the name of the Context Menu such as
contextMenuStrip1. Failure to do so will cause the Context Menu not to appear in your
application system.
308
Chapter 10
Developing Simple ADO.NET Database Connectivity
Most of the Visual C# applications that we design and develop involve the use of
data or information in some form. One of the most common types of application that we
are likely to develop is a data-driven application which operation is usually to retrieve
and process data. The most common database software that we will encounter when
developing data-driven application are SQL Server, Oracle, MySQL, IBM DB2, and
PostgreSQL.
We need to learn the ADO.NET components because these components are at the
heart of developing database applications. Moreover, they provide the necessary classes
that enable us to connect to a datastore and to retrieve, manipulate, and update data.
ADO.NET stands for ActiveX Data Objects which is the premiere data access technology
of Microsoft. The ADO.NET technology provides a user-friendly interface for accessing
data in any type of database and was accessible to programmers coding in most of
programming languages.
Visual C# is not designed for creating new databases or tables, but rather can be
used for displaying, manipulating, and analyzing the data in existing databases. A
database is simply a systematic way of collecting, organizing, and managing of data.
Creating, managing, and maintaining databases has become an essential task for all
companies, government agencies, and even small businesses.
Data resources such as sales records, ATM accounts, inventory controls, patients
files, payroll system, enrollment system, online reservation system, and many others have
become the lifeblood of the business operation and critical to its survival and prosperity.
ADO.NET has been designed for Internet database access and manipulation. This means
that it uses the same method for accessing Intranet-based, Internet-based, LAN-based or
client/server-based data resources.
The Visual C# provides data wizards that assist us in creating connections to our
database, like when we are retrieving and updating data. When building database
application using data controls, we need these three components: DataSet,
BindingSource, and TableAdapater. We can find the BindingSource and DataSet controls
in the Toolbox while the TableAdapter is automatically generated when we develop
database application.
The DataSet component is a cache of data stored in memory. It stores a rich
amount of metadata such as column names, table, data types, and the needed information
to manage and undo changes to the data.
The BindingSource component acts like a bridge between DataSet (data source)
and our data bound controls such as DataGridView, TextBox, or ListBox. Any
309
interaction with the data from our controls goes through the BindingSource component,
which in turn communicates with our data source.
The TableAdapter contains the query used to select data from our database and
the connection information for connecting to our database. It also contains the methods
that fill the DataSet in our project with data from the database. Furthermore, we can also
choose to have the TableAdapter generate the insert, delete, and update statements based
on the query that is used to select data.
Tip:
Metadata means the data about the data.
Example 1:
Design and develop a simple application system that contains a DataGridView control
bound to the *AdventureWorks2012_Data database file. At the ContactType table, select
the ContactTypeID, Name, and ModifiedDate columns to be displayed on the
DataGridView control. Follow the given figure below in designing and developing the
application program:
310
vbDataGridView4
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csDataGridView4. Now click the OK button.
4. Set the Form’s Text property to vbDataGridView4.
5. Now, click and drag a DataGridView control from the Toolbox and drop it on the
Form.
6. Click the drop-down arrow in the Choose Data Source combo box and then click
the Add Project Data Source link at the bottom of the list that is displayed. This
causes the Data Source Configuration Wizard to be displayed as shown below:
312
7. Now click the Next button (be sure that the Database is highlighted by default, if
not then select it). Click the Next button again when prompted to do so.
8. Click the New Connection button. At the Add Connection dialog box, click the
Change button. Now this time select Microsoft SQL Server Database File and
click the Continue button. The Data Source dialog box should look like the
following:
313
9. At the Add Connection dialog box, click the Browse button. Now find and select
the AdventureWorks2012_Data database file in your computer. You can find this
AdventureWorks2012_Data database file by downloading it from the Internet.
Just search it using the Google search engine. After you successfully downloaded
the AdventureWorks2012_Data database file into your computer, you can now
search it. When you find it, select it, and then click the Open button.
Your Add Connection dialog box should look like the following:
314
If the connection to the specified database is successful, then the following message box
will show up:
11. Click the OK button to close the message box, and then click another OK button
to close the Add Connection dialog box.
Now the Visual Basic displays the Data Source Configuration Wizard again.
This time, we are prompted to select the subset of database objects that we want to
use for this particular project, as shown below:
15. Click the arrow icon next to the Tables node to expand the list of the table.
16. Click the arrow icon next the ContactType table, then select all its respective
columns (fields): ContactTypeID, Name, ModifiedDate. After the selection, click
the Finish button.
316
17. Adjust to enlarge your Form now, to accommodate the three table columns,
namely: ContactTypeID, Name, and ModifiedDate.
18. At the DataGridView Properties window, click the Dock property and select the
center big square (Fill) then click it.
The Dock property now is set to Fill value. Can you see it?
19. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
The DataGridView control is a tool that gives us a way of seeing the data in our database
through a spreadsheet format. The spreadsheet format displays the columns of data
horizontally and the rows of data vertically. We are very familiar with this kind of data
presentation, because we usually use Microsoft Excel spreadsheet software. We can see
the Data Source Connection Wizard that automatically prepares our program to receive
database data. The wizard prompts us for the type of database that we will be connecting
to – whether a local database (database that resides directly in our computer’s hard disk)
or remote database (database that resides in our company’s LAN Server or Intranet
Server) or probably a database coming as a Web service. Furthermore, the wizard will
prompt us to establish a connection to the data and then creates a dataset within the
program to hold specific database tables and columns. The end result is that the wizard
317
opens the Data Sources window and fills it with a visual representation of each database
object that we can use in our program.
We can click the column header to have data in the DataGridView to be sorted in
ascending order. By clicking the same column header again will sort the data in
descending order. We can try this one in the Name header. Let us do it now! Can you see
the difference? I hope so.
You could notice that each sort order is indicated with an arrow pointing up for ascending
order, and down for descending order.
How about formatting the DataGridView cells with an alternating rows? Let us try it
now!
This time, we will format the DataGridView cells with an alternating rows default
cellstyle BackColor property of light yellow color (255,255, 192). Follow the given
figure below in designing and developing the application program:
vbDataGridView4
Solution:
Sample Output:
318
Example 2:
Design and develop a simple application system that contains three labels and three text
box controls which bind your data source to the ContactType table of the
AdventureWorks2012_Data database file. At the ContactType table, select the
ContactTypeID, Name, and ModifiedDate columns to be displayed on the text box
controls. Place a Binding Navigator control at the top. Follow the given figure below in
designing and developing the application program:
vbTextBoxBind4
ContactTypeID:
Name:
ModifiedDate:
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csTextBoxBind3. Now click the OK button.
4. Set the Form’s Text property to vbTextBoxBind3.
5. This time, select the Data Sources tab at the top extreme left-side of the Visual
Studio IDE. Then, click the Add New Data Source… link (in blue color).
The Data Source Configuration Wizard appears in the IDE, as shown below:
6. Now click the Next button (be sure that the Database is highlighted by default, if
not then select it). Click the Next button again when prompted to do so.
320
7. Click the New Connection button. At the Add Connection dialog box, click the
Change button. Now this time select Microsoft SQL Server Database File and
click the Continue button. The Data Source dialog box should look like the
following:
8. At the Add Connection dialog box, click the Browse button. Now find and select
the AdventureWorks2012_Data database file in your computer. You can find this
AdventureWorks2012_Data database file by downloading it from the Internet.
Just search it using the Google search engine. After you successfully downloaded
the AdventureWorks2012_Data database file into your computer, you can now
search it. When you find it, select it, and then click the Open button.
Your Add Connection dialog box should look like the following:
321
If the connection to the specified database is successful, then the following message box
will show up:
10. Click the OK button to close the message box, and then click another OK button
to close the Add Connection dialog box.
Now the Visual Basic displays the Data Source Configuration Wizard again.
This time, we are prompted to select the subset of database objects that we want to
use for this particular project, as shown below:
14. Click the arrow icon next to the Tables node to expand the list of the table.
15. Click the arrow icon next the ContactType table, then select all its respective
columns (fields): ContactTypeID, Name, ModifiedDate. After the selection, click
the Finish button.
323
When you click the Data Sources window, you can now see the ContactType table
object, as shown in the figure below:
16. Now at the Data Sources window, select the ContactTypeID column, then click
the arrow next to it, then select the Textbox item. This time, drag the
ContactTypeID into the Form. Do the same with Name, and ModifiedDate
columns.
17. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
We can see the Choose Your Data Connection dialog box which helps us to establish a
connection to our database by building a statement called a connection-string. A
connection string contains the information that Visual Basic needs to open and extract
information from a database file. This includes a path and a filename, as well as
username and password of the database user. Since the username and password are
included in the connection string, we have to protect it from any unauthorized access.
We can see also the Data Sources window that displays a visual representation of the
datasets that have been configured for use within your project, and to help us bind these
datasets to controls on the Form. We have to remember that a dataset is just a temporary
representation of database data in our program, and that each dataset contains only a
subset of the tables and columns within our entire database file. These are the items we
selected while using the Data Source Configuration Wizard.
325
In real-world application design and development, we are really connecting to our own
database schema. Unlike in the examples we presented here earlier, we simply use a
database file that was created by Microsoft Corporation which is the
AdventureWorks2012_Data. This is a test database file which most of the official manual
(not to mention the official database file used by the authors who write books about
database design and development) of the Microsoft products and technologies are using
to demonstrate the enormous power and capabilities of SQL Server Database to
manipulate complex data structures.
Starting SQL Server and Management Studio is so easy. Follow the following steps
to run them in tandem:
1. From the Start tab of the Windows 8 operating system, select and click the SQL
Server 2012 Management Studio.
2. Then, click the Connect button.
Once you are successfully connected to the SQL Server Database engine - by using the
SQL Server Management Studio, you will see the following figure:
326
Creating a Database
Before we can work with SQL Server 2012, we have to create first a practice database.
To create a database, follow the following steps, carefully:
Step 1. Right-click on the Databases in the Object Explorer, then select New
Databases…from the Context Menu that pops up, as you can see at the following figure:
327
After that, you will get the New Database dialog box as you can see at the following
figure below:
Creating a Table
We need to create a table, because the data is loaded (stored) into tables that are created
in a database.
Let us now have our actual demonstration on how to create a table. We have here two
examples.
Example 4:
EmployeeNumber INT
Name VARCHAR 15
Salary SMALLMONEY
329
Solution:
1. Select the Database1 database at the Object Explorer window, then select and
click the New Query item at the pop-up menu.
2. Type now the following script at the SQL Server Management Studio Query
Editor:
If we had created our table successfully, we can see the following message at the
Messages tab:
Command(s) completed successfully.
3. Then, input the following data values by using the INSERT command:
(1 row(s) affected)
(1 row(s) affected)
. . .
. . .
(1 row(s) affected)
Now, that we have already stored a test data into our database table called Emp1, we are
now ready to connect to our database. Remember, that in reality - a database is a
collection of related tables.
Now if we would like to use our own database file, in this case we named it: Database1;
we will try the succeeding examples.
Example 3:
Design and develop a simple application system that contains a DataGridView control
bound to the Database1 database file that we created at the SQL Server Management
Studio. At the Emp1 table, select the EmpNo, Name, and Salary columns to be displayed
on the DataGridView control. Follow the given figure below in designing and developing
the application program:
vbDataGridView3
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csDataGridView3. Now click the OK button.
4. Set the Form’s Text property to vbDataGridView3.
5. Now, click and drag a DataGridView control from the Toolbox and drop it on the
Form.
6. Click the drop-down arrow in the Choose Data Source combo box and then click
the Add Project Data Source link at the bottom of the list that is displayed. This
causes the Data Source Configuration Wizard to be displayed as shown below:
332
7. Now click the Next button (be sure that the Database is highlighted by default, if
not then select it). Click the Next button again when prompted to do so.
8. Click the New Connection button. At the Add Connection dialog box, click the
Change button. Now this time select Microsoft SQL Server and click the OK
button.
9. This time, we have to select our Server name. Select it now (to whatever name
you have assigned to your computer and the corresponding SQLExpress you have
installed into it. (In my case it is: MYHPLAPTOP\SQLEXPRESS).
10. At this junction, we have to select (or enter) our Database name. We have to
select the Database1.
Your Add Connection dialog box should look like the following:
333
11. Now, let us test our database connection by clicking the Test Connection button.
12. Click the OK button to close the message box, and then click another OK button
to close the Add Connection dialog box.
Now the Visual Basic displays the Data Source Configuration Wizard again.
13. Click the Next button. Then, click another Next button again when prompted.
This will save the default connection string.
This time, we are prompted to select the subset of database objects that we want to
use for this particular project, as shown below:
14. Click the arrow icon next to the Tables node to expand the list of the table.
15. Click the arrow icon next to the Emp1 table, then select all its respective columns
(fields): EmpNo, Name, Salary. After the selection, click the Finish button.
16. Adjust to enlarge your Form now, to accommodate the three table columns,
namely: EmpNo, Name, and Salary.
17. At the DataGridView Properties window, click the Dock property and select the
center big square (Fill) then click it.
335
The Dock property now is set to Fill value. Can you see it?
18. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
Explanation:
The DataGridView control is a tool that gives us a way of seeing the data in our database
through a spreadsheet format. The spreadsheet format displays the columns of data
horizontally and the rows of data vertically. We are very familiar with this kind of data
presentation, because we usually use Microsoft Excel spreadsheet software. We can see
the Data Source Connection Wizard that automatically prepares our program to receive
database data. The wizard prompts us for the type of database that we will be connecting
to – whether a local database (database that resides directly in our computer’s hard disk)
or remote database (database that resides in our company’s LAN Server or Intranet
Server) or probably a database coming as a Web service. Furthermore, the wizard will
prompt us to establish a connection to the data and then creates a dataset within the
program to hold specific database tables and columns. The end result is that the wizard
opens the Data Sources window and fills it with a visual representation of each database
object that we can use in our program.
We can click the column header to have data in the DataGridView to be sorted in
ascending order. By clicking the same column header again will sort the data in
336
descending order. We can try this one in the Name header. Let us do it now! Can you see
the difference? I hope so.
You could notice that each sort order is indicated with an arrow pointing up for ascending
order, and down for descending order.
How about adding and putting a Binding Navigator into our Data Grid View so that we
can edit, save or delete a particular record? This is a very good idea! Isn’t it? Let us try it
now!
Follow the given figure below in designing and developing the application program:
vbDataGridView3
Solution:
Sample Output:
337
Example 4:
Design and develop a simple application system that contains three labels and three text
box controls which bind your data source to the Emp1 table of the Database1 database
file. At the Emp1 table, select the EmpNo, Name, and Salary columns to be displayed on
the text box controls. Place a Binding Navigator control at the top. Follow the given
figure below in designing and developing the application program:
vbTextBoxBind4
EmpNo:
Name:
Salary:
Solution:
1. Start Microsoft Visual Studio Express 2012 for Windows Desktop by clicking the
Start tab at your Windows 8 operating system. Now Start a New Project. Select
the Visual C# template.
2. Under the Visual C# template, select the Windows option. Finally, select the
Windows Forms Application new project template.
3. Name the new application system csTextBoxBind4. Now click the OK button.
4. Set the Form’s Text property to vbTextBoxBind4.
5. This time, select the Data Sources tab at the top extreme left-side of the Visual
Studio IDE. Then, click the Add New Data Source… link (in blue color).
The Data Source Configuration Wizard appears in the IDE, as shown below:
6. Now click the Next button (be sure that the Database is highlighted by default, if
not then select it). Click the Next button again when prompted to do so.
339
7. Click the New Connection button. At the Add Connection dialog box, click the
Change button. Now this time select Microsoft SQL Server and click the OK
button.
8. This time, we have to select our Server name. Select it now (to whatever name
you have assigned to your computer and the corresponding SQLExpress you have
installed into it. (In my case it is: MYHPLAPTOP\SQLEXPRESS).
9. At this junction, we have to select (or enter) our Database name. We have to
select the Database1.
Your Add Connection dialog box should look like the following:
10. Now, let us test our database connection by clicking the Test Connection button.
340
11. Click the OK button to close the message box, and then click another OK button
to close the Add Connection dialog box.
Now the Visual Basic displays the Data Source Configuration Wizard again.
12. Click the Next button. Then, click another Next button again when prompted.
This will save the default connection string.
This time, we are prompted to select the subset of database objects that we want to
use for this particular project, as shown below:
341
13. Click the arrow icon next to the Tables node to expand the list of the table.
14. Click the arrow icon next to the Emp1 table, then select all its respective columns
(fields): EmpNo, Name, and Salary. After the selection, click the Finish button.
When you click the Data Sources window, you can now see the Emp1 table object, as
shown in the figure below:
342
3. Now at the Data Sources window, select the EmpNo column, then click the arrow
next to it, then select the Textbox item. This time, drag the EmpNo into the Form.
Do the same with Name, and Salary columns.
15. Build and execute the application system by clicking the Start debugging icon (or
press F5) at the Toolbar which color is a green arrow.
Sample Output:
343
Explanation:
We can see the Choose Your Data Connection dialog box which helps us to establish a
connection to our database by building a statement called a connection-string. A
connection string contains the information that Visual Basic needs to open and extract
information from a database file. This includes a path and a filename, as well as
username and password of the database user. Since the username and password are
included in the connection string, we have to protect it from any unauthorized access.
We can see also the Data Sources window that displays a visual representation of the
datasets that have been configured for use within your project, and to help us bind these
datasets to controls on the Form. We have to remember that a dataset is just a temporary
representation of database data in our program, and that each dataset contains only a
subset of the tables and columns within our entire database file. These are the items we
selected while using the Data Source Configuration Wizard.
344
LAB ACTIVITY
TEST 7
vbDataGridView9
2. Design and develop a simple application system that contains three labels and
three text box controls which bind your data source to the Currency table of the
AdventureWorks2012_Data database. At the Currency table, select the
CurrencyCode, Name, and ModifiedDate columns to be displayed on the text box
controls. Follow the given figure below in designing and developing the
application program:
vbTextBoxBind9
CurrencyCode:
Name:
ModifiedDate:
345
General Instruction:
Use your own database. Create now that database and named it as MyDatabase2. Apply
the following steps to create it:
Step 1. Right-click on the Databases in the Object Explorer, then select New
Databases…from the Context Menu that pops up.
Step 2. Type MyDatabase2 at the Database Name box.
Step 3. Lastly, click the OK button.
All the tables in the LAB ACTIVITIES that you will solve must be created within your
own MyDatabase2 database.
Apply the CREATE TABLE clause, create a table called Student1. The following are its
field names (column names) and their respective data types:
StudentNumber SMALLINT
StudentName VARCHAR 20
Grade TINYINT
Applying the INSERT INTO…VALUES clauses, input the following values into
Student1 table:
3.Design and develop a simple application system that contains a DataGridView control
bound to the MyDatabase2 database. At the Student1 table, select the StudentNumber,
StudentName, and Grade columns to be displayed on the DataGridView control. Follow
the given figure below in designing and developing the application program:
346
vbDataGridView9
4.Design and develop a simple application system that contains three labels and three text
box controls which bind your data source to the Student1 table of the MyDatabase2
database. At the Student1 table, select the StudentNumber, Student Name, and Grade
columns to be displayed on the text box controls. Follow the given figure below in
designing and developing the application program:
vbTextBoxBind9
Student Number:
Student Name:
Grade:
5.Design and develop a simple application system that contains a DataGridView control
bound to the MyDatabase2 database. At the Student1 table, select the Student Number,
Student Name, and Grade columns to be displayed on the DataGridView control. This
time, format the DataGridView cells with an alternating rows default cellstyle BackColor
property of Light Green. Then, you have to add and put a Binding Navigator into our
DataGridView so that we can edit, save or delete a particular record. Follow the given
figure below in designing and developing the application program:
347
vbDataGridView9
Chapter 9
Developing Simple ASP.NET Web Application
We can actually design a simple web site using HTML5 only. Now, this is only
good if we are just presenting static data (or information) to our targeted end-users. If we
want to add some limited intuitive presentation, we can apply DHTML (Dynamic
Hypertext Markup Language) on the web page that we designed. Now, to allure our
target users (web surfers), we can employ some third party software that will make our
web page presentation more animated or even multimedia-powered. This is possible by
using Dreamweaver and Macromedia Flash third-party software for designing web sites.
How about developing an interactive web page where we can validate the data
entered by our frequent web surfers? This can be in the form of survey data, personal-
identification data, or any data that need to be validated before they can be submitted to
the web server? This time, we need to employ the power of JavaScript language to
accomplish this challenging job.
The next question now is: how about a data-driven website? Meaning, what if we
want to present voluminous or live data to our users that are coming from our database
software such as SQL Server, Oracle Database, IBM DB2, MySQL, or PostgreSQL?
Definitely, this monumental task can only be accomplished using the ASP.NET (Active
Server Pages) software technology or with a competing products such as JSP (Java
Server Pages) or PHP. In other words, this task is beyond the capability of HTML5 or
JavaScript. So, we really need to learn website development using *Microsoft Visual
Studio Express for Web software this time. Are you ready now? I hope so!
*Warning!
You are required to install the Microsoft Visual Express 2012 for Web to successfully design and develop
the examples presented in this chapter
Inside Webpages
The webpage that we will develop in ASP.NET consist of two pieces: Web Forms
Page and Source Code File. The Web Forms Page contains HTML and controls (objects)
to create the user-interface, while the Source Code File contains the program code that
“works-behind” the Web Forms page.
This division is conceptually much like the way we do with Windows Forms Application
where there is a graphical-user-interface component (GUI) and a program code
component. Typically, the Web Forms page is stored in a file with filename extension of
.aspx, while the program code-behind source file is stored with filename extension of
.aspx.cs.
But we have to always remember that in addition to Web Forms Page file and Program
Code Source file (code-behind file), the Website that we will develop can contain other
349
program code modules (.cs files), other HTML pages (.html files), Web configuration
information (Web.config file) and even global Web application information (Global.asax
file).
Many Web page controls are server controls, which means: they run on the Web
server and they have an “asp” prefix in their tag. The HTML controls are by default –
client controls, which means they run only within the end-user’s web-browser.
Finally, take note the important difference between developing Website and
Windows Forms Application. In Windows Form Application development, the Windows
Form is our primary user-interface for our program while in Website application
development, the Webpage is the primary user-interface for our program.
Example 1:
Design and develop a simple web application system that converts dollar into its
equivalent peso exchange rate. Follow the given figure below in designing and
developing the application program:
csWebApp1a
$-Dollar Amount
Text
Boxes Peso Exchange Rate
Compute Now!
Button
Solution:
1. Start Microsoft Visual Studio Express 2012 for Web by clicking the Start tab at
your Windows 8 operating system. Now Start a New Project. Select the Visual C#
template.
2. Under the Visual C# template, select the Web option. Finally, select the ASP.NET
Web Forms Application new project template.
3. Name the new application system csWebApp1a. Now click the OK button.
4. This time, select and click the Design tab at the bottom part of our Web Page
Designer.
You can now see the ASP.NET Application template that is pre-designed for us:
5. This time, let us now modify the ASP.NET Application template according to our
Website design specs above. Type now the specified information at the Web
Page Designer.
Tip:
The most important thing to remember is that in the Web Page Designer, controls
are inserted at the insertion point. Meaning, the control that we double-click from
the Toolbox will be inserted right-through where our blinking cursor is.
351
6. Now, position the blinking cursor where you want to put the controls. Then,
double-click that specific control icon in the Toolbox. Here, we need 3 text boxes,
3 labels, and 1 button controls. Design it now!
Our website skeleton design should look like the following:
7. Let us set the Properties for the objects (controls) on our Web Form:
TextBox1 ID txtDAmount
TextBox2 ID txtPERate
TextBox3 ID txtTPCRate
ReadOnly True
Label1 ID lblDAmount
Text “$-Dollar Amount”
Label2 ID lblPERate
Text “Peso Exchange Rate”
Label3 ID lblTPCRate
Text “Total Peso Converted Rate”
Button1 ID btnCompute
352
8. Let us now write the event-handling method for our Compute Now! button
Webpage control. Double-click the Compute Now! button. Then, embed the
following code (in bold only):
Sample Output:
353
Explanation:
The first thing we noticed in designing a webpage is that our Toolbox contains the
basic controls that are used only specifically for Web programming, however only
in icon format. We need to point our mouse-pointer to a particular control to
know it well (because the tooltip will appear to tell what that icon really is).
The second thing you will noticed is that unlike in Windows Forms Application, a
web page can have text added into it, while it is in the Design view of the Web
Page Designer.
In Design view, the text appears in top-to-bottom fashion like we see in word-
processing software such as Microsoft Word. In Source view, the text appears
within HTML tags like the way we see in our Visual Studio Code Editor, though
however - the codes are in HTML code structure and formatting.
The third thing we will noticed that when programming our event-handling
method, we just simply apply the regular Visual Basic programming syntax. Well,
this is really a great bonus, because Web Application programming is similar with
Windows Form Application programming when it comes to code development.
So, are you happy now? I hope so.
Now, since we want to convert a string data (though we enter it as number in our
text boxes, it is still a string data) into numeric data for our computation purposes,
we applied the double-precision floating-point Convert.Double function, as you
could notice it in our code below:
txtTPCRate.Text = Convert.ToString(nTPCRate);
}
We also apply the Convert.ToString function, so that the computed numeric data will be
converted to its string equivalent so that we can display it in our text box without any
trouble.
Now, this time you can be pretty sure that developing and viewing a Website is basically
the same as developing and running a Windows Form Application, except that the
Website is executed in the web browser environment. So, feel comfortable, for you don’t
need to learn a lot in designing and developing website. For you had already learned the
basic and fundamental knowledge and skills, buddy.
How about additional webpages and resources to our website? Such as an HTML
webpage Help Page? This is the fun side of it! We will just add a Hyperlink to our main
webpage (HomePage).
It is so simple. When the user clicks the “Need Help?” hyperlink, our HTML webpage
(Help Page) will appear. Let us try it now.
Follow the slightly modified figure below in designing and developing the application
program (by just adding a Hyperlink control on it):
vbWebApp1a
$-Dollar Amount
Text
Boxes Peso Exchange Rate
Compute Now!
Button
Hyperlink1
Need Help?
Figure 9.1b Web Application Default Page with Help Page Hyperlink 1
355
Solution:
1. At the Menu Bar, select the Project menu, then select the Add New Item
submenu. Now, select the Web option. Then select the HTML Page new item.
2. Name the new application system csDPConversionHelp.html. Now, click the
Add button.
3. This time, select and click the Design tab at the bottom part of our Web Page
Designer. Type now the specified information at the Web Page Designer:
Type the Amount of Dollar on the text box provided, well without the dollar
sign. Just put the numerical figure. Then next, type the Peso Exchange Rate on
the text box provided. You can get the information about the exact Peso
Exchange Rate from the daily news reported through TV stations or printed
newspapers or even through the Internet news.
Finally, click the Compute Now! button to compute the Total Peso Converted
Rate. That’s all folks! Thank you.
4. Now at the Menu bar, click the Save All menu item.
5. This time, click the Default.aspx tab at the top of the Web Page Designer. Place
the insertion point below the Compute Now! button by just pressing the Enter key
in the keyboard.
6. Now double-click the HyperLink control icon in the Toolbox to create a hyperlink
object at the insertion point (the place where our blinking cursor is positioned).
Finally, set the Text property of the hyperlink object to “Need Help?”.
7. This time, set the ID property of the hyperlink object to “lnkDPCHelp”.
8. Click the NavigateUrl property, and then click the ellipsis (…) button. Select the
csDPConversionHelp.html file in the Contents of folder list box. Then, click the
OK button to set the NavigateUrl property.
356
Our slightly modified and enhanced main web page should look like the following:
Hyperlink object
9. Build and execute the application system by clicking the Internet Explorer icon
(or press F5) at the Toolbar which color is a green arrow.
Now, let us test our new HTML Help webpage. First, we have to input the dollar amount
and its corresponding peso exchange rate. Then, we have to click the Compute Now!
button to compute the total peso converted rate. After that, we have to click the Need
Help? Hyperlink. Let us see if our HTML Help webpage will appear. Let us do it now!
Sample Output:
357
Explanation:
This time, you know very well that we can quickly expand our website by including
additional webpages to provide more information and important resources to our target
surfers. This additional resource could be HTML webpages, XML webpages, database
records, web services, and even site maps and ordinary text files. See? The possibilities
are endless!
Now, we have to remember that in our example above which task is about adding an
HTML webpage, we can accomplish it in two ways:
• By using Add New Item command on the menu bar wherein we have to design
and develop our new HTML webpage from scratch.
Or
• By using Add Existing Item command on the menu bar wherein we can add an
HTML webpage that we have already created beforehand (probably using third-
party software such as Macromedia Flash or Dreamweaver), then we can just
customize it to suit to our present needs.
To link the webpages together, the Visual Studio for Web provides the Hyperlink control,
which creates a hyperlink label object (control), that the surfer can click to jump from the
current webpage to a new one.
When we use the Hyperlink control, we set the text that we will be displayed on the
webpage by using the Text property. In the case of our example that text is: Need Help?.
Then, we specify the exact and complete resource to jump to – either a local path (for test
–practice only purpose) or to a URL( complete website address). In our case, since it is
only an example, we specify the local path for test-practice or simulation purposes only.
358
Do you want more fun? Like adding a database records to our website? Actually, this is
the very heart of ASP.NET design and development - making our website a data-driven
web application system. Can we really make it? Well, I can say with a resounding,
“Yes”! Yes, we can! What are you waiting for? Let us do it now – together!
Follow the modified and enhanced figure below in designing and developing the
application program (by just adding the second Hyperlink control for the display of our
database records):
vbWebApp1a
$-Dollar Amount
Text
Boxes Peso Exchange Rate
Compute Now!
Button
Hyperlink1
Need Help?
Hyperlink2
Display the list of Dollar Earners???
Figure 9.1c Web Application Default Page with Help Page Hyperlink 1 and 2
Solution:
1. At the Menu Bar, select the Project menu, then select the Add New Item
submenu. Now, select the Web option. Then select the Web Form new item.
359
2. Name the new application system csEmp1Salary.aspx. Now, click the Add
button.
3. This time, select and click the Design tab at the bottom part of our Web Page
Designer. Type now the specified information at the Web Page Designer:
4. Press the Enter key and double-click the GridView control on the Data tab of the
Toolbox.
5. Click the drop-down arrow in the Choose Data Source combo box and then select
the New data source option in the list. This causes the Data Source Configuration
Wizard to be displayed as shown below:
360
6. Select the SQL Database option and simply accept the suggested given default
data source ID. Then, click the OK button.
7. Click the New Connection button. This time, we have to select our Server name.
Select it now (to whatever name you have assigned to your computer and the
corresponding SQLExpress database engine you have installed into it. (In my
case it is: MYHPLAPTOP1\SQLEXPRESS).
8. At this junction, we have to select (or enter) our Database name. We have to
select the Database1.
Your Add Connection dialog box should look like the following:
361
9. Now, let us test our database connection (if it is a success) by clicking the Test
Connection button.
362
10. Click the OK button to close the message box, and then click another OK button
to close the Add Connection dialog box.
11. Click the Next button. Then, click another Next button again when prompted.
This will save the default connection string.
This time, we are prompted to select the subset of database objects that we want to
use for this particular project, as shown below:
12. Just select columns (fields): Name and Salary. After the selection, click the Next
button. Now, we can test the SQL Query command to see the preview of our
database records. Click the Test Query button now!
See (the figure below)??? This is the preview of our database records that we
would like to display in our website! What an amazing power there is to
ASP.NET Web Application development. Very easy, isn’t it?!
363
Your chosen AutoFormat scheme should now be displayed like the following:
15. Now at the Menu bar, click the Save All menu item.
364
16. This time, click the Default.aspx tab at the top of the Web Page Designer. Place
the insertion point below the Need Help? Hyperlink label by just pressing the
Enter key in the keyboard.
17. Now double-click the HyperLink control icon in the Toolbox to create a hyperlink
object at the insertion point (the place where our blinking cursor is positioned).
Finally, set the Text property of the hyperlink object to “Display the list of Dollar
Earners???”.
18. This time, set the ID property of the hyperlink object to “lnkEmp1Salary”.
19. Click the NavigateUrl property, and then click the ellipsis (…) button. Select the
csEmp1Salary.aspx file in the Contents of folder list box. Then, click the OK
button to set the NavigateUrl property.
Our modified and enhanced main web page should look like the following:
Hyperlink 2 object
20. Build and execute the application system by clicking the Internet Explorer icon
(or press F5) at the Toolbar which color is a green arrow.
Now, let us test our new Database records (data-driven) webpage. First, we have to input
the dollar amount and its corresponding peso exchange rate. Then, we have to click the
Compute Now! button to compute the total peso converted rate. After that, we have to
click the Display the list of Dollar Earners??? Hyperlink. Let us see if our data-driven
webpage will appear. Again, let us try it now!
365
Sample Output:
Explanation:
Isn’t it exciting if we can design and develop a data-driven website? Yes, I’m sure, you
are as excited as I am- knowing that we can do it easily and fast by using the ASP.NET
technology. What a feeling there is in our hearts believing that the possibilities are
endless in website application development. Yes, it is a feeling of euphoria, nothing less.
Imagine, that with the amazing power of ASP.NET, we can access our live data
anywhere in the world, and anytime we want - around the clock: 24/7. Wow!!!
As you can see, we can use the GridView control to display simple database records
without writing a single program code.
Configuring a data source is simply means to select a database table then its respective
selected columns (fields) that we want to display on our webpage. The formatting of our
displayed data is represented by the so-called: placeholder information – abc for
character-string data and 0.1, 0.2,… 0.n for numerical data.
366
LAB ACTIVITY
TEST 8
1. Design and develop a simple web application system that computes the monthly
payment of a motorcycle loan which is payable for 3 years (or 3 years to pay).
Follow the given figure below in designing and developing the application
program:
vbWebApp3a
Loan Amount
Text
Boxes Interest Rate (For example: 0.20)
Monthly Payment
Calculate Now!
Button
Hyperlink1
Want Help?
Hyperlink2
Display the list of Prospective Clients!
Type the amount of the loan on the text box provided, but without the peso sign
or commas symbol.
Next, type the interest rate in decimal format in the text box provided.
Remember, don't include the "%" symbol. For example, to specify a 20% interest
rate, the decimal format equivalent is: "0.20". So, a 50% interest rate is "0.50",
and so on and so forth.
Take note also, that this motorcycle loan is three years to pay which is
equivalent to 36-month payment period.
367
Your GridView should display the entire three columns (fields) of the Emp1 database
table, namely: EmpNo, Name, and Salary.
Note: Select the Colorful scheme from your GridView’s AutoFormat pop-up context-
menu submenu item in displaying the database records. Good luck! And God bless
you more.