Module 3 Working With Toolbox Controls
Module 3 Working With Toolbox Controls
NET
ONLINE COURSE
Acknowledgments
Hi! Welcome back!. Sir Red Mirabel here!.. but its NOT really my voice.. today session will focus on..
Acknowledgments
Acknowledgments
Note Use the following i nstructions each time you want to create a new project on
your hard disk.
Step 3: Ensure that the Visual Basic Windows category is selected on the left
side of the dialog box, and that Windows Forms Application template
is also selected in the middle of the dialo g box. These selections
indicate that you’ll be building a stand -alone Visual Basic application
that will run under Windows.
Step 4: Remove the default project name (WindowsApplication1) from the
Name text box, and then type Hello WorldProgram. …
Acknowledgments
Note Throughout this module, you should create your own folder , to distinguish your
own work from the practice files include d on the module folder.
The new project is created, and a blank form appears in the Designer . The
two controls you’ll use in this exercise, Button and TextBo x, are visible in
the Toolbox, which appears in the screen shot as a docked window. If your
programming tools are configured differently, take a few moments to
organize them.
Acknowledgments
Step 6: Click the TextBox control on the Common Controls tab of the Toolbox.
Step 7: Draw a text box similar to this:
Text boxes are used to display text on a form or to get user input while a
program is running. How a text box works depends on how you set its
properties and how you reference the text box in the program code. In this
program, a text box object will be used to display the message “Hello,
world!” when you click a button object on the form.
Acknowledgments
As you learned in Module 2, “Writing Your First Program,” buttons are used
to get the most basic input from a user. When a user clicks a button, he or
she is requesting that the program perform a specific action immediately. In
Visual Basic terms, the user is using the button to create an event that needs
to be processed in the program. Typical buttons in a program are the Display
button, which a user clicks to accept a list of options and to indicate that he
or she is ready to proceed; the Cancel button, w hich a user clicks to discard
a list of options; and the Quit button, which a user clicks to exit the program.
In each case, you should use these buttons in the standard way so that they
work as expected when the user clicks them. A button’s characteristic s (like
those of all objects) can be modified with property settings and references
to the object in program code.
Step 10: Set the following property for the button object by using the
Properties window:
Acknowledgments
For more information about setting properties and reading them in tables,
see the section entitled “The Properties Window”. Double -click the Display
button, and type the following program statement between the Private Sub
Button1_Click and End Sub statemen ts in the Code Editor:
Note: As you type statements, Visual Studio displays a list box containing all valid items
that match your text. After you type the TextBox1 object name and a period, Visual
Studio displays a list box containing all the valid properties and methods for tex t box
objects, to jog your memory if you’ve forgotten the complete list. This list box is called
Microsoft IntelliSense and can be very helpful when you are writing code. If you click
an item in the list box, you will typically get a tooltip that provides a short description
of the selected item. You can add the property from the list to your code by double -
clicking it or by using the arrow keys to select it and then pressing TAB. You can also
continue typing to enter the property yourself.
Step 1: Click the Start Debugging button on the Standard toolbar. The Hello
program compiles and, after a few seconds, runs in the Visual Studio
IDE.
Note: I change the Textbox1 text property to “Hello, World”
Acknowledgments
Step 2: Click Display button. The program displays the greeting “Hello,
World!” in the text box, as shown here:
When you clicked the Display button, the program code changed the Text
property of the empty TextBox1 text box to “Hello, worl d!” and displayed
this text in the box. If you didn’t get this result, repeat the steps in the
previous section, and build the program again. You might have set a
property incorrectly or made a typing mistake in the program code. (Syntax
errors appear with a jagged underline in the Code Editor .)
Step 3: Click the Close button in the upper -right corner of the Hello World
program window to stop the program.
Acknowledgments
Note To stop a program running in Visual Studio, you can also click the Stop
Debugging button on the Standard toolbar to close the program.
Step 4: Click the Save All button on the Standard toolbar to save your new
project to disk. Visual Studio now prompts you for a name and a
location for the project.
Step 5: Click the Browse button. The Project Location dialog box opens. You
use this dialog box to specify the location of your project and to
create new folders for your projects if necessary. Although you can
save your projects in any location .
Step 6: Click the Select Folder or Open button to open the folder you
specified.
Step 7: Clear the check ma rk from the Create Directory for Solution check box
if it is selected. Because this solution contains only one project , you
don’t need to create a separate root folder to hold the solution files
for the project. (However, you can create an extra folder if you want.)
Step 8: Click Save to save the project and its files.
Acknowledgments
The date/time picker object by default displays the current date, but you
can adjust the displayed date by changing the object’s Value property.
Acknowledgments
Displaying the date is a handy design guide —it lets you size the date/time
picker object appropriately when you ’re creating it.
Step 6: Click the Button control in the Toolbox, and then add a button
object below the date/time picker. You’ll use this button to display
your birth date and to verify that the date/time picker works
correctly.
Step 7: In the Properties window, chang e the Text property of the button
object to Show Birthday Program. Now you’ll add a few lines of
program code to a procedure associated with the button object.
This is an event procedure because it runs when an event, such as
a mouse click, occurs, or fires , in the object.
Step 8: Double-click the button object on the form to display its default
event procedure, and then type the following program statements
between the Private Sub and End Sub statements in the
Button1_Click event procedure:
These program statements display two message boxes (small dialog boxes)
with information from the date/time picker object. The first line uses the
Text property of the date/time picker to display the birth date information
Acknowledgments
that you select when using the object at run time. The MsgBox function
displays the string value “Your birth date was” in addition to the textual
value held in the date/time picker’s Text property. These two pieces of
information are joined together by the string concatenation operator (&).
You’ll learn more about the MsgBox function and the string concatenation
operator in Module 5, “Visual Basic Variables and Formulas, and the .NET
Framework.”
The second and third lines collectively form one program statement and
have been broken by the line continuation character (_) because the
statement was a bit too long to print in this module.
Program lines can be more than 65,000 characters long in the Visual Studio
Code Editor, but it’s usually easiest to work with lines of 80 or fewer
characters. You can divide long program statements among multiple lines
by using a space and a line continuation character (_) at t he end of each
line in the statement except for the last line. (You cannot use a line
continuation character to break a string that’s in quotation marks,
however.) I use the line continuation character in this exercise to break the
second line of code into two parts.
Note Starting in Visual Basic 2010, the line continuation character (_) is optional.
There are a few instances where the line continuation character is needed, but they
are rare. In this course, I still use line continuation characters to make it clear where
there are long lines, but you don’t have to include them.
to a list box. Methods differ from properties, which contain a value, and
event procedures, which execute wh en a user manipulates an object.
Methods can also be shared among objects, so when you learn how to use
a particular method, you’ll often be able to apply it to several
circumstances. We’ll discuss several important methods as you work
through this module.
After you enter the code for the Button1_Click event procedure, the Code
Editor looks similar to this:
Step 9: Click the Save All button to save your changes to disk, and specify
the folder location.
Step 1: Click the Start Debugging button on the Standard toolbar. The
Birthday program starts to run in the IDE. The current date is
displayed in the date/time picker.
Step 2: Click the arrow in the date/time picker to display the object in
Calendar view. Your form looks like the following screen shot, but
with a different date.
Acknowledgments
Step 3: Click the Left scroll arrow to look at previous months on the
calendar
Notice that the text box portion of the object also changes as you scroll
the date. The “today” value at the bottom of the calendar doesn’t change,
however. Although you can scroll all the way back to your exact birthday,
you might not have the patience to scroll month by month. To move to
your birth year faster, select the year value in the date/time picker text
box and enter a new year.
Step 4: Select the four-digit year in the date/time picker text box. When
you select the date, the date/time picker closes.
Step 5: Type your birth year in place of the year that’s currently selected,
and then click the arrow again. The calendar reappears in the year
of your birth.
Step 6: Click the scroll arrow again to locate the month in which you were
born, and then click the exact day on which you were born. If you
didn’t know the day of the week on which you were born, now you
can find out! When you select the final date, the date/time picker
closes, and your birth date is displayed in the text box. You can
click the button object to see how this information is made
available to other objects on your form.
Step 7: Click the Show My Birthday button. Visual Basic executes your
program code and displays a message box containing the day and
Acknowledgments
date of your birth. Notice how the two dates shown in the tw o
boxes match:
Note To configure the date/time picker object to display times instead of dates, set
the object’s Format property to Time.
Step 9: Click OK to close the message box, and then click the Close button
on the form. You’re finished using the DateTimePicker control for
now.
Acknowledgments
As a simple experiment, try using the C heckBox control now to see how
user input is processed on a form and in program code.
Step 1: On the File menu, click Close Project to close the Birthday project.
Step 2: On the File menu, click New Project. The New Project dialog box
opens.
Step 3: Create a new Visual Basic Windows Forms Application project
named MyCheckBox. The new project is created, and a bl ank form
appears in the Designer.
Step 4: Click the CheckBox control in the Toolbox.
Step 5: Draw two check box objects on the form, one above the other.
Check boxes appear as objects on your form just as other objects
do. You’ll have to click the CheckBox control in th e Toolbox a
second time for the second check box.
Step 6: Using the PictureBox control, draw two square picture box objects
beneath the two check boxes.
Step 7: Select the first PictureBox control named PictureBox1.
Step 8: Click the Image property in the Properties window, and then click
the ellipsis button in the second column. The Select Resource
dialog box appears.
Step 9: Click the Local Resource radio button, and then click the Import
button.
Step 10: In the Open dialog box, navigate to the module file.
Step 11: Select Laptop.png, and then click Open.
Step 12: Click OK in the Select Resource dialog box. The Desktop Computer
appears in the PictureBox1.
Acknowledgments
In these steps, you’ll use the check boxes to display and hide images of a
Laptop and a Desktop Computer. The Text property of the check box object
determines the contents of the check box label in the user interface. With
the Checked property, you can set a default value for the check box.
Setting Checked to True places a check mark in the box, and setting
Checked to False (the default setting) removes the check mark.
I use the SizeMode properties in the picture boxes to size the images so
that they stretch to fit in the picture box. Your form looks something like
this:
Acknowledgments
Step 15: Double-click the first check box object to open the
CheckBox1_CheckedChanged event procedure in the Code Editor,
and then enter the following program code:
If CheckBox1.CheckState = 1 Then .
PictureBox1.Image = System.Drawing.Image.FromFile _ .
("E: \Module 3\Laptop.png").
PictureBox1.Visible = True .
Else.
PictureBox1.Visible = False .
End If.
Step 16: Click the View Designer button in Solution Explorer to display the
form again, double-click the second check box, and then add the
following code to the CheckBox2_CheckedChanged event
procedure:
If CheckBox2.CheckState = 1 Then .
PictureBox2.Image = System.Drawing.Image.FromFile _ .
("E \Module 3\Desktop Computer.png").
PictureBox2.Visible = True .
Acknowledgments
Else.
PictureBox2.Visible = False .
End If.
This event procedure is almost identical to the one that you just entered;
only the names of the image (Desktop Computer), the check box object
(CheckBox2), and the picture box object (PictureBox2) are different.
Step 17: Click the Save All button on the Standard toolbar to save your
changes, specifying your folder as the location.
Acknowledgments
The RadioButton control is another tool that you can use to receive input
in a program, and it is also located on the Common Controls tab of the
Toolbox. Radio buttons get their name from the old push -button car radios
of the 1950s and 1960s, when people pushed or “selec ted” one button on
the car radio and the rest of the buttons clunked back to the unselected
position. Only one button could be selected at a time, because (it was
thought) the driver should listen to only one thing at a time. In Visual
Studio, you can also offer mutually exclusive options for a user on a form,
Acknowledgments
allowing them to pick one (and only one) option from a group. The
procedure is to use the GroupBox control to create a frame on the form,
and then to use the RadioButton control to place the desired n umber of
radio buttons in the frame. (Because the GroupBox control is not used that
often, it is located on the Containers tab of the Toolbox.) Note also that
your form can have more than one group of radio buttons, each operating
independently of one another. For each group that you want to construct,
simply create a group box object first and then add radio buttons one by
one to the group box. In the following exercise, you’ll create a simple
program that uses GroupBox, RadioButton, and PictureBox control s to
present three graphical ordering options to a user. Like the CheckBox
control, the RadioButton control is programmed by using event procedures
and program code, with which you’ll also experiment. Give it a try now.
Step 6: Return to the Toolbox, scroll up to the Common Controls tab, and
click the RadioButton control. .
Acknowledgments
Step 7: Create three radio button objects in the group box. It is handy to
double-click the RadioButton control to create radio buttons. Notice
that each radio button gets its own number, which you can use to set
properties. .
Step 8: Using the PictureBox control, create one square picture box object
beneath the group box on the form.
Step 9: Set the following properties for the group box, radio button, and
picture box objects:
Acknowledgments
The initial radio button state is controlled by the Checked property. Notice
that the Desktop Computer radio button now appears selected in the IDE.
Now you’ll add some program code to make the radio buttons operate
while the program runs.
Step 10: Double-click the RadioButton1 object on the form to open the Code
Editor. The CheckedChanged event procedure for the RadioButton1
object appears in the Code Editor. This procedure is run each time the
user clicks the first radio button. Because you want to cha nge the
picture box image when this happens, you’ll add a line of program
code to accomplish that.
Step 11: Type the following program code: .
PictureBox1.Image = System.Drawing.Image.FromFile _.
(“E:\Subject File\VB.NET File\VB.NET Modular for Online
.Learning\Module 3\Desktop Computer.png”).
This program statement uses the FromFile method to load the picture of
the Desktop Computer from the hard disk into the picture box object.
You’ll use a similar statement for the second and third radio buttons.
Step 12: Switch back to the Designer, double -click the RadioButton2 object on
the form, and type the following program code:
Acknowledgments
Step 13: Switch back to the Designer, double -click the RadioButton3 object on
the form, and type the following program code:
Note: if you don’t know the location address of the image, right click on the image
select properties then copy by selecting the address then paste on the code editor
Step 14: Click the Save All button on the toolbar to save your changes,
specifying your folder as the location.
Step 1: Click the Start Debugging button on the Standard toolbar. Visual Basic
runs the program in the IDE. The desktop PC image appears in a
picture box on the form, and the first radio button is selected.
Acknowledgments
Step 2: Click the second radio button (Desktop Computer). Visual Basic
displays the image, as shown here:
Step 3: Click the third radio button (LED Projector). The LED Projector image
appears.
Step 4: Click the first radio button (Desktop Computer). The desktop
computer image appears again. It appears that each of the three
CheckedChanged event procedures is loading the images just fine.
Nice work.
Step 5: Click the Close button on the form to end the program.
Perfect. You’re finished working with radio buttons and group boxe s for
now. But can you imagine how you might use them on your own in a
program?..
As you well know from your own use of Windows, one of the key
mechanisms for getting input from the user —in addition to check boxes
and radio buttons—are basic list boxes, those rectangular containers used
Acknowledgments
in dialog boxes or on forms that present a list of items and encourage the
user to select one of them. List boxes are created in Visual Studio by using
the ListBox control, and they are v aluable because they can expand to
include many items while the program is running. In addition, scroll bars
can appear in list boxes if the number of items is larger than will fit in the
box as you designed it on the form.
Unlike radio buttons, a list bo x doesn’t require that the user be presented
with a default selection. Another difference, from a programmatic
standpoint, is that items in a list box can be rearranged while the program
is running by adding items to a list, removing items, or sorting item s. (You
can also add a collection of items to a list box at design time by setting the
Items property under the Data category with the Properties window.)
However, if you prefer to see a list with check marks next to some of or all
the items, you should use the CheckedListBox control in the Toolbox
instead of ListBox. As a third option, you can use the handy ComboBox
control to create a list box on a form that collapses to the size of a text
box when not in use.
Step 1: On the File menu, click Close Project to close the Radio Button
project.
Step 2: On the File menu, click New Project, and create a new Windows
Forms Application project named ListBox Program. The new project
is created, and a blank form appears in the Designer.
Step 3: In the Toolbox, click the ListBox control in the Toolbox, and create
a medium-sized list box object on the top half of the form. The list
Acknowledgments
Step 5: Set the following property for the picture box object:
Object. Property. Setting.
PictureBox1 . SizeMode . StretchImage.
Now you’ll add the necessary program code to fill the list box object with
valid selections, and to pick from the selections while the program is
running.
Step 6: Double-click the ListBox1 object on the form to open the Code
Editor.
Acknowledgments
'The list box item selected (0 -2) is held in the SelectedIndex property .
Select Case ListBox1.SelectedIndex .
Case 0.
PictureBox1.Image = System.Drawing.Image.FromFile _ .
("C:\Module 3\GarageBand.png").
Case 1.
PictureBox1.Image = System.Drawin g.Image.FromFile _ .
("C:\Module 3\Headphones.png").
Case 2.
PictureBox1.Image = System.Drawing.Image.FromFile _ .
("C:\Module 3\Ipod.png").
End Select.
Note: Check the location address of the image in your unit used …
The code maybe has a different location in your computer used..
The entire block of code that you typed is actually called a Select Case
decision structure, which explains to the compiler how to process the
user’s selection in the list box. The important keyword that begins this
decision structure is ListBox1 .SelectedIndex, which is read as “the
SelectedIndex property of the list box object named ListBox1.” If item 0 is
selected, the Case 0 section of the structure, which uses the FromFile
Acknowledgments
method to load a picture of an external hard disk into the picture box
object, will be executed. If item 1 is selected, the Case 1 section will be
executed, and a printer will appear in the picture box object. If item 2 is
selected, the Case 2 section will be executed, and a satellite dish will
appear. Don’t worry too much if this is a little strange —you’ll get a more
fulsome introduction to decision structures in Module 6.
Now you need to enter some program code to add text to the list box
object. To do this, we’ll do something new —we’ll put some program
statements in the Form1_Load event procedure, which is run when the
program first starts.
Step 8: Switch back to the Designer and double -click the form (Form1) to
display the Form1_Load event procedure in the Code Editor. The
Form1_Load event procedu re appears. This program code is
executed each time the List Box program is loaded into memory.
Programmers put program statements in this special procedure
when they want them executed every time a form loads. (Your
program can display more than one form, or none at all, but the
default behavior is that Visual Basic loads and runs the
Form1_Load event procedure each time the user runs the
program.) Often, as in the List Box program, these statements
define an aspect of the user interface that couldn’t be c reated
easily by using the controls in the Toolbox or the Properties
window.
Step 9: Type the following program code:
The first line is simply a comment offering a reminder about what the code
accomplishes. The next three lines add items to the list box (ListBox1) in
Acknowledgments
the program. The words in quotes will appear in the list box when it
appears on the form. The important ke yword in these statements is Add, a
handy method that adds items to list boxes or other items. Remember that
in the ListBox1_SelectedIndexChanged event procedure, these items will be
identified as 0, 1, and 2.
Step 10: Click the Save All button on th e toolbar to save your changes,
specifying your folder as the location.
Ok lets do this..
Run the List Box Program...
Step 1: Click the Start Debugging button on the Standard toolbar. Visual
Basic runs the program in the IDE. The three items appear in the
list box, but because no item is currently selected, nothing appears
yet in the picture box object.
Step 2: Click the first item in the list box (GarageBand).
Acknowledgments
Step 3: Click the second item in the list box (Headphones). The
Headphones image appears
Step 4: Click the third item in the list box ( Ipod). The Ipod display on the
picturebox.
Acknowledgments
All of the list box code seems to be working correctly, although you should
always continue to test these things (that is, check the various user input
options) to make sure that nothing unexpected happens . As you’ll learn
later in the course, you always want to test your programs thoroughly,
especially the UI elements that users have access to
Step 5: Click the Close button on the form to end the program. You’re
finished working with list boxes for now. If you li ke, you can
continue to experiment with the ComboBox and CheckedListBox
controls on your own—they operate similar to the tools you have
been using in the last few exercises.
Acknowledgments
let’s do a quick terminology review. So far in this module, I’ve used several
different terms to describe items in a Visual Basic program. Do you know
what most these items are yet? It’s worth listing several of them now to
clear up any confusion.
Toolbox and use them to draw objects with the mouse on a form. You
use most controls to create UI elements such as buttons, picture
boxes, and list boxes.
Acknowledgments
Button1.Text = "Hello".
could be used in the program code to set the Text property of the Button1
object to “Hello”.
ListBox1.Items.Add("Check") .
uses the Add method to put the word Check in the ListBox1 list box.
Methods and properties are often identified by their position in a
collection or class library, so don’t be surprised if you see long references
Acknowledgments
Step 1: On the File menu, click Close Project to close the List Box project.
Step 2: On the File menu, click New P roject.
Acknowledgments
Step 5: Set the Text property of the link label object to the Uniform
Resource Locator (URL) for the Mi crosoft Press home page:
Step 6: Click the form in the IDE to select it. (Click the form itself, not the
link label object.)
This is the technique that you use to view the properties of the default
form, Form1, in the Properties window. Like other objects in your
project, the form also h as properties that you can set.
Step 7: Set the Text property of the form object to Web Link Test.
The Text property for a form specifies what appears on the form’s title
bar at design time and when the program runs.
Acknowledgments
Step 8: Double-click the link label object, and then type the following
program code in the LinkLabel1_LinkClicked event procedure:
I’ve included more comments in the program code to give you some
practice entering them. As soon as you enter the singl e quote character (‘),
Visual Studio changes the color of the line to green.
The two program statements that aren’t comments control how the link
works. Setting the LinkVisited property to True gives the link that dimmer
color of purple, which indicates in many browsers that the Hypertext
Markup Language (HTML) document associated with the link has already
been viewed. Although setting this property isn’t necessary to display a
Web page, it’s a good programming practice to provide the user with
information in a way that’s consistent with other applications.
Acknowledgments
The second program statement (which I have broken into two lines) runs
the default Web browser (such as Internet Explorer) if the browser isn’t
already running. (If the browser is running, the URL jus t loads
immediately.) The Start method in the Process class performs the
important work, by starting a process or executable program session in
memory for the browser. The Process class, which manages many other
aspects of program execution, is a member of the System.Diagnostics
namespace. By including an Internet address or a URL with the Start
method, I’m letting Visual Basic know that I want to view a Web site, and
Visual Basic is clever enough to know that the default system browser is
the tool that would best display that URL, even though I didn’t identify the
browser by name.
System.Diagnostics.Process.Start("IExplore.exe",
"http://www.plpasig.edu.ph/") .
Step 1: Click the Start Debugging button on the Standard toolbar to run
the WebLink program. The form opens and runs, showing its Web
site link and handsome title bar text.
Step 2: Click the link to open the Web site at http://www.plpasig.edu.ph/.
Recall that it’s only a happy coincidence that the link label Text property
contains the same URL as the site you named in the program code. (It is
not necessary that these two items match.) You can enter any text you
like in the link label. You can also use the Image property for a link label
Acknowledgments
Step 3: Display the form again. (Click the Web Link Test form icon on the
Windows taskbar if the form isn’t visible.)
Acknowledgments
Notice that the link now appears in a dimmed style. Like a standard Web
link, your link label communicates that it’s been used (but is still active)
by the color and intensity that it appears in.
Step 4: Click the Close button on the form to quit the test utility.
Acknowledgments
To Do This
Create a text box Click the TextBox control, and draw the box.
Create a button Click the Button control, and draw the button.
Change a property at Change the value of the property by using program
run time code. For example:
Label1.Text = "Hello!"
Create a radio button Use the RadioButton control. To create multiple radio
buttons, place more
than one radio button object inside a box that you
create by using the
GroupBox control.
Create a check box Click the CheckBox control, and draw a check box.
Create a list box Click the ListBox control, and draw a list box.
Create a drop-down Click the ComboBox control, and draw a drop-down
list box list box.
Add items to a list box Include statements with the Add method in the
procedure of your program. Form1_Load event
For example:
ListBox1.Items.Add("Printer")
Use a comment in code Type a single quotation mark (‘) in the Code Editor,
and then type
a descriptive comment that will be ignored by the
compiler. For example:
' Use the Process.Start method to start IE
Create a link to the Web page by using LinkLabel
Display a Web page the control, and then open the link in a browser by using
the Process.Start method in
program code.
Acknowledgments