VC#2012 Series 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 367

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

*PSITE – Philippine Society of Information Technology Educators


NCR – National Capital Region
5

About the Author

Copernicus P. Pepito is formerly an Assistant Professor of AMA Computer University –


Quezon City Campus for 11 years and once a Training Consultant of Mapua IT Center –
Makati Campus. He holds 4 degrees: Bachelor of Science in Computer Science (BSCS),
Bachelor of Science in Computer Engineering (BSCoE), Master of Science in Computer
Science (MSCS), and Master in Business Administration (MBA). Professor Pepito earned
7 international certifications in Information Technology: Cisco Certified Network
Associate (CCNA), Cisco Certified Academy Instructor (CCAI), Microsoft Certified
Professional (MCP), Microsoft Certified Systems Administrator (MCSA), Microsoft
Certified Database Administrator (MCDBA), Microsoft Certified Solution Developer
(MCSD), and Microsoft Certified Systems Engineer (MCSE). He is an author of 14
computer books, all of which are published by National Bookstore.
6

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

Chapter 2 Designing Basic Controls or Objects 10


Using Button and Text box 10
Example 1: Button and Text box 11
Example 2: Button and Message box 12
Using Check Boxes, Radio buttons, and Message Box 14
Example 3: Check boxes and Text box 15
Example 4: Check boxes and Message box 17
Example 5: Radio buttons and Text box 20
Example 6: Radio buttons and Message Box 22
Example 7: Radio buttons and Text box 23
Example 8: Disabling Controls 24
Example 9: Hiding Controls Part 1 25
Example 10: Hiding Controls Part 2 26
Example 11: Simple Tooltip program 27
Example 12: Echoing a message program 28
7

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 3 Using Controls with Input/Output Functions 39


The Legend of ToInt??( ) and ToString( ) Methods 39
Visual C# Arithmetic Operators 39
Example 1: Sum of two input numbers 40
Example 2: Area of a circle 41
Example 3: Compute the average quiz 42
Example 4: Convert Celsius to Fahrenheit 43
Variable and Constant Declarations 44
Basic Data Types of Visual C# 55
LAB ACTIVITY TEST 2 64

Chapter 4 Using Controls with Conditional Statements 80


Relational Operators 80
Logical Operators 80
Logical AND Truth Table 81
Logical OR Truth Table 81
Logical NOT Truth Table 82
If--Else Syntax 82
If—Else If Syntax 82
Switch / Case Syntax 83
Example 1: Determines the magic words 84
Example 2: Determines if positive or negative numbers 87
Example 3: Converting numerical to letter form grade 89
Example 4: Display equivalent color (if solution) 95
Example 5: Display equivalent color (case solution) 100
Example 6: Display the high school level 105
Using Radio buttons and Check boxes Together 117
Example 7: String data type implementation 118
Example 8: Simple Pizza application 1 119
Example 9: Simple Pizza application 2 121
Visual Basic 2008 versus Visual C# 2008 Part 1 123
Example 10: Simple Password program 125
LAB ACTIVITY TEST 3 130

Chapter 5 Using Controls with Looping Statements 137


Looping Statements 137
Using List Boxes 139
Example 1: Generates sequence numbers 1 139
Example 2: Generate sequence numbers 2 140
Example 3: Generate sequence numbers 3 143
8

Example 4: Generate an inverse sequence numbers 1 146


Example 5: Generate an inverse sequence numbers 2 149
Example 6: Generate an inverse sequence numbers 3 155
A Brief Discussion about Simple Array 157
Example 7: For Each Loop with String declaration 162
Example 8: For Each Loop with Integer declaration 164
Example 9: For Each Loop with Object declaration 166
Example 10: List box with preloaded-items 170
Example 11: Design List box with Text box 172
Example 12: Design List box with Button 175
Example 13: Removing items from the List box 1 179
Example 14: Removing items from the List box 2 181
Example 15: Displaying an items to another List box 183
Example 16: Transferring an items to another List box 186
Example 17: Get the value of selected item 190
Example 18: Add, Remove, and Clear an item 194
Example 19: Transfer and Clear an item 203
Using Combo Boxes 209
Advantages of the Combo Boxes over List Box 209
Example 20: Designing Combo box with preloaded items 210
Example 21: Designing Combo box with Text box 212
Example 22: Designing Combo box with List box 213
Visual Basic 2008 versus Visual C# 2008 Part 2 216
LAB ACTIVITY TEST 4 220

Chapter 6 Other Basic Controls 234


Using the Timer Control 235
Example 1: Simple Timer control in a Label 236
Example 2: Simple Timer control in a Text box 237
Example 3: Simple DateTimePicker program 238
Example 4: One Horizontal Scrollbar program 241
Example 5: Two Horizontal Scrollbar program 243
Example 6: Vertical Scrollbar program 246
Using Picture Box Control 248
Example 7: Designing simple Picture Box control 248
Example 8: Designing the LinkLabel control 258
Example 9: Designing the Panel control 260
Example 10: Designing the Track Bar control 263
Example 11: Designing the Progress Bar control 265
In My Own Personal Experience 268
Postscript 269
LAB ACTIVITY TEST 5

Chapter 7 Designing and Developing Menus 258


What Is a Menu or a ToolBar? 258
Example 1: Simple Menu Design 259
9

Example 2: Menu with Shortcuts and Submenus 260


Example 3: Menu with Dialogs and other Forms 266
Designing a Toolbar 274
Example 4: Menu with Toolbar 274
Example 5: Menu with Context Menu 276
LAB ACTIVITY TEST 6 281

Chapter 8 Developing Simple ADO.NET Database Connectivity 284


DataSet, BindingSource and TableAdapter 285
DataGridView and BindingNavigator 286
Example 1: Applying DataGridView 286
Example 2: Applying BindingNavigator 292
Example 3: Displaying Table Data in Text Boxes 297
Example 4: Formatting DataGridView cells 303
Example 5: Arranging Table Data in Text Boxes 308
LAB ACTIVITY TEST 10 317

Chapter 9 Developing Simple ASP.NET Web Application 320


Inside Webpages 320
Example 1: Developing Simple Web Application 321
LAB ACTIVITY TEST 11
10

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.

A Brief History and Background of Visual C#


The Microsoft Corporation releases officially the C# programming language
version 1.0 in July 2000, which primary objective is to change the way how the
programmer and developer construct their Windows and web applications. This language
was invented by Anders Hejlsberg and Scott Wiltamuth – the two distinguished Microsoft
engineers. Anders Hejlsberg is legendary in the circle of programming language invention
arena, because he was the one who created Turbo Pascal programming language and lead-
creator of Delphi IDE at Inprise company (formerly Borland International).
C# is created and developed by combining the strengths found in three
programming languages: C++, Java, and Visual Basic, and avoids its respective weakness
points. The objective of C# is to provide an object-oriented, Internet-centric, high-
performance and yet simple language for the .NET framework development environment.

Visual Studio Express Is a Free Edition

The Express Edition is configured to be used by students, developers, hobbyists


and consultants for testing and experimentation purposes. This means that you cannot use
the programs you develop in Express Edition for commercial use and implementation due
to its inherent limitation. You have to use the licensed edition (Professional, Premium, or
Ultimate edition), when you plan to develop a business application system that will be
used by companies or government agencies. Whatever you learn in Visual Basic Express
Edition is applicable to the licensed edition. So, the Express Edition is a good way to start
mastering the language. So, what are you waiting for? Grab your copy now? Copy of
what? Copy of the Microsoft Visual Studio 2012 Express Edition and this book too. This
is just a suggestion, okay? Don’t get offended, buddy.
11

Common Elements of the Visual C# IDE


The Integrated Development Environment (IDE) is the workspace where we
construct together all the components of our application system such as the place where
we design our forms and controls as well as the place where we develop our code or
programs.
We just simply discuss here the common elements of the Visual C# IDE which
we commonly used in our programming task.

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

The Start Page


We can use the Start Page to select from recent projects. We can also select a
New Project from here by clicking the New Project icon at the Toolbar or as a menu item
at the File menu.

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.

The New Project Dialog


When we create a new project, we select this menu item from the File menu or
alternatively, we click the New Project icon (the first icon) from the Toolbar. We will be
presented with different Visual Studio installed templates such as Windows Form
Application, Class Library, Console Application, and more. In this Series 1 book, we
focus more on the Windows Forms Application. So, we select always the Windows
Forms Application template.

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

The context menus contain shortcuts to our frequently performed commands. To


open the context menu is easy, we simply click the right mouse button on the control or
object we are currently using. The specific list of shortcuts available from context menu
depends on the part of the environment where we click the right mouse button.
14

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!

Program Conventions Used

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!";
}

The above code demonstrates that the statement:

this.textBox1.Text = "Hello World!";

is the code to be embedded (typed) within the method:


16

private void button1_Click(object sender, EventArgs e)


{


}

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:

private void button1_Click(object sender, EventArgs e)


{

Explaining Properties, Methods, and Events briefly


Properties can be considered as an object’s attributes, methods as its actions, and
events as its responses. For example, a button’s attributes are its caption, color, and size.
An object such as a button can perform methods and respond to events. This event can be
a click by the mouse or a key-press from the keyboard. The performed method could be
to show a form object or hide it instead.

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

“When people ask me what is the best way to learn programming


or how to use a specific language, I tell them to experiment -
write as many small programs as you can, as each one will
teach you more - and each one will add another trick to
your tool bag.”
- Alan Cooper
(Father of Visual Basic)

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.

Using Button and Text box

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

Hello World ! Text box

Greet Now!
Button

Figure 2.1 Button and Text box design

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:

private void button1_Click(object sender, EventArgs e)


{
this.textBox1.Text = "Hello World!";
}

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

Figure 2.1 Button and Text box Output

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):

this.textBox1.Text = "Hello World!";

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

Greet Now! Button

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:

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show("Hello World!");
}

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

Figure 2.2a Button and Message box Output

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.

Using Check Boxes, Radio buttons and Message Box


Check boxes are valid as single controls, however they are not mutually
exclusive. Meaning, the user can check as many check boxes as they want, unlike in
Radio buttons, the user can only select one option at a time. Check boxes are applicable
to the situation where you can select a lot of items because you want them all, such as
you can order a pizza and choose all the ingredients you want to put on it as long as you
can afford to pay. While in radio buttons, you can only choose one and only one. The
radio buttons is applicable to this situation - marrying a girl. In the Christian world, no
matter how many girlfriends you have at the same time or in the same place (shame on
you brother!), you can only choose one among them to marry, unless you change your
religion into something else (better?) that allows polygamous marriages (which I like –
joke only).
22

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

Check box 2 is clicked!

CheckBox 1

CheckBox 2

CheckBox 3

Figure 2.3 Check box and Text box design

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

7. Double-click the Check Box 2 on the Form to display the


checkBox2_CheckedChanged event method. Embed the following lines (in bold
only) into the method:

private void checkBox2_CheckedChanged(object sender, EventArgs e)


{
this.textBox1.Text = "Check box 2 clicked!";
}

8. Double-click the Check Box 3 on the Form to display the


checkBox3_CheckedChanged event method. Embed the following lines (in bold
only) into the method:
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
this.textBox1.Text = "Check box 3 clicked!";
}

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:

Figure 2.3a Check box and Text box 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)

this.textBox1.Text = "Check box 1 clicked!";

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

Check box 2 clicked!


25

Figure 2.4 Check box and Message box design

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:

private void checkBox1_CheckedChanged(object sender, EventArgs e)


{
MessageBox.Show("Check box 1 clicked!");
}

7. Double-click the Check Box 2 on the Form to display the


checkBox2_CheckedChanged event method. Embed the following lines (in bold
only) into the method:
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("Check box 2 clicked!");
}

8. Double-click the Check Box 3 on the Form to display the


checkBox3_CheckedChanged event method. Embed the following lines (in bold
only) into the method:
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("Check box 3 clicked!");
}

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

Figure 2.4a Check box and Message box Output

Explanation:

A message box is used for displaying simple messages to the user.


We will notice here that the embedded code (within the procedure)

MessageBox.Show("Check box 1 clicked!");

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 button 2 is clicked!

Radio 1

Radio 2

Radio 3

Figure 2.5 Text box and Radio buttons design

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:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
this.textBox1.Text = "Radio button 1 clicked!";
}

7. Double-click the Radio button 2 on the Form to display the


radioButton2_CheckedChanged event method. Embed the following lines (in bold
only) into the method:
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
this.textBox1.Text = "Radio button 2 clicked!";
}

8. Double-click the Radio button 3 on the Form to display the


radioButton3_CheckedChanged event method. Embed the following lines (in bold
only) into the method:
28

private void radioButton3_CheckedChanged(object sender, EventArgs e)


{
this.textBox1.Text = "Radio button 3 clicked!";
}

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:

Figure 2.5a Text box and Radio buttons Ouptu

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 = "Radio button 1 clicked!";

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

Radio button 2 clicked!

Figure 2.6 Message box and Radio buttons design

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

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
if (radioButton1.Checked)
MessageBox.Show("Radio button 1 clicked!");
}

7. Double-click the Radio button 2 on the Form to display the


radioButton2_CheckedChanged event method. Embed the following lines (in bold
only) into the method:
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
MessageBox.Show("Radio button 2 clicked!");
}

8. Double-click the Radio button 3 on the Form to display the


radioButton3_CheckedChanged event method. Embed the following lines (in bold
only) into the method:
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
if (radioButton3.Checked)
MessageBox.Show("Radio button 3 clicked!");
}

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

Figure 2.6a Message box and Radio buttons design output

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

High School Level:

First Year

Second Year

Third Year

Fourth Year

Is also called: Sophomore! Text box

Figure 2.7 Radio buttons and Text box design 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 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:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "Freshman!";
}

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:

Figure 2.7a Radio buttons and Text box design 2 output


34

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.

Hiding and Disabling Controls


We will tackle some program examples that demonstrate on an actual
basis how to hide or disable a control. Actually, it is very easy. We just simply set
the Enabled or Visible property of a particular control to false at the design time.
Or alternatively, we can set it at the run-time, by issuing this syntax:

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

Try to Click Me! Button

Text box

Radio buttons
Enable Button! Disable Button!

Figure2.8 Disabling and Enabling 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 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:

private void button1_Click(object sender, EventArgs e)


{
textBox1.Text = "Yes! I was Enabled!, thank you!";
}

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:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
button1.Enabled = true;
textBox1.Text = "You Enabled the Button!";
}

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

Figure 2.8a Disabling and Enabling Controls output

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:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
button1.Enabled = true;
textBox1.Text = "You Enabled the Button!";
}

Now, when the user clicks the Disable radio button (radioButton2), we disabled it
through the following code:

private void radioButton2_CheckedChanged(object sender, EventArgs e)


{
button1.Enabled = false;
textBox1.Text = "You Disabled the Button!";
}

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

Hide Radio1! Show Radio1!

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:

Figure 2.9a Showing and Hiding Controls 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:

private void button1_Click(object sender, EventArgs e)


{
radioButton1.Visible = false;
}
40

Now, when the user clicks the Show radio button (radioButton2), we showed it through
the following code:

private void button2_Click(object sender, EventArgs e)


{
radioButton1.Visible = true;
}

You could notice that the preceding codes are similar to the enabling and disabling a
particular control which was demonstrated in our previous example.

Tweaking the High School Level Example a little bit


Now the question is, what if we want to design an empty list of radio buttons?
This is in the case of our High School Level example where we saw that during the time
we run our program, the default selection will always be the First Year radio button,
thus its corresponding displayed message is “Freshman!”. What we want is to be able to
display all the list of radio buttons as empty (unselected), so that there is no message
displayed at the Text box, by default. Well, this is possible, however, we will apply a
trick on our program. Like any tricks, it works sometimes, and in most cases, it won’t.
To work around this programming task dilemma, we have to hide the first radio button
which contain the default selection. In that way, the user was tricked to see the
remaining list of radio buttons as empty (or unselected). Very clever, isn’t it. But no,
don’t practice tricks, I warned you. It is but just a temporary success, and eventually a
permanent failure. Remember that only truth lasts. And it lasts forever…like diamonds.
Putting tricks on our programs will unexpectedly produce side effects, and these side-
effects could be disastrous to our application system in the long run. Some technical
people call this one “quick fix”.
For the sake of showing you that we can turn around this programming task using
tricks, let us do it now. But again, this is just for demonstration purposes only.

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!

Show Radio 1! Hide Radio 1 !

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:

private void Form1_Load(object sender, EventArgs e)


{
radioButton1.Visible = false;
radioButton1.Checked = true;
}

10. Double-click the Radio button 1 on the Form to display the


radioButton1_CheckedChanged event method. Embed the following lines (in bold
only) to the method:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "";
}

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:

private void radioButton2_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "Freshman!";
}

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:

Figure 2.10a Hiding some controls to trick up the application output


44

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:

private void Form1_Load(object sender, EventArgs e)


{
radioButton1.Visible = false;
radioButton1.Checked = true;
}

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:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = " ";
}

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:

private void button2_Click(object sender, EventArgs e)


{
radioButton1.Visible = false;
textBox1.Text = " ";
}

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:

private void radioButton2_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "Freshman!";
}

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

Point your mouse to any of the controls:

label2

button1

checkBox1

radioButton1

Figure 2.11 Simple ToolTip program

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

4. Set the Form’s Text property to vbToolTip1.


5. Click, drag and drop a Label, a Button, a Check Box, and a Radio Button from the
Toolbox to add them into the form. Then, click, drag and drop five ToolTips into
the Form. The toolTip1, toolTip2, toolTip3, toolTip4, and toolTip5 controls should
appear at the bottom of the Form. Why the tooltip is up to 5? Because, we will
include the Form as one of the controls to be assigned with a toolTip control,
okay?
6. Double-click now the Form to display the Form1_Load event method. Embed the
following lines (in bold only) to the method:

private void Form1_Load(object sender, EventArgs e)


{
toolTip1.SetToolTip(this, "This is a Form!");
toolTip2.SetToolTip(label2, "This is a Label!");
toolTip3.SetToolTip(button1, "This is a Button!");
toolTip4.SetToolTip(checkBox1, "This is a Check Box!");
toolTip5.SetToolTip(radioButton1, "This is a Radio Button!");
}

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:

Figure 2.11a Simple ToolTip program output

Explanation:

See, it is easy to program a simple ToolTip application, isn’t it? Here, in this code below:
47

private void Form1_Load(object sender, EventArgs e)


{
toolTip1.SetToolTip(this, "This is a Form!");
toolTip2.SetToolTip(label2, "This is a Label!");
toolTip3.SetToolTip(button1, "This is a Button!");
toolTip4.SetToolTip(checkBox1, "This is a Check Box!");
toolTip5.SetToolTip(radioButton1, "This is a Radio Button!");
}

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

Enter a message to echo:

Text box

label 2

Figure 2.12 A Simple Echo program

vbEcho1

Enter a message to echo:

How are you buddy? Are you in or out? Text box

How are you buddy? Are you in or out?


48

Figure 2.12a A Simple Echo program

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:

private void textBox1_TextChanged(object sender, EventArgs e)


{
label2.Text = textBox1.Text;
}

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

Figure 2.12b A Simple Echo program output

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:

private void textBox1_TextChanged(object sender, EventArgs e)


{
label2.Text = textBox1.Text;
}

That’s all for now, buddy.

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 and Classes Defined

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.

To Comment or Not to Comment


(That is the Question!)
Making a comment or putting one or two in your code, makes your program more
readable and comprehensible to other programmers or developers. In other words, your
program is a programmer-friendly if it contains comment or comments most especially to
some part of your program which are hard to understand or decipher. Well, you will learn
later on in your programming career that a comment can help you to remember easily
what your code is doing once you have not read it for a week or month. This is but just a
simple thoughtfulness that can give you and your fellow programmers an easy way to
understand programs without resorting to serious and deep code analysis. You will also
be surprised later on in your life as a programmer, that you too can hardly understand
your own program if it contains no comments on it. Try not doing it (not putting a
comment in your program), and you will be sorry after all. Take my word seriously,
buddy; I really mean it.
As you read through the examples in this book, you will often come across with the
comment symbol (//) of Visual C# language (other programming languages have other
comment symbols to use). This symbol tells the Visual C# system-compiler to ignore the
words that follow it. These words are remarks placed in the code for the benefit of the
other programmer or developer who might examine or use your code later.
51

A Friendly Reminder for the Instructors

Since programming endeavor is a creative art as well as an analytical science, I would


like to suggest that all the laboratory activity tests must be an open notes or open books,
or even an open Internet research. In this way, the students won’t spend too much time
memorizing the commands and functions that they will use in solving the problems
presented. The memory capacity is so precious enough to be wasted only for the things
that need not to be memorized such as commands and functions or methods. I myself
cannot memorize commands and functions or methods with accuracy most of the time. It
is my belief that if the students are given enough resources such as notes, books, and
Internet connection, they can spend more time in analyzing and solving the problems
than cramming their minds with command syntax memorization. In the actual practice of
our profession, no boss in his right mind who would instruct his or her programmers and
developers to design and develop a real-world application system without the aid of
notes, books, manuals or Internet connection. So why not emulate that kind of treatment
and consideration to our future programmers or developers, the way the real boss do in
real-world?
52

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

Button 2 clicked! Text box

Command1 Command2 Command3 Buttons

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

Command1 Button 1 clicked!

Command2 Button 2 clicked!

Command3 Button 3 clicked!

Buttons Text boxes

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

Submit button clicked!

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 1 Check box 1 clicked!

Check 2 Check box 2 clicked!

Check 3
Check box 3 clicked!

Check boxes Text boxes

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 2 Radio button 2 clicked!

Option 3

Radio buttons Text boxes

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

Button 3 clicked! Text box 1

Button 1 Button 2 Button 3 Buttons

Check box 2 clicked! Text box 2

Check 1 Check 2 Check 3 Check boxes

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

Option 1 Option 2 Option 3 Radio buttons

Radio button 2 clicked! Text box 1

Check 1 Check 2 Check 3 Check boxes

Check box 3 clicked! Text box 2

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.

csElementary School Level

Elementary School Level:

Grade 1

Grade 2

Grade 3

Grade 4

Grade 5

Grade 6

Is also written in Roman Numerals: Grade IV


57

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++)

The Legend of ToInt??( ) and ToString( ) Methods


In calculating and displaying data in our Form, we need to know how they can be
manipulated using the two most important methods: Numeric Value method (ToInt??( )
or ToDouble( )) and String method (ToString( )). These two common methods simply
convert our data from numeric to string data or vice versa. The ToInt??( ) method
converts the displayed data into numeric, while the ToString( ) method converts the
displayed data into string data.
The ToInt??( ) method is applied when we want to calculate the numeric data displayed
in text boxes. Now if we want to display the computed data into the text box, we need to
convert it into a string data using the ToString( ) method.
We need to apply the ToInt??( ) method so that the numbers that are being entered in the
text box can be converted to numeric data for computation purposes in our equation or
formula, otherwise these numbers are treated as string which cannot be calculated or
processed in the equation. We need also to convert the numeric data into its equivalent
string data representation using the ToString( ) method for the proper display of the
numbers into the text box control. Without doing so, it will result to an undesired output.
Okay, let us have our example about this one. The best example of this application is the
simple calculator. In our simple calculator, we will design a program where a user can
input two numbers then our program will summed them up. Let us start with a program
that will add two numbers.

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

Text box 1 + Text box 2


5 2

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:

private void button1_Click(object sender, EventArgs e)


{
int no1, no2, sum;
sum = 0;
no1 = Convert.ToInt16(textBox1.Text);
no2 = Convert.ToInt16(textBox2.Text);
sum = no1 + no2;
textBox3.Text = Convert.ToString(sum);
}

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:

Figure 3.1a Sum of two input numbers 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:

int no1, no2, sum;


sum = 0;

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:

sum = no1 + no2;

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);

So, that is our discussion to this example.

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

Enter the radius: Text box 1


5

Compute Button

Area of a circle is: 78.54 Text box 2

Figure 3.2 Compute the area of a circle

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:

private void button1_Click(object sender, EventArgs e)


{
double Area,Pi;
62

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:

Figure 3.2a Compute the area of a circle

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

Enter the three quizzes:

80 90 70 Text box 1,2, & 3

Compute Button

The average is: 80

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:

private void button1_Click(object sender, EventArgs e)


{
int Quiz1, Quiz2, Quiz3;
65

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:

Figure 3.3a Compute the average quiz output

Explanation:

First, we declared all the variables we used in our program. We did that with the
following code:

int Quiz1, Quiz2, Quiz3;


float Ave;
Ave = 0;
.
66

.
.
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:

Ave = (Quiz1 + Quiz2 + Quiz3)/3;

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

Enter the Celsius: 100 Text box 1

Button
Compute

The Fahrenheit is: 237.6 Text box 2

Figure 3.4 Convert Celsius to Fahrenheit degree

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:

private void button1_Click(object sender, EventArgs e)


{
int Celsius;
double Fahrenheit;
Fahrenheit = 0;
Celsius = Convert.ToInt16(textBox1.Text);
Fahrenheit = (9.0 / 5.0) * (Celsius + 32);
textBox2.Text = Convert.ToString(Fahrenheit);
}

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

Figure 3.4a Convert Celsius to Fahrenheit degree output

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.

Variable and Constant Declarations

As what we have learned in our previous examples, variables and constants


played an important role in our program. Understanding how to use them and how they
work is critical to our programming endeavor and crucial to our career as systems
programmer or solutions developer. So let us start to learn about them now.
The declaration part in our program consists usually with the list of variables. In some
instances, we have declared also the constant names within the program module.
Variables are memory location (address) which we can assign a specific name. For
example, we can name our variables as Sum, Num1, Area, or Ave. We can assign or store
a value or data into a variable. To declare a variable is to tell the program about it in
advance. A variable name must begin with a letter which does not contain an embedded
period and must be unique within the same scope (in a form or method).
Constants look like a variable, however unlike the variable, the value or data it holds
remain fixed while the application system is running or executing. One of the purposes
why we use constants in our program is to make coding and debugging easier. By putting
the constant value at the declaration part in our program (usually placed at the top of the
module), we can easily modify or debug it once it causes some errors. Here are some
examples of the constant declarations:

const float conPi = 3.1416

const float conInterestRate = 0.03

const int conHoursWork=8


71

Basic Data Types of Visual C#

Data Type Purpose

int An integer data type is a whole number.

Examples: 9 143 32000 +123 -4567

long A bigger integer - means a wider range than an int.

Examples: 10,123,456,789 1,000,000,000,321

float A number with fractional part or decimal point.

Examples: 3.1416 2.54 +193.20 -1,000.003

double A bigger float – means a wider range than float.

Examples: 1143441000.5121 1000000000.151314

string A sequence of one or more characters that are enclosed within double
quotation marks.

Examples: “a” “Z” “*” “Ma.” “Bianca”


“I love you very much, Bianca.”

char Usually a single value enclosed with single quote.

Example: ‘a’ ‘1’ ‘*’ ‘Z’ ‘0’ ‘!’

bool A boolean data type holds true or false values.

Examples:

chkOnionsChili.Checked = true;

chkTomatoPineapple.Checked = false;

byte A small integer data type with a range of 0 to 255.

Example: 6 254 100 +20 -99


72

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

Enter the dollar(s) : 3 Text box 1

$ 1 dollar = P 56.47 Convert Button

The Peso rate conversion is: 169.41 Text box 2

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

The centimeters: 10.16 Text box 2

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

Enter the radius: 3 Text box 1

Compute Button

The Sphere is: Text box 2


113.0976

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

Enter the following data:

Price Service Yearly Depreciation

80 5 4 Text boxes 1,2, & 3

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:

EOQ = sqrt( 2RS/I)

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

Enter the following data:

Requirement Set Up Cost Inventory

4 100 20 Text boxes (1,2&3)

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.

where intNum1 is the number to square root.

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

Text box 1 _ Text box 2


5 2

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

Text box 1 * Text box 2


5 2

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

Text box 1 / Text box 2


5 2

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

< less than


> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to

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 ( || ).

Logical AND (&&) Truth Table


In logical operators, 0 is equivalent to False and 1 is equivalent to True. So the first table
below is equivalent to the second table that follows:

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

Logical OR (||) Truth Table

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

Logical NOT (!) Truth Table

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 the condition is evaluated to True, then statement1 is executed, otherwise


statemenet2 is executed instead. The condition is usually a comparison using the
relational operators and in some cases it can be any expression that evaluates to a
numeric value. The Visual C# system compiler interprets this value as true or false,
where a zero (0) numeric value is false, and most of the time a numeric value of one
(1) is considered true (or any non-zero value).

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

Group of Associated Statements Syntax

In the case of the group of associated statements in a particular if – else if conditional


statement, we have to group these associated statements with begin and end symbols ({
and }) such as the following:

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 /case Syntax

The switch/case conditional statement is an alternative to if- else if conditional statement.


With the use of switch/case statement, we can simplify some of the code that are tedious,
long, and cumbersome when we use the if-else if statement. In other words, the
switch/case can be the best substitute conditional statement to write a clearer and concise
multi-way decision program compared to the messy if-else if statement. Here is the
switch/case general syntax:

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

case 1>0 || case 50<100

Or

case 4>0 && Case 32<100

This is a syntax error.


It takes you to learn deeply the switch/case syntax and its limitations and capabilities.
Otherwise, you would have a hard time converting an if/else if code into switch/case
code. Let us try converting the example below from if/else if conditional statement to
switch/case statement code. Are you ready?

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

Enter the magic number: 143 Text box 1

Determine
Now! Button

I love you!
Text box 2

Figure 4.1 Determining a magic number

Solution: (Using the if/else if Conditional Statement)

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:

private void button1_Click(object sender, EventArgs e)


{
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.

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:

Figure 4.1 Determine the Magic Words


84

Explanation:

In our conditional statement:

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:

textBox2.Text = " I love you!";

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

Enter a number: -5 Text box 1

Determine
Button
Now!

Negative number!
Text box 2

Figure 4.2 Determine if Negative or Positive number

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:

private void button1_Click(object sender, EventArgs e)


{
Int16 num1;
num1 = Convert.ToInt16(textBox1.Text);
if (num1 >= 0)
textBox2.Text = "Positive number!";
else
textBox2.Text = "Negative number!";
}

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:

Figure 4.2a Determine if Negative or Positive number 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!”

Or the reverse of the solution presented above:

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

Enter a grade: Text box 1


94

Determine
Button
Now!

A Text box 2
Your grade in letter form is:

Figure 4.3 Numeric to Letter-form grade conversion

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:

private void button1_Click(object sender, EventArgs e)


{
int grade;
grade = Convert.ToInt16(textBox1.Text);
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";
}
89

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:

Figure 4.3a Numeric to Letter-form grade conversion

Explanation:

First, we declared the variable we used in our program. We did that with the following
code:

int grade;

We need to apply the Convert.ToInt16( ) method 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:

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>=80) && (grade<=89))


90

.
.
.
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

‘B’ or ‘b’ Blue


‘R’ or ‘r’ Red
‘G’ or ‘g’ Green
‘Y’ or ‘y’ Yellow
other letters ‘Unknown Color’

Follow the given figure below in designing and developing the application system:

csColor1

Enter a letter: r Text box 1

Determine
Now! Button

Red! Text box 2

Figure 4.4 Determine a color using if/else if


92

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:

private void button1_Click(object sender, EventArgs e)


{
char Letter;
Letter = Convert.ToChar(textBox1.Text);
if ((Letter == 'B') || (Letter == 'b'))
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!";
}

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:

Figure 4.4a Determine a color using if/else if output

Explanation:

First, we declared the variable we used in our program. We did that with the following
code:

char Letter;

We need to apply the Convert.ToChar( ) method here in our textBox1.Text expression so


that the letter entered at text box 1 which is a string (text) by default will be converted
into its character equivalent:

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:

if ((Letter == 'B') || (Letter == 'b'))


94

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

‘B’ or ‘b’ Blue


‘R’ or ‘r’ Red
‘G’ or ‘g’ Green
‘Y’ or ‘y’ Yellow
other letters ‘Unknown Color’

Follow the given figure below in designing and developing the application system:
95

csColor2

Enter a letter: r Text box 1

Determine Button
Now!

Text box 2
Red!

Figure 4.5 Determine a color using switch/case

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:

private void button1_Click(object sender, EventArgs e)


{
char Letter;
Letter = Convert.ToChar(textBox1.Text);
switch (Letter)
{
case 'B':
case 'b':
textBox2.Text = "Blue!";
break;
case 'R':
case 'r':
textBox2.Text = "Red!";
break;
case 'G':
96

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:

Figure 4.5 Determine a color using switch/case output

Explanation:

First, we declared the variable we used in our program. We did that with the following
code:

char Letter;
97

We need to apply the Convert.ToChar( ) method here in our textBox1.Text expression so


that the letter entered at text box 1 which is a string (text) by default will be converted
into its character equivalent:

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 switch/case conditional statement, we have to pass the Letter variable to switch


statement using the following syntax:

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

In the if/else if, we have these statements:


.
.
else if ((Letter == 'R') || (Letter == 'r'))
textBox2.Text = "Red!";
.
.
while in switch/case, its equivalent statements are:
.
.
case 'R':
case 'r':
textBox2.Text = "Red!";
break;
.
.

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:

Year-entry number High-School Level

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

Enter Year-entry number: 2 Text box 1

Determine Button
Now!

Sophomore! Text box 2

Figure 4.6 Determine the high school level

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:

private void button1_Click(object sender, EventArgs e)


{
int Level;
Level = Convert.ToInt16(textBox1.Text);
switch (Level)
{
case 1:
textBox2.Text = "Freshmen!";
break;
case 2:
textBox2.Text = "Sophomore!";
break;
case 3:
textBox2.Text = "Junior!";
break;
100

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:

Figure 4.6a Determine the high school level 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:

private void button1_Click(object sender, EventArgs e)


{
String Level;
Level = textBox1.Text;
switch (Level)
{
case "1":
textBox2.Text = "Freshmen!";
break;
case "2":
textBox2.Text = "Sophomore!";
break;
case "3":
textBox2.Text = "Junior!";
break;
case "4":
textBox2.Text = "Senior!";
102

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

Enter your name: Text box 1

Greet Me?
Button

Good morning: Text box 2

Figure 4.7 String data type implementation Good morning: ???????

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:

private void button1_Click(object sender, EventArgs e)


{
String strName= "";
strName = textBox1.Text;
textBox2.Text = strName;
MessageBox.Show( "Good morning: "+strName );
}

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

Figure 4.7a String data type implementation output

Explanation:

First, we declared the variable we used in our program. We did that with the following
code:

String strName= " ";

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:

strName= " ";

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

MessageBox.Show( "Good morning: "+strName );

where we concatenate it with the string message “Good morning:”.

That’s the end of our discussion, and let us go to other application that will make us more
excited!

Using Radio buttons and Check boxes Together


(It’s All Together Now!)

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

Onions & Chili


Price:
Tomato & P-Apple
185
Salami

Figure 4.8 Pizza Assessment System Part 1

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:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
chkCheese.Checked = true;
107

chkPepper.Checked = false;
chkBaconHam.Checked = true;
chkMushroom.Checked = false;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
chkSalami.Checked = false;
textBox1.Text = "185";
}

8.Double-click the Special (Radio button 2) on the Form to display the


radioButton2_CheckedChanged event method. Embed the following lines of code (in
bold only) to the method:
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
chkCheese.Checked = true;
chkPepper.Checked = true;
chkBaconHam.Checked = true;
chkMushroom.Checked = true;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
chkSalami.Checked = false;
textBox1.Text = "250";
}

9.Double-click the Primo (Radio button 3) on the Form to display the


radioButton3_CheckChanged event method. Embed the following lines of code (in bold
only) to the method:
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
chkCheese.Checked = true;
chkPepper.Checked = true;
chkBaconHam.Checked = true;
chkMushroom.Checked = true;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = true;
chkSalami.Checked = true;
textBox1.Text = "290";
}

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

Figure 4.8a Pizza Assessment System Part 1 output

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:

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
chkCheese.Checked = true;
chkPepper.Checked = false;
chkBaconHam.Checked = true;
chkMushroom.Checked = false;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
chkSalami.Checked = false;
textBox1.Text = "185";
}

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

Price: 185 Onions & Chili

Quantity: 2 Tomato & P-Apple

Salami
Compute
Button
Now!

Amount: 370
110

Figure 4.9 Pizza Assessment System Part 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 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

private void rdoDeluxe_CheckedChanged(object sender, EventArgs e)


{
chkCheese.Checked = true;
chkPepper.Checked = false;
chkBaconHam.Checked = true;
chkMushroom.Checked = false;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
chkSalami.Checked = false;
txtPrice.Text = "185";
txtAmount.Text = " ";
}
11. Double-click the Special (Radio button 2) on the Form to display the
rdoSpecial_CheckedChanged event method. Embed the following lines of code
(in bold only) to the method:
private void rdoSpecial_CheckedChanged(object sender, EventArgs e)
{
chkCheese.Checked = true;
chkPepper.Checked = true;
chkBaconHam.Checked = true;
chkMushroom.Checked = true;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
chkSalami.Checked = false;
txtPrice.Text = "250";
txtAmount.Text = " ";
}
12. Double-click the Primo (Radio button 3) on the Form to display the
rdoPrimo_CheckChanged event method. Embed the following lines of code (in
bold only) to the method:
private void rdoPrimo_CheckedChanged(object sender, EventArgs e)
{
chkCheese.Checked = true;
chkPepper.Checked = true;
chkBaconHam.Checked = true;
chkMushroom.Checked = true;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = true;
chkSalami.Checked = true;
txtPrice.Text = "290";
txtAmount.Text = " ";
}

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

Figure 4.9a Pizza Assessment System Part 2 output

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:

private void rdoDeluxe_CheckedChanged(object sender, EventArgs e)


{
chkCheese.Checked = true;
chkPepper.Checked = false;
chkBaconHam.Checked = true;
chkMushroom.Checked = false;
chkOnionsChili.Checked = true;
chkTomatoPineapple.Checked = false;
chkSalami.Checked = false;
txtPrice.Text = "185";
txtAmount.Text = " ";
}

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:

private void button1_Click(object sender, EventArgs e)


{
int Quantity;
float Amount;
Amount = 0;
if (rdoDeluxe.Checked)
{
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);
}
}

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.

Visual Basic 2012 versus Visual C# 2012 Part 1

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!

Example 1: (This One Works!)

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

Enter the magic number: 143 Text box 1

I love you! Text box 2

Figure 4.10 Determining a magic number

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:

private void textBox1_TextChanged(object sender, EventArgs e)


116

{
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:

Figure 4.10a Determining a magic number output

Example 2: (This One Does Not Work!)

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

Enter a number: -5 Text box 1

Negative number! Text box 2

Figure 4.11 Determine if Negative or Positive number

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:

private void textBox1_TextChanged(object sender, EventArgs e)


{
int num1;
num1 = Convert.ToInt16(textBox1.Text);
if (num1 >= 0)
textBox2.Text = "Positive number!";
else
textBox2.Text = "Negative number!";
}

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

Login now your Password: ***********


Text box 1

Check if correct! Button

Text box 2

Figure 4.12 Simple Password program

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:

private void button1_Click(object sender, EventArgs e)


{
if (textBox1.Text == "MyPassword" )
textBox2.Text = "Correct Password!";
else
textBox2.Text = "Incorrect Password!!, Try again!";
}

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:

private void textBox1_TextChanged(object sender, EventArgs e)


{
textBox2.Text = " ";
}

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

Figure 4.12a Simple Password program output

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:

private void textBox1_TextChanged(object sender, EventArgs e)


{
textBox2.Text = " ";
}

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.

So, I think, I don’t need to explain further. Would you agree?


121

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

Enter a letter: Text box 1


E

Button
Determine
Now!

It’s a Vowel! Text box 2

Solution: Use the If/Else If conditional statement

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

Less than 0 ICE


Between 0 and 100 WATER
Exceeds 100 STEAM

Follow the given figure below in designing and developing the application program:

csTemperature9

Enter the temperature: 70 Text box 1

Determine
Now! Button

WATER! Text box 2


122

Solution: Use the If/Else If conditional statement

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

It’s a military aircraft! Text box 2

Solution: Use the If/Else If conditional statement

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.

Class ID Ship Class

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!

Cruiser! Text box 2

1st Solution: Use the If/Else If conditional Statement


2nd Solution: Use the Switch/Case conditional Statement

5. The National Earthquake Information Center has the following criteria to


determine the earthquake’s damage. Here is the given richter scale criteria and its
corresponding characterization. The richter scale serves as an input data at text
box 1 and the characterization as an output information at text box 2.

Richter Number Characterization

Less than 5 Little or No Damage


From 5 up to 5.5 Some Damage
From 5.6 up to 6.5 Serious Damage
From 6.6 up to 7.5 Disaster
Higher than 7.5 Catastrophe

Follow the given figure below in designing and developing the application program:

csEarthquake2

Enter the richter number: Text box 1


6.9

Determine
Now! Button

Disaster! Text box 2

Solution: Use the If/Else If conditional statement


124

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:

Range in Percentile Form Grade in Transcript

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

Enter a grade in percentage: 93 Text box 1

Determine
Now! Button

The Grade in Transcript: 1.50 Text box 2

1st Solution: Use the If/Else If conditional statement


2nd Solution: Use the Switch/Case conditional statement

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

Add 1st no. 5

Subtract Text boxes


2nd no. 2
Multiply
=
Divide
Answer: 7

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:):

private void Form1_Load(object sender, EventArgs e)


{
int intNum1, intNum2;
intNum1 = 0;
intNum2 = 0;
textBox1.Text = Convert.ToString(intNum1);
textBox2.Text = Convert.ToString(intNum2);
}

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

Subtract Text boxes


2nd no. 2

=
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

Cabin Bed sheets

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

Medical Exam Body Parts

CT-Scan (P12,000) Head

X-Ray (P1,000) Mouth

Physical Exam (P700) Body

No. of M. Exam: Urine


2
Compute Bill:
2000

Button Text boxes


128

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 looping statements of Visual C# programming language are:

1. for loop and for each loop


2. while loop
3. do/while loop

The syntax of the for loop statement is:

for ( init; condition; inc/dec) {


statement(s) statements that do something repetitively (body of the loop)
}

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 syntax of the for each loop statement is:

foreach( element in group) {


statement(s)
}
129

For example of how to use the for each looping statement:

foreach (Control oObject in Controls) {


statement(s)
}

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.

The syntax of the while loop statement is:

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);

Incrementation, Decrementation, and Accumulator Formulas


These three formulas are oftenly used in looping statements operation:

Examples of Incrementation Formula:

i++ or ++i
++n or n++

Examples of Decrementation Formula:

i-- or --i
--n or n--
130

Examples of Accumulator Formula: (Sample Implementation)

acc=acc+n (acc = acc + 20 or a shortcut method: acc =+20 )


sum=sum+n (sum = sum + 5 or a shortcut method: sum+=5 )
total=total+n (total=total +1000 or a shortcut method: total+=1000)

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.

Using List Boxes

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

Figure 5.1 Generating sequence number using For Next syntax

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter;
for (nCounter = 1; nCounter <= 5; nCounter++)
{
listBox1.Items.Add("Loop " + nCounter.ToString());
}
listBox1.EndUpdate();
}
132

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:

First we declared an ordinary variable here in our program as follows:

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:

listBox1.Items.Add("Loop " + nCounter.ToString( ));

We need to convert the numeric value of variable nCounter to its equivalent string value
by using the ToString( ) method as follows:

listBox1.Items.Add("Loop " + nCounter.ToString( ));

In this way, we can add it properly at the List box.


The role of the BeginUpdate( ) method here in our code is simply to turn off the visual
updating of the List box until the EndUpdate( ) method is called, while the EndUpdate( )
method resumes the visual updating of the List box.

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

Figure 5.2 Generating sequence numbers using Do-While-Loop syntax.

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter=1;
do {
listBox1.Items.Add("Loop "+nCounter.ToString());
nCounter++;
} while (nCounter<=5);
listBox1.EndUpdate();
}

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

while ( nCounter <= 5);


135

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

Figure 5.4 Generating an inverse sequence numbers using For Loop

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter;
for (nCounter = 5; nCounter >= 1; nCounter--)
{
listBox1.Items.Add("Loop " + nCounter.ToString());
}
listBox1.EndUpdate();
137

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.4a Generating an inverse sequence numbers


using for loop syntax output

Explanation:

First we declared an ordinary variable here in our program as follows:

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:

listBox1.Items.Add("Loop " + nCounter.ToString( ) );

In this way, we can add it properly at the List box.


The role of the BeginUpdate( ) method here in our code is simply to turn off the visual
updating of the List box until the EndUpdate( ) method is called, while the EndUpdate( )
method resumes the visual updating of the List box.

Sample Output:

Figure 5.4a Generating an inverse sequence numbers


using for loop syntax 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

Figure 5.4 Generating an inverse sequence numbers using do-while

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter = 5;
do
{
listBox1.Items.Add("Loop " + nCounter.ToString());
nCounter--;
} while (nCounter >= 1);
listBox1.EndUpdate();
140

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.5a Generating inverse sequence numbers


using do-while loop syntax output

Explanation:

First we declared an ordinary variable here in our program as follows:

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

Figure 5.6a Generating numbers by 5 using loop statement

Our solution is this:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter;
for (nCounter = 5; nCounter <= 50; nCounter=nCounter + 5)
{
listBox1.Items.Add("Loop " + nCounter.ToString());
}
listBox1.EndUpdate();
}
142

Sample Output:

Figure 5.6b Generating numbers by 5 using loop statement output

Since we start from 5 and end at 50, we have this for loop line:

for (nCounter = 5; nCounter <= 50; nCounter=nCounter + 5)

To convert the code to do while loop statement equivalent, we will have the following
solution:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter = 5;
do
{
listBox1.Items.Add("Loop " + nCounter.ToString());
nCounter=nCounter+5;
} while (nCounter <= 50);
listBox1.EndUpdate();
}

What if we want to generate the number in reverse order? Consider the following design
specification:
143

csLoopby5 In Reverse Order

Decrement by 5 Now!

50
40
35
30
25
20
15
10
5

Figure 5.6b Generating numbers inversely by 5 using loop statement

The solution is just an opposite from the previous one:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter;
for (nCounter = 50; nCounter >= 5; nCounter=nCounter-5)
{
listBox1.Items.Add("Loop " + nCounter.ToString());
}
listBox1.EndUpdate();
}

Sample Output:
144

Figure 5.6d Generating numbers inversely by 5


using loop statement output

Here, we are using the decrementation process in the for loop line:

for (nCounter = 50; nCounter >= 5; nCounter=nCounter-5)

How can we convert the syntax into the do-while Loop statement? Here is its equivalent
code:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
int nCounter = 50;
do
{
listBox1.Items.Add("Loop " + nCounter.ToString());
nCounter = nCounter - 5;
} while (nCounter >= 5);
listBox1.EndUpdate();
}

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

A Brief Discussion about Simple Array

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[ ]

Examples of Array Declaration:

Example 1:

String[ ] strIDArray = new String[5];

strIDArray[0] = "Monkey";
strIDArray[1] = "Zebra";
strIDArray[2] = "Elephant";
strIDArray[3] = "Eagle";
strIDArray[4] = "Crocodile";

Or this way (Enumerated Array format):

String[ ] strIDArray = {“Monkey”, “Zebra”,”Elephant”,”Eagle”,”Crocodile”};

Example 2:

int[ ] intIDArray = new int[5];


intIDArray[0] = 6;
intIDArray[1] = 12;
intIDArray[2] = 14;
intIDArray[3] = 9;
intIDArray[4] = 4;

Or this way (Enumerated Array format):

int[ ] intIDArray = {6, 12, 14, 9, 4};

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!

Click Now! Button

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
String[] strIDArray = new String[5];
strIDArray[0] = "Monkey";
strIDArray[1] = "Zebra";
strIDArray[2] = "Elephant";
strIDArray[3] = "Eagle";
strIDArray[4] = "Crocodile";
foreach (String strArrayItem in strIDArray)
{
listBox1.Items.Add(strArrayItem.ToString());
}
listBox1.EndUpdate();
}

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.7a Using for each looping statement output

Explanation:

First, we declare an array variable here with the following code:

String[ ] strIDArray = new String[5];


148

.
.
.
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:

Dim intIDArray(4), strArrayItem As String


intIDArray(0) = "Monkey"
intIDArray(1) = "Zebra"
intIDArray(2) = "Elephant"
intIDArray(3) = "Eagle"
intIDArray(4) = "Crocodile"
For Each strArrayItem In intIDArray
ListBox1.Items.Add(strArrayItem)
Next strArrayItem

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:

foreach (String strArrayItem in strIDArray)


{
listBox1.Items.Add(strArrayItem.ToString());
}
149

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

SuperFairy Ship Vessels Number!


Button
List Now!

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

int[] intIDArray = new int[5];


intIDArray[0] = 6;
intIDArray[1] = 12;
intIDArray[2] = 14;
intIDArray[3] = 9;
intIDArray[4] = 4;
foreach (int intArrayItem in intIDArray)
{
listBox1.Items.Add(intArrayItem.ToString());
}
listBox1.EndUpdate();
}

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.8a Using for each looping statement 2 output

Explanation:

First, we declare an array variable here with the following code:

int[ ] intIDArray = new int[5];


.
.
.
And here is how we can assign an individual integer value to the array variable:

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

Figure 5.9 Display and Count the Objects in the form.

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:

“There are: 8 objects in this form!

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?

private void button1_Click(object sender, EventArgs e)


{
int nIterate = 0;
foreach(Control oObject in Controls) {
nIterate++;
}
textBox1.Text = nIterate.ToString();
}

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:

foreach(Control oObject in Controls) {


nIterate++;
}

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

There are: 8 objects in this form!


154

Where 8 was produced by the following code:

textBox1.Text = nIterate.ToString( );

and the nIterate variable contains a value of 8 which in turn will be displayed inside Text
box 1.

Here is the breakdown of the objects counted in our Form control:

Button - 1
Labels - 3
Text boxes - 2
Radio button - 1
Check box - 1
----------
A total of 8

Now can you count them, individually?

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

Figure 5.11 Preload the items into the List Box l


155

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:

private void Form1_Load(object sender, EventArgs e)


{
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");
}

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

Beef Text box

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Text = "";
textBox1.Text = "";
// Add items to the List box
listBox1.Items.Add("Chicken");
listBox1.Items.Add("Beef");
listBox1.Items.Add("Pork");
listBox1.Items.Add("Vegetables");
158

listBox1.Items.Add("Fish");
listBox1.Items.Add("Squids");
listBox1.Items.Add("Noodles");
listBox1.Items.Add("Fruits");
}

9. Double-click now the List box to display the listBox1_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = "";
textBox1.Text = listBox1.Text;
}

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:

listBox1.Text = " ";


159

textBox1.Text = " ";

Then we preloaded the list box with the following list of products using the AddItem
method:

// Add items to the List box


listBox1.Items.Add("Chicken");
listBox1.Items.Add("Beef");
listBox1.Items.Add("Pork");
listBox1.Items.Add("Vegetables");
listBox1.Items.Add("Fish");
listBox1.Items.Add("Squids");
listBox1.Items.Add("Noodles");
listBox1.Items.Add("Fruits");

And finally, we display the selected item into the text box with the following code:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
textBox1.Text = " ";
textBox1.Text = listBox1.Text;
}

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

Add Item to the List box: Item 1


Item 2
Item 5
Item 3
Item 4
Add to the List
List box

Remove from the


List
160

Text box Buttons

Figure 5.13 Adding and Removing an Item in the List box

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("Item 1");
listBox1.Items.Add("Item 2");
listBox1.Items.Add("Item 3");
listBox1.Items.Add("Item 4");
textBox1.Text = " ";
}

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.Items.Add(textBox1.Text);
textBox1.Text = " ";
161

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:

private void Form1_Load(object sender, EventArgs e)


162

{
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:

textBox1.Text = " ";

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.Items.Add(textBox1.Text);
textBox1.Text = " ";
textBox1.Focus( );
}

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:

textBox1.Text = " ";


textBox1.Focus( );

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:

private void button2_Click(object sender, EventArgs e)


{

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

Preloaded with Items:


Sizzling beef
Pork tonkatsu
Chicken torikatsu
Fish tempura List box
Miso soup
Coffee jelly
Yukiudon
Gyoza

Click an Item to Remove it from the List!

Figure 5.14 Remove an Item from a List box


164

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("sizzling beef");
listBox1.Items.Add("pork tonkatsu");
listBox1.Items.Add("chicken torikatsu");
listBox1.Items.Add("fish tempura");
listBox1.Items.Add("miso soup");
listBox1.Items.Add("coffee jelly");
listBox1.Items.Add("yakiudon");
listBox1.Items.Add("gyoza");
}

9. Double-click now the ListBox to display the listBox1_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
listBox1.Items.Remove(listBox1.SelectedItem);
}

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:

Figure 5.14a Remove an Item from a List box output

Explanation:

First, we load the list box with items, using the following code:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("sizzling beef");
listBox1.Items.Add("pork tonkatsu");
listBox1.Items.Add("chicken torikatsu");
listBox1.Items.Add("fish tempura");
listBox1.Items.Add("miso soup");
listBox1.Items.Add("coffee jelly");
listBox1.Items.Add("yakiudon");
listBox1.Items.Add("gyoza");
}

Then we put a code in the method listBox1_SelectedIndexChanged( ) with the following:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
listBox1.Items.Remove(listBox1.SelectedItem);
}

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("sizzling beef");
listBox1.Items.Add("pork tonkatsu");
listBox1.Items.Add("chicken torikatsu");
listBox1.Items.Add("fish tempura");
listBox1.Items.Add("miso soup");
listBox1.Items.Add("coffee jelly");
listBox1.Items.Add("yakiudon");
listBox1.Items.Add("gyoza");
}

9. Double-click the Remove Selected/Highlighted Item button control 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.RemoveAt(listBox1.SelectedIndex);
}

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

Figure 5.14a Removing a selected item using Button output

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}

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

Click an Item to Display to List box 2:

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");
}

8. Double-click now the ListBox to display the listBox1_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//Add item to List box 2
listBox2.Items.Add(listBox1.Text);
}

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:

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");
}

Next, we add the selected items from List box 1 into List box 2, using the following
code:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


171

{
//Add item to List box 2
listBox2.Items.Add(listBox1.Text);
}

It seems so simple, isn’t it? Well, because we knew how to do it.


There are times that we want to transfer an item from one list box to another (not just
copying it from one list box to another). How are we able to do that? In our next example,
we will accomplish this particular task:

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

Click an Item to transfer to other List box:

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("Java");
listBox1.Items.Add("C++");
listBox1.Items.Add("Perl");
listBox1.Items.Add("Basic");
listBox1.Items.Add("FoxPro");
listBox1.Items.Add("Pascal");
listBox1.Items.Add("COBOL");
listBox1.Items.Add("HTML");
listBox1.Items.Add("XML");
listBox1.Items.Add("Fortran");
}

8. Double-click now the List box to display the listBox1_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//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. Double-click now the List box to display the listBox2_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
//Add the item to the other List box
listBox1.Items.Add(listBox2.Text);
listBox1.Items.Remove(listBox1.Text);
//Remove the item from this List box
listBox2.Items.Remove(listBox2.SelectedItem);
}
173

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("Java");
listBox1.Items.Add("C++");
listBox1.Items.Add("Perl");
listBox1.Items.Add("Basic");
listBox1.Items.Add("FoxPro");
listBox1.Items.Add("Pascal");
174

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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
//Add the item to the other List box
int iIndex=0;
listBox2.Items.Add(listBox1.Text);
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:

private void listBox2_SelectedIndexChanged(object sender, EventArgs e)


{
//Add the item to the other List box
listBox1.Items.Add(listBox2.Text);
listBox1.Items.Remove(listBox1.Text);
//Remove the item from this List box
listBox2.Items.Remove(listBox2.SelectedItem);
}

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

Figure 5.19 Determining what item is currently selected

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

private void Form1_Load(object sender, EventArgs e)


{
textBox1.Text = " ";
listBox1.Items.Add("Germany");
listBox1.Items.Add("Philippines");
listBox1.Items.Add("Singapore");
listBox1.Items.Add("Japan");
listBox1.Items.Add("Alaska");
listBox1.Items.Add("California");
listBox1.Items.Add("Italy");
listBox1.Items.Add("France");
listBox1.Items.Add("Alabama");
listBox1.Items.Add("Brazil");
listBox1.Items.Add("Venezuela");
}

10. Double-click now the list box to display the listBox1_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
if (listBox1.Text== "Germany")
{
textBox1.Text = " ";
textBox1.Text = "Germany is in Europe";
}
else if (listBox1.Text== "Philippines")
{
textBox1.Text = " ";
textBox1.Text = "Philippines is in Asia";
}
else if (listBox1.Text == "Singapore")
{
textBox1.Text = " ";
textBox1.Text = "Singapore is in Asia";
}
else if (listBox1.Text == "Japan")
{
textBox1.Text = " ";
textBox1.Text = "Japan is in Asia";
}
else if (listBox1.Text == "Alaska")
{
textBox1.Text = " ";
textBox1.Text = "Alaska is in North America";
}
else if (listBox1.Text == "California")
{
textBox1.Text = " ";
textBox1.Text = "California is in North America";
}
else if (listBox1.Text == "Italy")
{
textBox1.Text = " ";
textBox1.Text = "Italy is in Europe";
}
177

else if (listBox1.Text == "France")


{
textBox1.Text = " ";
textBox1.Text = "France is in Europe";
}
else if (listBox1.Text == "Alabama")
{
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";
}

} // end of void listBox1

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.17a Determining what item is currently selected output


178

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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
if (listBox1.Text== "Germany")
{
textBox1.Text = " ";
textBox1.Text = "Germany is in Europe";
}
else if (listBox1.Text== "Philippines")
{
textBox1.Text = " ";
textBox1.Text = "Philippines is in Asia";
}
else if (listBox1.Text == "Singapore")
{
textBox1.Text = " ";
textBox1.Text = "Singapore is in Asia";
}
else if (listBox1.Text == "Japan")
{
textBox1.Text = " ";
textBox1.Text = "Japan is in Asia";
}
else if (listBox1.Text == "Alaska")
{
textBox1.Text = " ";
textBox1.Text = "Alaska is in North America";
}
else if (listBox1.Text == "California")
{
textBox1.Text = " ";
textBox1.Text = "California is in North America";
}
else if (listBox1.Text == "Italy")
{
textBox1.Text = " ";
textBox1.Text = "Italy is in Europe";
}
else if (listBox1.Text == "France")
{
textBox1.Text = " ";
textBox1.Text = "France is in Europe";
}
else if (listBox1.Text == "Alabama")
179

{
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";
}

} // end of void listBox1

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:

Text box 1 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:

Button objects Property Setting

Add Button Name btnAdd


Text Add

Delete Button Name btnDelete


Text Remove

Clear Button Name btnClear


Text Clear

Exit Button Name btnExit


Text Exit

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:

private void Form1_Load(object sender, EventArgs e)


{
textBox1.Text = " ";
textBox2.Text = " ";
//We have to disable the Add button by default to prevent it from
//adding any blank spaces to the List Box
//It can only add an Item if there is a Text Change event
//happend at the Text Box 1. Meaning, the user is now inputting data
//in the Text Box 1.
btnAdd.Enabled = false;
}

12. Double-click now the list box to display the listBox1_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:
182

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
btnDelete.Enabled = listBox1.SelectedIndex != -1;
}

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:

private void textBox1_TextChanged(object sender, EventArgs e)


{
int nLen;
nLen = textBox1.Text.Length;
if (nLen > 0)
{
// Enable the Add button if at least
// one character in the text box 1
btnAdd.Enabled = true;
}
}

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:

private void btnAdd_Click(object sender, EventArgs e)


{
//Add to the List box
listBox1.Items.Add(textBox1.Text);
//Clear the text box
textBox1.Text = " ";
textBox1.Focus();
//Display the number of items
//to text box 2
textBox2.Text = Convert.ToString(listBox1.Items.Count);
//We need to disable the Add button after we click it so that
//the space character of the TextBox1 cannot be allowed to be added to
//the ListBox. Only in this way we can ensure that no blank spaces
//can be added to the ListBox.
btnAdd.Enabled = false;
}

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:

private void btnDelete_Click(object sender, EventArgs e)


{
int Ind;
//Get the index
Ind = listBox1.SelectedIndex;
if (Ind >= 0)
{
//Remove it from the List box
listBox1.Items.RemoveAt(Ind);
183

//Display the number of items


//to the text box 2
textBox2.Text = Convert.ToString(listBox1.Items.Count);
}
else
{
//Generate a warning message
MessageBox.Show("No more items left to erase!");
}
//Disable (dimmed) button if no items
//on the List box
btnDelete.Enabled = (listBox1.SelectedIndex != -1);
} // end of the private void btnDelete_Click

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:

private void btnAdd_Click(object sender, EventArgs e)


{
//Add to the List box
listBox1.Items.Add(textBox1.Text);
//Clear the text box
textBox1.Text = " ";
textBox1.Focus( );
//Display the number of items
//to text box 2
textBox2.Text = Convert.ToString(listBox1.Items.Count);
//We need to disable the Add button after we click it so that
//the space character of the TextBox1 cannot be allowed to be added to
//the ListBox. Only in this way we can ensure that no blank spaces
//can be added to the ListBox.
btnAdd.Enabled = false;
}
185

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:

textBox1.Text = " ";

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:

private void btnDelete_Click(object sender, EventArgs e)


{
int Ind;
//Get the index
Ind = listBox1.SelectedIndex;
if (Ind >= 0)
{
//Remove it from the List box
listBox1.Items.RemoveAt(Ind);
//Display the number of items
//to the text box 2
textBox2.Text = Convert.ToString(listBox1.Items.Count);
}
else
{
//Generate a warning sound
MessageBox.Show("No more items left to erase!");
}
//Disable (dimmed) button if no items
//on the List box
btnDelete.Enabled = (listBox1.SelectedIndex != -1);
} // end of the btnDelete_Click
186

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:

btnDelete.Enabled = (listBox1.SelectedIndex != -1);

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!

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
187

//to the text box 2


textBox2.Text = Convert.ToString(listBox1.Items.Count);
}

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:

private void btnExit_Click(object sender, EventArgs e)


{
this.Close( );
}

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:

private void textBox1_TextChanged(object sender, EventArgs e)


{
int nLen;
nLen = textBox1.Text.Length;

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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
btnDelete.Enabled = listBox1.SelectedIndex != -1;
}
expression
188

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).

private void Form1_Load(object sender, EventArgs e)


{
textBox1.Text = " ";
textBox2.Text = " ";
//We have to disable the Add button by default to prevent it from
//adding any blank spaces to the List Box
//It can only add an Item if there is a Text Change event
//happend at the Text Box 1. Meaning, the user is now inputting data
//in the Text Box 1.
btnAdd.Enabled = false;
}

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

January Press Shift and Arrow keys


February to select multiple items:
March
List box 1 April
May Transfer
June
July
August
Buttons
September
Clear

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

Objects Property Setting

List box 1 Name ListBox1


SelectionMode MultiExtended

Transfer Button Name btnTransfer


Text Transfer

Clear Button Name btnClear


Text Clear

Exit Button Name btnExit


Text Exit

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("January");
listBox1.Items.Add("February");
listBox1.Items.Add("March");
listBox1.Items.Add("April");
listBox1.Items.Add("May");
listBox1.Items.Add("June");
listBox1.Items.Add("July");
listBox1.Items.Add("August");
listBox1.Items.Add("September");
listBox1.Items.Add("October");
listBox1.Items.Add("November");
listBox1.Items.Add("December");
//Pre-select a collection of items
listBox1.SetSelected(1, true);
listBox1.SetSelected(3, true);
listBox1.SetSelected(5, true);
}

10. Double-click now the list box to display the listBox1_SelectedIndexChanged


event method. Embed the following lines of code (in bold only) to the method:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
//Click the transfer button
191

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:

private void btnTransfer_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate();
foreach (String sItem in listBox1.SelectedItems)
{
listBox2.Items.Add(sItem);
}
listBox1.EndUpdate();
btnClear.Enabled = true;
}

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:

private void btnClear_Click(object sender, EventArgs e)


{
listBox2.Items.Clear();
btnClear.Enabled = false;
}

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:

private void btnExit_Click(object sender, EventArgs e)


{
this.Close();
}

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("January");
listBox1.Items.Add("February");
listBox1.Items.Add("March");
listBox1.Items.Add("April");
listBox1.Items.Add("May");
listBox1.Items.Add("June");
listBox1.Items.Add("July");
listBox1.Items.Add("August");
listBox1.Items.Add("September");
listBox1.Items.Add("October");
listBox1.Items.Add("November");
listBox1.Items.Add("December");
//Pre-select a collection of items
listBox1.SetSelected(1, true);
listBox1.SetSelected(3, true);
listBox1.SetSelected(5, true);
}
193

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:

private void btnTransfer_Click(object sender, EventArgs e)


{
listBox1.BeginUpdate( );
foreach (String sItem in listBox1.SelectedItems)
{
listBox2.Items.Add(sItem);
}
listBox1.EndUpdate( );
btnClear.Enabled = true;
}

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:

private void btnClear_Click(object sender, EventArgs e)


{
listBox2.Items.Clear( );
btnClear.Enabled = false;
}

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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{
//Click the transfer button
// Enabling the Trasfer button once the user
// selects an item or items in List box 1.
btnTransfer.Enabled = true;
}
194

Lastly, we will examine the code behind the Exit Button:

private void btnExit_Click(object sender, EventArgs e)


{
this.Close( );
}

The Close( ) method simply closes the current object (Control) which is in this case is the
Form.

Using Combo Boxes

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.

Advantages of the Combo Box over List Box

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

Just click to choose:


Combo box
Pork

The Item you choose is:

Pork Text box


Figure 5.25 Displaying an item at the Text box

Figure 5.25 Displaying an item at the Text box

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:

private void Form1_Load(object sender, EventArgs e)


{
textBox1.Text = " ";
comboBox1.Text = "Chicken";
//Add items to the Combo box
comboBox1.Items.Add("Chicken");
comboBox1.Items.Add("Beef");
comboBox1.Items.Add("Pork");
comboBox1.Items.Add("Vegetables");
comboBox1.Items.Add("Fish");
comboBox1.Items.Add("Squids");
comboBox1.Items.Add("Noodles");
comboBox1.Items.Add("Fruits");
}

10. Double-click now the Combo box to display the


ComboBox1_SelectedIndexChanged event method. Embed the following lines of
code (in bold only) to the method:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = " ";
textBox1.Text = Convert.ToString(comboBox1.SelectedItem);
}

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

Figure 5.20a Displaying an item at the Text 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 text box. So we just use
the following code:

private void Form1_Load(object sender, EventArgs e)


{
textBox1.Text = " ";
comboBox1.Text = "Chicken";
//Add items to the Combo box
comboBox1.Items.Add("Chicken");
comboBox1.Items.Add("Beef");
comboBox1.Items.Add("Pork");
comboBox1.Items.Add("Vegetables");
comboBox1.Items.Add("Fish");
comboBox1.Items.Add("Squids");
comboBox1.Items.Add("Noodles");
comboBox1.Items.Add("Fruits");
}

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:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)


{
textBox1.Text = " ";
textBox1.Text = Convert.ToString(comboBox1.SelectedItem);
}

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

Choose a product to buy:


Combo box
Banana Split

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:

private void Form1_Load(object sender, EventArgs e)


{
comboBox1.Text = "Banana Split";
listBox1.Text = "";
comboBox1.Items.Add("Banana Split");
comboBox1.Items.Add("Blueberry");
comboBox1.Items.Add("Cherry");
comboBox1.Items.Add("Mud Pie");
comboBox1.Items.Add("Nestle Crunch");
comboBox1.Items.Add("Oreo Cookies");
comboBox1.Items.Add("Choco Chip");
comboBox1.Items.Add("Chocolate Covered");
comboBox1.Items.Add("Rocky Road");
comboBox1.Items.Add("Strawberry");
comboBox1.Items.Add("Walnut Fudge");
comboBox1.Items.Add("Choco Almond");
comboBox1.Items.Add("Choco Mallows");
comboBox1.Items.Add("Brownies");
comboBox1.Items.Add("Butterfinger");
}

10. Double-click now the Combo box to display the


ComboBox1_SelectedIndexChanged event method. Embed the following lines of
code (in bold only) to the method:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Add(comboBox1.SelectedItem);
}

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:

private void Form1_Load(object sender, EventArgs e)


{
comboBox1.Text = "Banana Split";
listBox1.Text = " ";
comboBox1.Items.Add("Banana Split");
comboBox1.Items.Add("Blueberry");
comboBox1.Items.Add("Cherry");
comboBox1.Items.Add("Mud Pie");
comboBox1.Items.Add("Nestle Crunch");
comboBox1.Items.Add("Oreo Cookies");
comboBox1.Items.Add("Choco Chip");
comboBox1.Items.Add("Chocolate Covered");
comboBox1.Items.Add("Rocky Road");
comboBox1.Items.Add("Strawberry");
comboBox1.Items.Add("Walnut Fudge");
comboBox1.Items.Add("Choco Almond");
comboBox1.Items.Add("Choco Mallows");
comboBox1.Items.Add("Brownies");
comboBox1.Items.Add("Butterfinger");
}
201

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:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)


{
listBox1.Items.Add(comboBox1.SelectedItem);
}

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 of Products Bought:

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:

private void Form1_Load(object sender, EventArgs e)


{
comboBox1.Text = "Chicken";
//Add items to the Combo box
comboBox1.Items.Add("Chicken");
comboBox1.Items.Add("Beef");
comboBox1.Items.Add("Pork");
comboBox1.Items.Add("Vegetables");
comboBox1.Items.Add("Fish");
comboBox1.Items.Add("Squids");
comboBox1.Items.Add("Noodles");
comboBox1.Items.Add("Fruits");
}

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:

private void Form1_Load(object sender, EventArgs e)


{
comboBox1.Text = "Chicken";
//Add items to the Combo box
comboBox1.Items.Add("Chicken");
comboBox1.Items.Add("Beef");
comboBox1.Items.Add("Pork");
comboBox1.Items.Add("Vegetables");
comboBox1.Items.Add("Fish");
comboBox1.Items.Add("Squids");
comboBox1.Items.Add("Noodles");
comboBox1.Items.Add("Fruits");
}

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:

private void button1_Click(object sender, EventArgs e)


{
listBox1.Items.Add(comboBox1.Text);
}
204

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.

Visual Basic 2012 versus Visual C# 2012 Part 2

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

Preloaded with Items:


Sizzling beef
Pork tonkatsu
Chicken torikatsu
Fish tempura List box
Miso soup
Coffee jelly
Yukiudon
Gyoza

Double-click an Item to Remove it from the List!


205

Figure 5.23 Remove an Item from a List box

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("sizzling beef");
listBox1.Items.Add("pork tonkatsu");
listBox1.Items.Add("chicken torikatsu");
listBox1.Items.Add("fish tempura");
listBox1.Items.Add("miso soup");
listBox1.Items.Add("coffee jelly");
listBox1.Items.Add("yakiudon");
listBox1.Items.Add("gyoza");
}

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)
206

{
listBox1.Items.Remove(listBox1.SelectedItem);
}

10.This time we have to hardcode the listBox1_DoubleClick component initialization at


the InitializeComponent( ) part of our program. First, we have to select the
InitializeComponent( ) as we can see at the figure below
(you can observed that the InitializeComponent( ) is dimmed by default at the list of the
drop-down box):

.
.
.
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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{

}
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:

Figure 5.23a Remove an Item from a List box output

Explanation:

First, we load the list box with items, using the following code:
208

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("sizzling beef");
listBox1.Items.Add("pork tonkatsu");
listBox1.Items.Add("chicken torikatsu");
listBox1.Items.Add("fish tempura");
listBox1.Items.Add("miso soup");
listBox1.Items.Add("coffee jelly");
listBox1.Items.Add("yakiudon");
listBox1.Items.Add("gyoza");
}

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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{

private void listBox1_DoubleClick(object sender, EventArgs e)


{
listBox1.Items.Remove(listBox1.SelectedItem);
}

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.

After hard-coding our listBox1_DoubleClick( ) event method, we will initialize its


component at the InitializeComponent( ) part of our program, by emulating the
component initialization of the listBox1_SelectedIndexChanged( ) component, as you can
see on the code below:

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;
209

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

Double-click to Display into List box 2

Hamburger
Cheeseburger
Chickenburger List box 1
Mashed Potato
Spaghetti
Honeybun
Macaroni Salad
Cherry Pie

You displayed:

Hamburger List box 2


Spaghetti
Honeybun
210

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:

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.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

10.This time we have to hardcode the listBox1_DoubleClick component initialization at


the InitializeComponent( ) part of our program. First, we have to select the
InitializeComponent( ) as we can see at the figure below (you can observed that the
InitializeComponent( ) is dimmed by default at the list of the drop-down box):

.
.
.
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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{

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.
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:

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");
}

Next, we add the selected items from List box 1 into List box 2, using the following
code:

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);
}

After hard-coding our listBox1_DoubleClick( ) event method, we will initialize its


component at the InitializeComponent( ) part of our program, by emulating the
component initialization of the listBox1_SelectedIndexChanged( ) component, as you can
see on the code below:

private void InitializeComponent()


{
.
.
.
//
// listBox1
214

//
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

Double-click to transfer to other List box:

Java
C++
Perl
Basic
FoxPro List box 1
HTML

You transferred the following:


XML
Pascal

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("Java");
listBox1.Items.Add("C++");
listBox1.Items.Add("Perl");
listBox1.Items.Add("Basic");
listBox1.Items.Add("FoxPro");
listBox1.Items.Add("Pascal");
listBox1.Items.Add("COBOL");
listBox1.Items.Add("HTML");
listBox1.Items.Add("XML");
listBox1.Items.Add("Fortran");
}

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_SelectedIndexChanged(object sender, EventArgs e)


{

}
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 listBox2_DoubleClick(object sender, EventArgs e)


{
//Add the item to the other List box
listBox1.Items.Add(listBox2.Text);
listBox1.Items.Remove(listBox1.Text);
//Remove the item from this List box
listBox2.Items.Remove(listBox2.SelectedItem);
}

10.This time we have to hardcode the listBox1_DoubleClick and listBox2_DoubleClick


components initialization at the InitializeComponent( ) part of our program. First, we
have to select the InitializeComponent( ) as we can see at the figure below
(you can observed that the InitializeComponent( ) is dimmed by default at the list of the
drop-down box):

.
.
.
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:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{

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:

private void Form1_Load(object sender, EventArgs e)


{
listBox1.Items.Add("Java");
listBox1.Items.Add("C++");
listBox1.Items.Add("Perl");
listBox1.Items.Add("Basic");
listBox1.Items.Add("FoxPro");
listBox1.Items.Add("Pascal");
listBox1.Items.Add("COBOL");
listBox1.Items.Add("HTML");
listBox1.Items.Add("XML");
listBox1.Items.Add("Fortran");
}

Then we embed the following code at the List box 1 object and in its Double-click event:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)


{

}
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:

private void listBox2_DoubleClick(object sender, EventArgs e)


{
//Add the item to the other List box
listBox1.Items.Add(listBox2.Text);
listBox1.Items.Remove(listBox1.Text);
//Remove the item from this List box
listBox2.Items.Remove(listBox2.SelectedItem);
}

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.

After hard-coding our listBox1_DoubleClick( ) and listBox2_DoubleClick event


methods, we will initialize their components at the InitializeComponent( ) part of our
program, by emulating the component initialization of the
listBox1_SelectedIndexChanged( ) component, as you can see on the code below:

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);
//
// listBox2
220

//
.
.
.
}

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

List box 1 List box 2

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

List box 1 List box 2

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

List box 1 Button List box 2

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

List box Button


223

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

List box Button

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

There are: 6 controls in this Form!

Command1 Button

Text1 Text box

Combo1 Combo box


224

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

Steak Text box

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

8. 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 the
selected item on the list by double-clicking it. Follow the given figure below in
designing and developing the application program:
225

csListboxExam2

Hot Drinks Menu:

Cappuccino
Macchiato
Americano
Chocolate List box
Tea
Café Au Lait
Espresso
Brewed Coffe

Double-click an Item to Remove It!

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

9. 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 the
selected item on the list with a confirmation using a Button. Follow the given
figure below in designing and developing the application program:
csListboxExam3

Cold Drinks Menu:

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

Figaro Frost Menu:

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

Pastries and Snacks Menu:

Muffins
Banana Muffin
Carrot Loaf
Banana Crunch
Cookies List box 1
Pecan Bar
Figaro Bar
Cake Danish

List of Transferred Pastries and Snacks:

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:

Cebu is in the Visayan Region Text box

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

Enter product to add: Text box 1

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

Iced Coffee Press Shift and Arrow keys to


Iced Cappuccino select multiple items.
Iced Mocha
Iced Latte
Iced Tea
Ice Chocolate
Grilled Eggplant Transfer
Grilled Chicken
Grilled Ham
Grilled Beef
Grilled Fish Clear Buttons

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

Just click to select: Combo box

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

Select an Item: Combo box

List of items Selected:

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

Starsback Café Menu:


Combo box
List of Ordered items:
Order Button

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.

Using the Timer Control

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

The Time now is: label2

Figure 6.1b Using Timer control within a Label control


236

vbTimer1

The Time now is: 12:38:25 AM

Figure 6.1b Using Timer control within a Label control

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:

Control Property Setting

Timer1 Interval 1000


Timer1 Enabled True

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:

Figure 6.1c Using Timer control within a Label control

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:

private void timer1_Tick(object sender, EventArgs e)


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

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

Figure 6.1d Using Timer control with bigger Font size

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

Our Time now is: 11:34:04 PM

Figure 6.2b Using Timer control within Text box control

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:

Control Property Setting

Timer1 Interval 1000


Timer1 Enabled True

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:

private void timer1_Tick(object sender, EventArgs e)


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

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

Tuesday, June 17, 2008

The Date you selected is:

June 17, 2008 12:34: 20 AM

Figure 6.3 Using Date-Time Picker control


241

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:

private void Form1_Load(object sender, EventArgs e)


{
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MMMM dd, yyyy hh:mm:ss tt";
}

10. Double-click now the DateTimerPicker control to display the


DateTimePicker1_ValueChanged event method. Embed the following lines of
code (in bold only) to the method:
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
textBox1.Text = dateTimePicker1.Text;
}

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

Figure 6.3a Using Date-Time Picker control output

Explanation:

You will notice that in our code below:

private void Form1_Load(object sender, EventArgs e)


{
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MMMM dd, yyyy hh:mm:ss tt";
}

we format the date and time as we display them.


First, we format the date by putting first the Month using the MMMM format, then the
Day using the dd format, then lastly, the year in four digit format using the yyyy.
Then, we format the time as we display it. It is in the hour, minutes, and seconds format.
The hour is denoted by the hh format, the minutes with the mm format, and lastly the
seconds in ss format. The last format that we have is the tt format which refers to the AM
or PM for our time.
Now, once we choose a particular date in the calendar presented, the date of the calendar
and the corresponding time will be displayed at the Text box. We can accomplish this
task through the following code:

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)


{
textBox1.Text = dateTimePicker1.Text;
}
243

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.

Using Scroll Bars

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

The Scrollbar position is: Text box

Figure 6.4 Using Horizontal scroll 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.
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:

private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)


{
textBox1.Text = Convert.ToString(hScrollBar1.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:

Figure 6.4a Using Horizontal scroll bar output


245

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:

private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)


{
textBox1.Text = Convert.ToString(hScrollBar1.Value);
}

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

The well-coordinated Scrollbars!


HScrollbar 1

The position for both scrollbars is: Text box

HScrollbar 2

Figure 6.5 Using Two Synchronized Horizontal scrollbars


246

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:

private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)


{
hScrollBar2.Value = e.NewValue;
textBox1.Text = Convert.ToString(hScrollBar2.Value);
}

9. Double-click the second Scrollbar (HScrollBar2) control to display the


HScrollbar2_Scroll event method. Embed the following lines of code (in bold
only) to the method:

private void hScrollBar2_Scroll(object sender, ScrollEventArgs e)


{
hScrollBar1.Value = e.NewValue;
textBox1.Text = Convert.ToString(hScrollBar1.Value);
}

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

Figure 6.5a Using Two Synchronized Horizontal scrollbars 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 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:

In Horizontal ScrollBar 1, we updated the ScrollBar 2 with the new value:

private void hScrollBar1_Scroll(object sender, ScrollEventArgs e)


{
hScrollBar2.Value = e.NewValue;
textBox1.Text = Convert.ToString(hScrollBar2.Value);
}

In Horizontal ScrollBar 2, we updated the ScrollBar 1 with the new value:

private void hScrollBar2_Scroll(object sender, ScrollEventArgs e)


{
hScrollBar1.Value = e.NewValue;
textBox1.Text = Convert.ToString(hScrollBar1.Value);
248

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

The scrollbar position is:


Text box

Figure 6.6 Using Vertical scroll 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 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:

Figure 6.6a Using Vertical scroll bar 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

private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)


{
textBox1.Text = Convert.ToString(vScrollBar1.Value);
}

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.

Using Picture Box Control


A picture box control is used for displaying graphics with the following formats: .png,
.bmp, .jpeg, .gif and even an icon. Moreover, a picture box can contain other controls. In
this capacity, we can place a Button within a picture box.
We can design text and graphics methods in a picture box at run time. The graphics
methods will enable us to draw lines, rectangles, and circles on a picture 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

Display Now the Picture!


Button
251

Figure 6. 7 Using the Picture box control

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

Figure 6.7a Using the Picture box control output

Explanation:

The syntax of loading the picture in our Picture box control is so simple. Here is its code
below:

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");
}

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.

Using LinkLabel Control


We can use LinkLabel Control to activate a Hyperlink capability. Let us try it now!

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

Do you want to go to Yahoo website?

Figure 6. 8 Using the LinkLabel control

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

6. Double-click the LinkLabel control to display the LinkLabel1_Click event


method. Embed the following lines of code (in bold only) to the method:
private void linkLabel1_LinkClicked(object sender,
LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("www.yahoo.com");
}

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:

private void linkLabel1_LinkClicked(object sender,


LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("www.yahoo.com");
}

Well, I guess you would agree with me on how simple the program code is.
255

Using the Panel Control


We use panels to group other controls, usually to divide a Form control into regions by
classifications or functionalities. For example, we may let the user selects a kind of soft-
drinks in one panel, and snack foods in another panel.

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

You clicked: RadioButton3!

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!";
}

private void checkBox2_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "checkBox2!";
}

private void checkBox3_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "checkBox3!";
}

private void checkBox4_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "checkBox4!";
}

private void checkBox5_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "checkBox5!";
}

private void radioButton1_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "radioButton1!";
}

private void radioButton2_CheckedChanged(object sender, EventArgs e)


{
257

textBox1.Text = "radioButton2!";
}

private void radioButton3_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "radioButton3!";
}

private void radioButton4_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "radioButton4!";
}

private void radioButton5_CheckedChanged(object sender, EventArgs e)


{
textBox1.Text = "radioButton5!";
}

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:

private void checkBox1_CheckedChanged(object sender, EventArgs e)


{
258

textBox1.Text = "checkBox1!";
}
….
….
private void radioButton5_CheckedChanged(object sender, EventArgs e)
{
textBox1.Text = "radioButton5!";
}

to understand it all.

Using the Track Bar Control


A track bar control is like what we can see in our Windows Media Player’s volume-
control or in our computer speaker’s volume-control. We can display our track bar
horizontally or vertically by just setting its Orientation property.

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

The track bar value is: Text Box

Figure 6. 10 Using the Track Bar control


259

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:

private void trackBar1_Scroll(object sender, EventArgs e)


{
textBox1.Text = Convert.ToString(trackBar1.Value);
}

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.

Using the Progress Bar


The Progress Bar control is a simple control that show the progress of some operation by
displaying a moving rectangular gauge in a horizontal bar.

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

Now counting: Text Box

Start Moving Now!


Button 1
and
Clear the Value Button 2
of Progress Bar!
261

Figure 6. 11 Using the Progress Bar control

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:

private void button1_Click(object sender, EventArgs e)


{
timer1.Enabled = true;
}

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:

private void button2_Click(object sender, EventArgs e)


{
progressBar1.Value = progressBar1.Minimum;
textBox1.Text = Convert.ToString(progressBar1.Minimum);
}
262

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:

private void button1_Click(object sender, EventArgs e)


{
timer1.Enabled = true;
}

Now within the Timer control, we simply put an incrementation formula:

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:

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;
}

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:

private void button2_Click(object sender, EventArgs e)


{
progressBar1.Value = progressBar1.Minimum;
textBox1.Text = Convert.ToString(progressBar1.Minimum);
}

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

In My Own Personal Experience


I used this powerful idea when I designed my master’s thesis in Computer Science (at
AMA Computer University – Quezon City Campus) which deals with sales performance
for a hypothetical high-tech retail store. During that time (in DOS-based era), I have to
designed and programmed my own Progress Bar since this particular control was not yet
available on that time. I developed my thesis within the LAN-based environment to
simulate the online live-sales transaction where I used one workstation to act as a POS-
terminal and another workstation to act as the sales performance monitoring PC-terminal.
I presented and sell this idea to the thesis panel members with the conviction that this will
work also in an Intranet-based setting where all live sales transactions (in a multinational
high-tech retail stores scattered all over the world) can be recorded and reflected in real-
time for the top executives to see it anytime and anywhere they want. Truly, this is an
amazing idea. And probably, I am the only person in the world who can appreciate it. But
who cares? As long as I am happy dreaming of making this marketable idea to happen.
Who knows?

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.

Note: The Acronyms and their meanings:


AMA – Amable Mendoza Aguiluz LAN – Local Area Network PC – Personal Computer
DOS – Disk Operating System POS – Point of Sale System
265

LAB ACTIVITY
TEST 5

1. Design and develop a simple timer-control application system that demonstrates


how it works with a bigger font size of the clock timer and at the same time a
second clock timer as a Label. Follow the given figure below in designing and
developing the application program:

csClock1

System Clock:

Text box
4:28:40 PM
4:28:40 PM

Label

2. 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:

csHScrollbar 5

0 Intensity 50 109 Intensity

Note:
Set the Max property of the Horizontal Scroll bar to 109.

3.Design and develop a simple well-coordinated Vertical scroll-bars application system


that demonstrates how they work. Follow the given figure below in designing and
developing the application program:
266

csVertical Scroll bar 1

Down 0

50 Label 1

Up 109

The well-coordinated Vertical Scroll bars!

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

Low Middle High

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

Panel for Animals Panel for Fruits

Dog Banana

Cat Apple

Lion Mango

Tiger Orange

Zebra Melon

You clicked: Mango!

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

The track bar value is: Text Box

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

Start Moving Now! Button 1

Progress Bar

Now counting: Text Box

Clear the Value


of Progress Bar! Button 2
270

Chapter 7
Designing and Developing Menus

What Is A Menu Or a Toolbar?


Menus are controls that allow us to select some items that can help us to
accomplish our task. Like the task of saving our documents, copying or pasting a
paragraph or cutting some parts of it, or printing a document that we write. How about 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 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. In other words, the commonly used commands in menu have their equivalent
icons in the toolbar that we can access quickly.
When we create a large application system, we need to use menus and toolbars to
organize each subsystems effectively and efficiently. In designing and developing menus
and toolbars, we have to make it sure that they conform to the Windows graphical user-
interface (GUI) standards, so that the user can easily adapt them for their daily use. In
other words, we have to mimic how the Microsoft Office software are designed and
created. For example, the File menu must be the first menu and the Help menu must be
the last menu of our application system, the way the Microsoft Word works. And the File
menu of our application system should contain the menu items such as New, Open,
Close, Save and Print, while the Help menu should contain menu items such as How Do
I? and About the Application System. Though not exactly as what is mentioned above,
but at least similarly arranged or grouped by.
Furthermore, menus and toolbars provide a compact way to organize the
commands that make our application system work and provide a convenient way to
access the functionality within it. Menus and toolbars save user’s desktop space, because
they only occupy space when activated. Once the user finishes accessing the menu, it
closes and returns control to the user’s current state or work.

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

Menu1 Menu2 Menu3


M1 Item1
M1 Item2
M1 Item3
M1 Item4
Exit

Figure 6.1 Menu items of the Menu1 menu


272

Form1
Menu title
Menu1 Menu2 Menu3
M2 Item1
Menu items M2 Item2
M2 Item3

Figure 6.2 Menu items of the Menu2 menu

Form1

Menu1 Menu2 Menu3


M3 Item1
M3 Item2

Figure 6.3 Menu items of the Menu3 menu

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:

Figure 7.1d Menu items of the Menu1 menu 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

Menu1 Menu2 Menu3


M1 Item1 F3
M1 Item2 Ctrl+W
M1 Item3 Alt+F9
M1 Item4 Say “Hello!”
Say “Goodbye?”
Exit

Figure 6.1a Menu items of the Menu1 menu

Form1
Menu title
Menu1 Menu2 Menu3
M2 Item1
Menu items M2 Item2
M2 Item3

Figure 6.2b Menu items of the Menu2 menu

Form1

Menu1 Menu2 Menu3


M3 Item1
Hidden
M3 Item2

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.

Figure 6.3c Menu items of the Menu3 menu

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:

Figure 7.2d Menu items of the Menu1 menu 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:

private void m3Item1ToolStripMenuItem_Click(object sender, EventArgs e)


{
m3Item2ToolStripMenuItem.Visible = true;
MessageBox.Show("M3 Item2 is now Appearing!");
281

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:

private void Form1_Load(object sender, EventArgs e)


{
m3Item2ToolStripMenuItem.Visible = false;
}

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:

private void m3Item2ToolStripMenuItem_Click(object sender, EventArgs e)


{
m2Item2ToolStripMenuItem.Enabled = true;
MessageBox.Show("M2 Item 2 is now Enabled!");
}

So, that is it!

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

Control Calculate About


Buttons
Check boxes
Radio buttons

Figure 6.5 Menu items of the Control menu


282

Form1

Control Calculate About

Add
Subtract
Multiply
Divide

Figure 6.6 Menu items of the Calculate menu

Form1

Control Calculate About


Me?
Close

Figure 6.7 Menu items of the About menu

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:

private void buttonToolStripMenuItem_Click(object sender, EventArgs e)


{
M1Item1 frmM1Item1 = new M1Item1();
frmM1Item1.Show();
}

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:

private void checkBoxToolStripMenuItem_Click(object sender,EventArgs e)


{
M1Item2 frmM1Item2 = new M1Item2();
frmM1Item2.Show();
}

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:

private void radioButtonToolStripMenuItem_Click(object sender,


EventArgs e)
{
285

M1Item3 frmM1Item3 = new M1Item3();


frmM1Item3.Show();
}

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

Addition Operation should be here!

17. After designing the above specs, you have to embed the following code into the
Add menu item Click event method:

private void addToolStripMenuItem_Click(object sender, EventArgs e)


{
M2Item1 frmM2Item1 = new M2Item1();
frmM2Item1.Show();
}

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

Subtraction operation should be here!


286

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

Multiplication operation should be here!

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

Division operation should be here!


287

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

Copyright MyCompany 2008

My Own Street, Makati City

25.You have to embed the following code into the Me? menu item Click event method:

private void meToolStripMenuItem_Click(object sender, EventArgs e)


{
AboutBox1 frmAboutBox1 = new AboutBox1();
frmAboutBox1.Show();
}

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

private void closeToolStripMenuItem_Click(object sender, EventArgs e)


{
this.Close();
}

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:

Figure 7.3d Menu items of the Calculate menu output

Explanation:

Calling the Form to appear once we click a particular menu item, we simply have the
following code:

private void buttonToolStripMenuItem_Click(object sender, EventArgs e)


{
M1Item1 frmM1Item1 = new M1Item1();
frmM1Item1.Show();
}

The same also apply with how we can call the other Form control when we click a
particular menu item:

private void checkBoxToolStripMenuItem_Click(object sender,EventArgs e)


{
M1Item2 frmM1Item2 = new M1Item2();
289

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

Figure 6.9a Creating a toolbar.

Form1

Menu1 Menu2
M1 Item1
M1 Item 2

Exit

Figure 6.9b Menu items of the Menu1 menu

Form1
Menu title
Menu1 Menu2
Tool bars M2 Item1
Menu items Close

Figure 6.9c Menu items of the Menu2 menu

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:

private void m1Item1ToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Menu 1 Item 1 clicked!");
}

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

Figure 6.9d Menu items of the Menu2 menu output

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:

private void m1Item1ToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Menu 1 Item 1 clicked!");
}

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:

private void toolStripButton1_Click(object sender, EventArgs e)


{
MessageBox.Show("Internet Explorer icon is clicked!");
}

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

Figure 6.10a Creating a toolbar that calls multiple forms.

vbMyContextMenu1

Menu1 Menu2
M1 Item1
icons
M1 Item2

Exit Context MI1


Context MI2
Copy
Cut

Context TI1
Paste
Context TI3

Figure 6.10a Creating a toolbar that calls multiple forms.

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

private void toolStripButton1_Click(object sender, EventArgs e)


{
MessageBox.Show("IE Explorer icon (Toolbar 1) is clicked!");
}

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

private void cutToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Cut Context menu Item clicked!");
}

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

Figure 7.5d Context Menu output

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:

private void m1Item1ToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Menu 1 Item 1 clicked!");
}

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:

private void contextMI2ToolStripMenuItem_Click(object sender, EventArgs e)


{
MessageBox.Show("Context menu Item 2 clicked!");
}
300

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

Menu1 Menu2 Help


Item One
Item Two
Item Three
Item Four

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

Menu1 Menu2 Help


First Item
Second Item
Third Item
302

Form1

Menu1 Menu2 Help


Help 1
Help 2

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

Box Button Help


Text box
Check box
List box
Combo box

Form1

Box Button Help


Button
Radio button
303

Form1

Box Button Help


Need Help?
About Help

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

Menu1 Menu2 Help


Tool bar

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

Box Button Help

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

Menu1 Menu2 Menu3


M1 Item1 F11
M1 Item2 Ctrl+Q
M1 Item3 Alt+F12
M1 Item4 Say “Hi”
Say “Hello”
Exit

Figure 6.1 Menu items of the Menu1 menu

csYourMenu2
Menu title
Menu1 Menu2 Menu3
M2 Item1
Menu items M2 Item2
M2 Item3
M2 Item4

Figure 6.2 Menu items of the Menu2 menu

Form1

Menu1 Menu2 Menu3


Toolbars
M3 Item1
Hidden
M3 Item2
Exit

Figure 6.3 Menu items of the Menu3 menu


306

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

Figure 7.5a Menu items of the Menu1


307

csMyContextMenu1

Menu1 Menu2
About Me?
Close

Restore
Minimize
Cut
Copy
Paste

Close

Figure 7.5b Menu items of the Menu2

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.

DataSet, BindingSource and TableAdapter

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.

DataGridView and BindingNavigator


The DataGridView component is a container that allows us to bind data from our
data source and have it displayed in a spreadsheet format, like the way we can see it in
MS Excel software. The spreadsheet format displays the columns of data horizontally and
the rows of data vertically. Furthermore, the DataGridView component provides also
many properties that allow us to customize the appearance of the component itself as
well as properties that allow us to customize the headers and the display of data.
The BindingNavigator component provides a standard user-interface (UI)
component that allow the database user to navigate through the records that can be found
in our data source (DataSet). In other words, it provides buttons that allow the user to
navigate to the first and last records as well as to the next and previous records. It also
display how many records we have in our table as well as which record is currently
displayed.
The data binding means taking data referenced by our BindingSource and bind it
to a data control. The data control receives its data from our BindingSource, which in
turn receives its data from our data source (DataSet), and the data is automatically
displayed in the control for the user to see and manipulate.
After all these preliminary discussions about ADO.NET, it is time now to see it in
action. Let us have now our running example.

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

ContactTypeID Name ModifiedDate

Figure 8.1a Data Grid View

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.

The DataGridView control displays a task list as shown below:


311

Figure 8.1b Data Grid View Tasks

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

Figure 8.1c Data Source Configuration Wizard

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

Figure 8.1d Change Data Source

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

Figure 8.1e Add Connection

10. Click the Test Connection button.

If the connection to the specified database is successful, then the following message box
will show up:

Figure 8.1f Test Connection


315

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.

This time the wizard displays an alert message.

13. Just click the Yes button.


14. Now click the Next button to 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:

Figure 8.1g Database Object

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:

Figure 8.1h Data Grid View 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

ContactTypeID Name ModifiedDate

Figure 8.1i Formatted Data Grid View Cells

Solution:

1. Still at the DataGridView Properties window, click the


AlternatingRowDefaultCellStyle property, and then click the ellipses button.
2. Click the BackColor property, click its arrow, then click the Custom tab, and click
the light Yellow color.
3. 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:
318

Figure 8.1g Formatted Data Grid View Cells

See??? It looks attractive! Isn’t it?

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:

Figure 8.2a Text Box Binding


319

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:

Figure 8.2b Data Source Configuration Wizard

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:

Figure 8.2c Change Data Source

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

Figure 8.2d Add Connection

9. Click the Test Connection button.

If the connection to the specified database is successful, then the following message box
will show up:

Figure 8.2e Test Connection


322

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.

11. Click the Next button.

This time the wizard displays an alert message.

12. Just click the Yes button.


13. Now click the Next button to 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:

Figure 8.2f Database Object

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:

Figure 8.2g Database Sources ContactType Object

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.

Your Form should look like the following:

Figure 8.2h Windows Form for vbTextBoxBind3


324

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:

Figure 8.2i TextBox Binding 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

Connecting to our own Database Schema

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.

Install SQL Server Management Studio (A Prerequisite!)


We need to install the SQL Server Management Studio where we will type and
run our SQL script. SQL Server 2012, SQL Server 2008, and SQL Server 2005 are
equipped with Query Editor, a replacement for Query Analyzer used in SQL Server 2000
(and earlier). This component is the primary tool for designing and testing SQL scripts,
queries, Transact-SQL statements, and batches – interactively.

Getting Started with SQL Server and Management Studio

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

Figure 8.3a The SQL Server Management Studio

So, we are now ready to start.

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

Figure 8.3b Selecting Databases at the Object Explorer

After that, you will get the New Database dialog box as you can see at the following
figure below:

Figure 8.3c New Database Dialog box

Step 2. Type Database1 at the Database Name box.

Step 3. Lastly, click the OK button.


328

Now, you will get the following figure below:

Figure 8.3d Database1 database is now created

The Database1 database has now been created.

Creating a Table

We need to create a table, because the data is loaded (stored) into tables that are created
in a database.

Create a Table Syntax:

CREATE TABLE TableName(column_name type, column_name type,…)

Let us now have our actual demonstration on how to create a table. We have here two
examples.

Example 4:

Create a table called Emp1.


The following are its field names (column names) and their respective data types:

Field Names Data Types Character Length

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:

CREATE TABLE Emp1 (EmpNo INT,


Name VARCHAR(15),
Salary SMALLMONEY)

After that, you will get the following figure below:

Figure 8.3e Creating a Database Table

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:

INSERT INTO Emp1 VALUES (1001, 'Juan Cruise', 20500.00);


INSERT INTO Emp1 VALUES (1002, 'Gabriela Silang', 19500.00);
INSERT INTO Emp1 VALUES (1003, 'Diego Silang', 29300.00);
INSERT INTO Emp1 VALUES (1004, 'Pedro Cruise', 16200.00);
INSERT INTO Emp1 VALUES (1006, 'Adres Bonifacio', 28600.00);
330

INSERT INTO Emp1 VALUES (1007, 'Jose Rizal', 27700.00);


INSERT INTO Emp1 VALUES (1008, 'Terio Balutlot', 39200.00);
INSERT INTO Emp1 VALUES (1009, 'Gavino Purisa', 23100.00);
INSERT INTO Emp1 VALUES (1010, 'Lenny Panogalog', 21800.00);
INSERT INTO Emp1 VALUES (1005, 'Lolit Bando',NULL);
INSERT INTO Emp1 VALUES (1011, 'Chona Hermosa',NULL);

which produces the following Results output:

(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

EmpNo Name Salary

Figure 8.3a Data Grid View


331

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.

The DataGridView control displays a task list as shown below:

Figure 8.3b Data Grid View Tasks

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

Figure 8.3c Data Source Configuration Wizard

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

Figure 8.3d Add Connection Wizard

11. Now, let us test our database connection by clicking the Test Connection button.

Figure 8.3e Test Connection testing


334

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:

Figure 8.3g Database Object

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:

Figure 8.3h DataGridView 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

EmpNo Name Salary

Figure 8.3i Data Grid View with Binding Navigator

Solution:

1. At the BindingNavigator Properties window, click the BindingSource property,


and then select the Emp1BindingSource.
2. 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:
337

Figure 8.3g Data Grid View with Binding Navigator output

See??? We’ve got it made!

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:

Figure 8.4a Text Box Binding


338

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:

Figure 8.4b Data Source Configuration Wizard

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:

Figure 8.4c Add Connection Wizard

10. Now, let us test our database connection by clicking the Test Connection button.
340

Figure 8.4d Test Connection testing

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

Figure 8.4e Database Object

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

Figure 8.4f Database Sources Emp1 Object

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.

Your Form should look like the following:

Figure 8.4g Windows Form for vbTextBoxBind4

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

Figure 8.4h TextBox Binding 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.
344

LAB ACTIVITY
TEST 7

1. Design and develop a simple application system that contains a DataGridView


control bound to the AdventureWorks2012_Data database. At the Currency table,
select the CurrencyCode, Name, and ModifiedDate columns to be displayed on
the DataGridView control. Follow the given figure below in designing and
developing the application program:

vbDataGridView9

CurrencyCode Name ModifiedDate

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:

Field Names Data Types Character Length

StudentNumber SMALLINT
StudentName VARCHAR 20
Grade TINYINT

Applying the INSERT INTO…VALUES clauses, input the following values into
Student1 table:

Student Number Student Name Grade

201 Alice Silverstone 90


202 Charliza Therone 68
203 Leely Sobieski 79
204 Sandra Ballock 74
205 Tom Cruz 80
206 Vilma Aunor NULL
207 Nora Santos NULL

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

Student Student Name Grade


Number

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

Student Student Name Grade


Number
348

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 to Peso Conversion


Input the U.S Dollar Amount & corresponding Peso Exchange Rate, then click
the Compute Now! button.

$-Dollar Amount

Text
Boxes Peso Exchange Rate

Total Peso Converted Rate

Compute Now!
Button

Figure 9.1a Web Application Default Page


350

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:

Object Property Setting

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

Text “Compute Now!”

The Webpage that we designed should look like the following:

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):

protected void btnCompute_Click(object sender, EventArgs e)


{
Double nTPCRate;
nTPCRate = Convert.ToDouble(txtDAmount.Text)*Convert.ToDouble(txtPERate.Text);
txtTPCRate.Text = Convert.ToString(nTPCRate);
}
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.

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:

protected void btnCompute_Click(object sender, EventArgs e)


{
Double nTPCRate;
nTPCRate = Convert.ToDouble(txtDAmount.Text)*Convert.ToDouble(txtPERate.Text);
354

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 to Peso Conversion


Input the U.S Dollar Amount & corresponding Peso Exchange Rate, then click
the Compute Now! button.

$-Dollar Amount

Text
Boxes Peso Exchange Rate

Total Peso Converted 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:

Peso to Dollar Conversion Help Guide

How to Operate Instructions:

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 to Peso Conversion


Input the U.S Dollar Amount & corresponding Peso Exchange Rate, then click
the Compute Now! button.

$-Dollar Amount

Text
Boxes Peso Exchange Rate

Total Peso Converted 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:

The following grid shows employees whose salaries are assumed to


be in dollars because they work in the U.S.???:

4. Press the Enter key and double-click the GridView control on the Data tab of the
Toolbox.

The GridView control displays a task list as shown below:

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

Figure 8.3d Add Connection Wizard

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

13. Now, click the Finish button.


14. While the GridView Task list still open, right-click your mouse, then select the
AutoFormat submenu item of the pop-up context menu. Now, select the Simple
scheme. Finally, click the Apply button, then the OK button.

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

Motorcycle Loan Calculator


Enter the Loan Amount & its corresponding Interest Rate on the text boxes
provided, then click the Calculate Now! button. Understood???

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!

Your HTML Help webpage should contain the following information:

Motorcycle Loan Calculator Help Guide


How To Operate Instructions:

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.

The following grid shows the targeted prospective clients:

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.

You might also like