Sabtu, 20 Juni 2009

MULAI BELAJAR DARI SINI VOLUME 1# - 4# ( Start here)

Learn Visual Basic .NET

© fr-one



This is a draft version of the first four chapters of KIDware’s new course, Learn Visual Basic .NET. There will be errors and omissions. It is offered to help you see what Visual Basic .NET is about. The completed version of the course will be available on the KIDware website after the commercial release of Visual Basic .NET (due in mid-juni 2009).

We welcome your comments on this draft version. Just visit our website at:

http://fey888.blogger.com/
http://fey888.blog.com/
and click the E-mail button on any page.



*

Course Description

Learn Visual Basic .NET is a 10-week, self-paced overview of the Visual Basic .NET programming environment. Upon completion of the course, you will:

1. Understand the benefits of using Microsoft Visual Basic .NET as a Windows appication development tool.
2. Understand the Visual Basic .NET event-driven programming concepts, terminology, and available controls.
3. Learn the fundamentals of designing, implementing, and distributing a wide variety of Visual Basic .NET Windows applications.

Learn Visual Basic .NET is presented using a combination of course notes (written in Microsoft Word format) and over 100 Visual Basic .NET examples and applications.



Course Prerequisites

To grasp the concepts presented in Learn Visual Basic .NET, you should possess a working knowledge of the Windows operating system. You should know how to use Windows Explorer to locate, copy, move and delete files. You should be familiar with the simple tasks of using menus, toolbars, resizing windows, and moving windows around.

You should have had some exposure to programming concepts (perhaps with Visual Basic). If you have never programmed a computer before, you’ll have to put in a little more effort - perhaps, find a book in your local library on programming using Visual Basic, QBasic or some other dialect of the BASIC computer language. A companion course (available in mid-2009), Beginning Visual Basic .NET, will be aimed at the person who has never programmed. You might consider waiting for its release.

You will also need the ability to view and print documents saved in Microsoft Word format. This can be accomplished in one of two ways. The first, and easiest, is that you already have Microsoft Word on your computer. The second way, and a bit more difficult, is that you can download the Microsoft Word Viewer. This is a free Microsoft product that allows viewing Word documents - it is available for download at fr-one website for Learn Visual Basic .NET:

http://fey888.blogger.com/
http://fey888.blog.com/

Finally, and most obvious, you need to have Microsoft Visual Basic .NET. This is a separate product that must be purchased - check out on-line software stores like Amazon.Com. You can use either the stand-alone Visual Basic .NET product (the cheaper alternative) or the Visual Basic .NET that is part of the Visual Studio .NET suite.
Using Learn Visual Basic .NET

The course notes and code for Learn Visual Basic .NET are included in one or more ZIP file(s). Use your favorite ‘unzipping’ application to write all files to your computer. (If you’ve received the course on CD-ROM, the files are not zipped and no unzipping is needed.) The course is included in the folder entitled LearnVBN. This folder contains two other folders: VBN Notes and VBN Code.

The VB Notes folder includes all the notes needed for the class. Each file in this folder has a DOC extension and is in Word format. The files are:

Start Here.doc This file in Word format
Contents.doc Course Table of Contents
Class 1.doc Class 1. Introduction to the Visual Basic .NET Environment
Class 2.doc Class 2. The Visual Basic .NET Language
Class 3.doc Class 3. Exploring the Visual Basic .NET Toolbox
Class 4.doc Class 4. More Exploration of the Visual Basic .NET Toolbox
Class 5.doc* Class 5. Application Design and Distribution
Class 6.doc* Class 6. Sequential Files, Error Handling, and Debugging
Class 7.doc* Class 7. Graphics Techniques with Visual Basic .NET
Class 8.doc* Class 8. More Graphics Methods and the Windows API
Class 9.doc* Class 9. Other Visual Basic .NET Topics
Class 10.doc* Class 10. Visual Basic .NET Internet Applications
Problems.doc* Practice Problems Solutions
Exercises.doc* Exercise Solutions
Appendix.doc* Visual Basic .NET for Visual Basic Programmers

Documents marked with an asterisk (*) are not included with the trial version. To obtain these files, you must purchase the complete course. Purchase information can be found at the fr-one website:

http://fey888.blogger.com/
http://fey888.blog.com/


The VBN Code folder includes all the Visual Basic .NET applications developed during the course. The applications are further divided into Class folders. Each class folder contains the Visual Basic .NET project folders. As an example, to open the project named Example 1-1 discussed in Class 1, you would go to this directory:

C:\LearnVBN\VBN Code\Class 1\Example 1-1\

Only the code for the examples in Classes 1 through 4 are included with the trial version of the course. All code is provided with purchase of the complete course.

How To Take the Course

Learn Visual Basic .NET is a self-paced course. The suggested approach is to do one class a week for ten weeks. Each week’s class should require about 4 to 8 hours of your time to grasp the concepts completely. Prior to doing a particular week’s work, open the class notes file for that week and print it out. Then, work through the notes at your own pace. Try to do each example as they are encountered in the notes. If you need any help, all solved examples are included in the VBN Code folder.

After completing each week’s notes, practice problems and homework exercise (sometimes, two) is given; covering many of the topics taught that in that class. Like the examples, try to work through the practice problems and homework exercise, or some variation thereof, on your own. Refer to the completed exercise in the VBN Code folder, if necessary. This is where you will learn to be a Visual Basic .NET programmer. You only learn how to build applications and write code by doing lots of it. The problems and exercises give you that opportunity. And, you learn coding by seeing lots of code. Programmers learn to program by seeing how other people do things. Feel free to ‘borrow’ code from the examples that you can adapt to your needs. I think you see my philosophy here. I don’t think you can teach programming. I do, however, think you can teach people how to become programmers. This course includes numerous examples, problems, and exercises to help you toward that goal. We show you how to do lots of different things in the code examples. You will learn from the examples!



What If You Have Questions?

It is recognized there may be times when you need clarification on some point about the notes, examples, or Visual Basic .NET. We will gladly help. The preferred method of relaying your questions to us is via E-Mail. The E-Mail address is:

frone.mellisa@gmail.com

Please include a clearly defined subject for all questions to get past our anti-spamming filters. All questions should be sent to the attention of Lou.



Who Produces Learn Visual Basic .NET?

This course has been developed and written by Lou Tylee, a principal partner in FR-ONE, a producer of quality children’s educational programs since 1982. The course notes have evolved based on Lou’s experience in writing children’s software and in teaching a similar course at the university level for over six years.

Lou has been programming computers since 1969 when he took his first Fortran course in college (yes, Lou is getting old!). He has written software to control suspensions for high speed ground vehicles, monitor nuclear power plants, lower noise levels in commercial jetliners, compute takeoff speeds for jetliners, locate and identify air and ground traffic and to let kids count bunnies, learn how to spell and do math problems. His wide breadth of practical experience is demonstrated in Learn Visual Basic .NET. He has been praised for his clear, reassuring teaching style. Thousands of people have learned to program using similar notes written by Lou.

During all his programming and writing efforts, Lou is accompanied by Clara, the fr-one dog. She is always under Lou’s desk directing his every keystroke. She is a primary contributor to this product.



Trial Version of Learn Visual Basic .NET

This trial version of Learn Visual Basic .NET gives you the first four chapters of the course for free. This allows you to evaluate the course and see if it meets your needs. The complete course (just $24.95) includes 10 chapters, an appendix and code for all examples, problems, and exercises. See the Table of Contents for a description of what topics the entire course covers. Purchase information can be found at our website:

http://fey888.blogger.com/
http://fey888.blog.com/

At the website, you can purchase the course and download it to your computer in minutes. Or, if preferred, you can place an on-line order to receive the course on CD-ROM, floppy disks or via E-mailed files. And, lastly, we accept mail, FAX and phone orders.



Contacting Fr-one

By Mail:
JL teuku umar no 85/60 bandung-indonesia
BANDUNG (022)91440444

By Phone:
CIANJUR (0263) 518459
BANDUNG (022)91440444
By FAX:
CIANJUR (0263) 518459

By E-Mail:
ferryrusmawan@yahoo.co.id
Our Web Site:
http://fey888.blogger.com/
http://fey888.blog.com/

Belajar vb.net volume 4#

Learn Visual Basic .NET


4. More Exploration of the Visual Basic .NET Toolbox


Review and Preview

• In this class, we continue looking at tools in the Visual Basic .NET toolbox. We will look at some input tools, scroll bars, picture boxes and controls that allow direct interaction with drives, directories, and files. In the examples, you should start trying to do as much of the building and programming of the applications you can with minimal reference to the notes. This will help you build your programming skills.



Control Z Order

• As you build Windows applications using Visual Basic .NET, you will notice that whenever controls occupy the same space on a form, one control is on top of the other. The relative location of controls on a form is established by what is called the Z Order.

• As each control is placed on the form, it is assigned a Z Order value. Controls placed last will lie over controls placed earlier. While designing an application, the Z Order can be changed by right-clicking the control of interest. A menu will appear. Selecting BringToFront will bring that control ‘in front’ of all other controls. Conversely, selecting SendToBack will send that control ‘behind’ all other controls.

• A control’s Z Order can also be changed in code. Why would you want to do this? Perhaps, you have two controls on the form in exactly the same location, one that should be accessible for one particular operation and the other accessible for another operation. To place one control in front of the other, you need to change the Z Order. The BringToFront and SendToBack methods accomplish this task. For a control named ControlExample, the code to accomplish this is:

ControlName.BringToFront()

Or

ControlName.SendToBack()

• Now, let’s continue our look at the Visual Basic .NET toolbox, looking first at more controls that allow ‘point and click’ selections.

NumericUpDown Control

In Toolbox:



On Form (Default Properties):



• The NumericUpDown Control is used to obtain a numeric input. It looks like a text box control with two small arrows. Clicking the arrows changes the displayed value, which ranges from a specified minimum to a specified maximum. The user can even type in a value, if desired. Such controls are useful for supplying a date in a month or are used as volume controls in some Windows multimedia applications.

• NumericUpDown Properties:

Name Gets or sets the name of the numeric updown (three letter prefix for numeric updown name is nud).
BackColor Get or sets the numeric updown background color.
BorderStyle Gets or sets the border style for the updown control.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
Increment Gets or sets the value to increment or decrement the updown control when the up or down buttons are clicked.
Maximum Gets or sets the maximum value for the updown control.
Minimum Gets or sets the minimum value for the updown control.
ReadOnly Gets or sets a value indicating whether the text may be changed by the use of the up or down buttons only.
TextAlign Gets or sets the alignment of text in the numeric updown.
Value Gets or sets the value assigned to the updown control.

• NumericUpDown Methods:

DownButton Decrements the value of the updown control.
UpButton Increments the value of the updown control.


• NumericUpDown Events:

LostFocus Occurs when the updown control loses focus.
ValueChanged Occurs when the Value property has been changed in some way.

• The Value property can be changed by clicking either of the arrows or, optionally by typing a value. If using the arrows, the value will always lie between Minimum and Maximum. If the user can type in a value, you have no control over what value is typed. However, once the control loses focus, the typed value will be compared to Minimum and Maximum and any adjustments made. Hence, if you allow typed values, only check the Value property in the LostFocus event.

• Typical use of NumericUpDown control:

 Set the Name, Minimum and Maximum properties. Initialize Value property. Decide on value for ReadOnly.
 Monitor ValueChanged (or LostFocus) event for changes in Value.
 You may also want to change the Font, Backcolor and Forecolor properties.


DomainUpDown Control

In Toolbox:



On Form (Default Properties):



• The DomainUpDown control is similar in appearance to the NumericUpDown control. The difference is that the DomainUpDown control displays a list of string items (rather than numbers) as potential choices. It is much like a single line ComboBox control with no dropdown list. You will see it shares many of the properties of the ComboBox. The DomainUpDown control is usually reserved for relatively small lists. Examples of use are selecting a state in the United States for an address book, selecting a month for a calendar input or selecting a name from a short list.

• DomainUpDown Properties:

Name Gets or sets the name of the domain updown (three letter prefix for domain updown name is dud).
BackColor Get or sets the domain updown background color.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the domain updown.
ReadOnly Gets or sets a value indicating whether the text may be changed by the use of the up or down buttons only.
SelectedIndex Gets or sets the zero-based index of the currently selected item.
SelectedItem Gets or sets the selected item based on the index value of the selected item.
Sorted Gets or sets a value indicating whether items are sorted alphabetically.
Text Gets or sets the text displayed in the updown control.
TextAlign Gets or sets the alignment of the text in the updown control.
Wrap Gets or sets a value indicating whether the list of items continues to the first or last item if the user continues past the end of the list.


• DomainUpDown Methods:

DownButton Displays the next item in the control.
UpButton Displays the previous item in the control.

• DomainUpDown Events:

KeyPress Occurs when a key is pressed while the domain updown has focus.
SelectedItemChanged Occurs when the SelectedItem property has changed.
TextChanged Occurs when the Text property has changed.

• Like the ListBox and ComboBox controls, the Items object provides details on what is in the control and how to add/delete information from the control. The first item in a updown control named dudExample is:

dudExample.Items.Item(0)

The last item in the list is:

dudExample.Items.Item(dudExample.Items.Count - 1)

• To add an item to the control, use the Add method, to delete an item, use the Remove method and to clear it use the Clear method. For our example:

Add Item: dudExample.Items.Add(StringToAdd)
Delete Item: dudExample.Items.Remove(IndexOfItem)
Clear list box: dudExample.Items.Clear

• Typical use of DomainUpDown control:

 Set Name property, decide whether ReadOnly should be True and populate Items object (usually in Form Load procedure).
 Monitor SelectedItemChanged (or TextChanged) event for individual selections.
 Read Text property to identify choice.
 As usual, you may also want to change the Font, Backcolor and Forecolor properties.


Example 4-1

Date Input Device

1. Start a new project. In this project, we’ll use a NumericUpDown control, in conjunction with a DomainUpDown control, to select a month and day of the year.

2. Place a NumericUpDown control, a DomainUpDown control and a Label control on the form. The form should resemble this:



3. Set these properties:

Form1:
Name frmDate
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Date Input

DomainUpDown1:
Name dudMonth
BackColor White
Font Size 14
ReadOnly True
Wrap True

NumericUpDown1:
Name nudDay
BackColor White
Font Size 14
Maximum 31
Minimum 1
ReadOnly True
TextAlign Center
Value 1

Label1:
Name lblDate
Font Size 12
Text [Blank]
TextAlign MiddleCenter

When done, the form should look like this:



4. Use this code in the Form Load procedure to populate the control with the month names:

Private Sub frmDate_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dudMonth.Items.Add("January")
dudMonth.Items.Add("February")
dudMonth.Items.Add("March")
dudMonth.Items.Add("April")
dudMonth.Items.Add("May")
dudMonth.Items.Add("June")
dudMonth.Items.Add("July")
dudMonth.Items.Add("August")
dudMonth.Items.Add("September")
dudMonth.Items.Add("October")
dudMonth.Items.Add("November")
dudMonth.Items.Add("December")
dudMonth.SelectedIndex = 0
lblDate.Text = dudMonth.Text + Str(nudDay.Value)
End Sub


5. Use this code in the dudMonth SelectedItemChanged event to update date if month changes:

Private Sub dudMonth_SelectedItemChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dudMonth.SelectedItemChanged
lblDate.Text = dudMonth.Text + Str(nudDay.Value)
End Sub

6. Use this code in the nudDay ValueChanged event to update date if day changes:

Private Sub nudDay_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles nudDay.ValueChanged
lblDate.Text = dudMonth.Text + Str(nudDay.Value)
End Sub

7. Run the program. Scroll through the month names. Notice how the Wrap property allows the list to return to January after December. Scroll through the day values, noticing how the displayed date changes. Save the project (saved in Example 4-1 folder in the LearnVBN\VBN Code\Class 4 folder).

Do you notice that you could enter April 31 as a date, even though it’s not a legal value? Can you think of how to modify this example to make sure you don’t exceed the number of days in any particular month? And, how would you handle February – you need to know if it’s a leap year.

Horizontal and Vertical ScrollBar Controls

Horizontal ScrollBar In Toolbox:



Horizontal ScrollBar On Form (Default Properties):



Vertical ScrollBar In Toolbox:



Vertical ScrollBar On Form (Default Properties):



• The NumericUpDown control is useful for relatively small ranges of numeric input. It wouldn’t work well for large number ranges – you’d spend a lot of time clicking those little arrows. For large ranges of numbers, we use horizontal (HScrollBar) and vertical (VScrollBar) scroll bar controls. Scroll bars are widely used in Windows applications. Scroll bars provide an intuitive way to move through a list of information and make great input devices. Here, we use a scroll bar to obtain a whole number (Integer data type).

• Both type of scroll bars are comprised of three areas that can be clicked, or dragged, to change the scroll bar value. Those areas are:




Clicking an end arrow increments the scroll box a small amount, clicking the bar area increments the scroll box a large amount, and dragging the scroll box (thumb) provides continuous motion. Using the properties of scroll bars, we can completely specify how one works. The scroll box position is the only output information from a scroll bar.


• ScrollBar Properties (apply to both horizontal and vertical controls):

Name Gets or sets the name of the scroll bar (three letter prefix for horizontal scroll bar is hsb, for vertical scroll bar vsb).
LargeChange Increment added to or subtracted from the scroll bar Value property when the bar area is clicked.
Maximum The maximum value of the horizontal scroll bar at the far right and the maximum value of the vertical scroll bar at the bottom.
Minimum The minimum value of the horizontal scroll bar at the left and the vertical scroll bar at the top
SmallChange The increment added to or subtracted from the scroll bar Value property when either of the scroll arrows is clicked.
Value The current position of the scroll box (thumb) within the scroll bar. If you set this in code, Visual Basic .NET moves the scroll box to the proper position.

Location of properties for horizontal scroll bar:







Location of properties for vertical scroll bar:






• A couple of important notes about scroll bar properties:

1. Notice the vertical scroll bar has its Minimum at the top and its Maximum at the bottom. This may be counter-intuitive in some applications. That is, users may expect things to ‘go up’ as they increase. You can give this appearance of going up by defining another variable that varies ‘negatively’ with the scroll bar Value property.

2. If you ever change the Value, Minimum, or Maximum properties in code, make sure Value is at all times between Minimum and Maximum or the program will stop with an error message.

• ScrollBar Events:

Scroll Occurs when the scroll box has been moved by either a mouse or keyboard action.

• Typical use of HScrollBar and VScrollBar controsl:

 Decide whether horizontal or vertical scroll bar fits your needs best.
 Set the Name, Minimum, Maximum, SmallChange, LargeChange properties. Initialize Value property.
 Monitor Scroll event for changes in Value.


Example 4-2

Temperature Conversion

1. Start a new project. In this project, we convert temperatures in degrees Fahrenheit (set using a horizontal scroll bar) to degrees Celsius. The formula for converting Fahrenheit (F) to Celsius (C) is:

C = (F - 32) * 5 / 9

Temperatures will be adjusted and displayed in tenths of degrees.

2. Place a horizontal scroll bar, four labels, and a button on the form. Place two more labels (right behind each other) behind the scroll bar (we’ll use these for special effects). It should resemble this:




3. Set the properties of the form and each control:

Form1:
Name frmTemp
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Temperature Conversion

Label1:
Font Microsoft Sans Serif, Bold, Size 10
Text Fahrenheit
TextAlign MiddleCenter

Label2:
Name lblTempF
BackColor White
BorderStyle Fixed3D
Font Microsoft Sans Serif, Bold, Size 10
Text 32.0
TextAlign MiddleCenter

Label3:
Font Microsoft Sans Serif, Bold, Size 10
Text Celsius
TextAlign MiddleCenter

Label4:
Name lblTempC
BackColor White
BorderStyle Fixed3D
Font Microsoft Sans Serif, Bold, Size 10
Text 0.0
TextAlign MiddleCenter

Label5:
Name lblBlue
BackColor Blue

Label6:
Name lblRed
BackColor Red


HScrollBar1:
Name hsbTemp
LargeChange 10
Maximum 1200
Minimum -600
SmallChange 1
Value 320

Note the scroll bar properties (Value, Minimum, Maximum, SmallChange, LargeChange) are in tenths of degrees. The initial temperatures are initialized at 32.0 F (Value = 320 tenths of degrees) and 0.0 C, known values.

When done, the form should look like this:



3. Form level scope declarations:

Dim IsHot As Boolean


4. Use this code in the hsbTemp Scroll event.

Private Sub hsbTemp_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Handles hsbTemp.Scroll
Dim TempF As Single, TempC As Single
'Read F and convert to C - divide by 10 needed since Value is tenths of degrees
TempF = CSng(Val(hsbTemp.Value) / 10)
'check to see if changed from hot to cold or vice versa
If IsHot And TempF < 70 Then
'changed to cold
IsHot = False
lblBlue.BringToFront()
hsbTemp.BringToFront()
ElseIf Not (IsHot) And TempF >= 70 Then
'changed to hot
IsHot = True
lblRed.BringToFront()
hsbTemp.BringToFront()
End If
lblTempF.Text = Format(TempF, "0.0")
TempC = (TempF - 32) * 5 / 9
lblTempC.Text = Format(TempC, "0.0")
End Sub

This code determines the scroll bar Value as it changes, takes that value as Fahrenheit temperature, computes Celsius temperature, and displays both values. A blue label is used for cold temperatures, a red label for warm temperatures.

5. Give the program a try. Make sure it provides correct information at obvious points. For example, 32.0 F better always be the same as 0.0 C! What happens around 70 F? Save the project (saved in Example 4-2 folder in the LearnVBN\VBN Code\Class 4 folder).

Can you find a point where Fahrenheit temperature equals Celsius temperature? If you don't know this off the top of your head, it's obvious you've never lived in extremely cold climates. I've actually witnessed one of those bank temperature signs flashing degrees F and degrees C and seeing the same number! Ever wonder why body temperature is that odd figure of 98.6 degrees F? Can your new application give you some insight to an answer to this question?


PictureBox Control

In Toolbox:



On Form (Default Properties):



• Visual Basic .NET has powerful features for graphics. The PictureBox control is the primary tool for exploiting these features. The picture box control can display graphics files (in a variety of formats), can host many graphics functions and can be used for detailed animations. We look at using picture boxes for graphics and animations in later chapters. Here, we concentrate on using the control to display a graphics file.

• PictureBox Properties:

Name Gets or sets the name of the picture box (three letter prefix for picture box name is pic).
BackColor Get or sets the picture box background color.
BorderStyle Indicates the border style for the picture box.
Height Height of picture box in pixels.
Image Establishes the graphics file to display in the picture box.
Left Distance from left edge of form to left edge of picture box, in pixels.
SizeMode Indicates how the image is displayed.
Top Distance bottom of form title bar area to top edge of picture box, in pixels.
Width Width of picture box in pixels.

• PictureBox Events:

Click Triggered when a picture box is clicked.


• The Image property specifies the graphics file to display. It can be established in design mode or at run-time. To set the Image property at design time, simply display the Properties window for the picture box control and select the Image property. An ellipsis (…) will appear. Click the ellipsis and an Open File dialog box will appear. Use that box to locate the graphics file to display.

• Five types of graphics files can be viewed in a picture box:

File Type Description
Bitmap An image represented by pixels and stored as a collection of bits in which each bit corresponds to one pixel. This is the format commonly used by scanners and paintbrush programs. Bitmap filenames have a .bmp extension.
Icon A special type of bitmap file of maximum 32 x 32 size. Icon filenames have an .ico extension. We’ll create icon files in Class 5
Metafile A file that stores an image as a collection of graphical objects (lines, circles, polygons) rather than pixels. Metafiles preserve an image more accurately than bitmaps when resized. Many graphics files available for download from the internet are metafiles. Metafile filenames have a .wmf extension.
JPEG JPEG (Joint Photographic Experts Group) is a compressed bitmap format which supports 8 and 24 bit color. It is popular on the Internet and is a common format for digital cameras. JPEG filenames have a .jpg extension.
GIF GIF (Graphic Interchange Format) is a compressed bitmap format originally developed by CompuServe. It supports up to 256 colors and is also popular on the Internet. GIF filenames have a .gif extension.

• To set the Image property at run-time, you use the FromFile method associated with the Image object. As an example, to load the file c:\\sample\myfile.bmp into a picture box name picExample, the proper code is:

picExample.Image = Image.FromFile(“c:\\sample\myfile.bmp”)

The argument in the Image.From method must be a legal, complete path and file name, or your program will stop with an error message.


• To clear an image from a picture box control at run-time, simply set the corresponding Image property to Nothing (a Basic keyword). This disassociates the Image property from the last loaded image. For our example, the code is:

picExample.Image = Nothing

• The SizeMode property dictates how a particular image will be displayed. There are four possible values for this property: Normal, StretchImage, AutoSize, CenterImage. The effect of each value is:

SizeMode Effect
Normal Image appears in original size. If picture box is larger than image, there will be blank space. If picture box is smaller than image, the image will be cropped.
CenterImage Image appears in original size, centered in picture box. If picture box is larger than image, there will be blank space. If picture box is smaller than image, image is cropped.
StretchImage Image will ‘fill’ picture box. If image is smaller than picture box, it will expand. If image is larger than picture box, it will scale down. Bitmap and icon files do not scale nicely, Metafiles, JPEG and GIF files do scale nicely.
AutoSize Reverse of StretchImage - picture box will change its dimensions to match the original size of the image. Be forewarned – metafiles are usually very large!

Notice picture box dimensions remain fixed for Normal, CenterImage, and StretchImage SizeMode values. With AutoSize, the picture box will grow in size. This may cause problems at run-time if your form is not large enough to ‘contain’ the picture box.

• Typical use of PictureBox control for displaying images:

 Set the Name and SizeMode property (most often, StretchImage).
 Set Image property, either in design mode or at run-time.


OpenFileDialog Control

In Toolbox:



Below Form (Default Properties):



• Note that to set the Image property of the picture box control, you need the path and filename for the image file. How can you get this from a user? One possibility would be to use a text box control, asking the user to type in the desired information? This is just asking for trouble. Even the simplest of paths is difficult to type, remembering drive names, proper folder names, file names and extensions, and where all the slashes go. And then you, the programmer, must verify that the information typed contains a valid path and valid file name.

• I think you see that asking a user to type a path and file name is a bad idea. We want a ‘point and click’ type interface to get a file name. Every Windows application provides such an interface for opening files. [Click on the Open File toolbar button in Visual Basic .NET and an ‘Open File’ dialog box will appear.] Visual Basic .NET lets us use this same interface in our applications via the OpenFileDialog control. This control is one of a suite of dialog controls we can add to our applications. There are also dialog controls to save files, change fonts, change colors, and perform printing operations. We’ll look at other dialog controls as we work through the course.

• What we learn here is not just limited to opening image files for the picture box control. There are many times in application development where we will need a file name from a user. Applications often require data files, initialization files, configuration files, sound files and other graphic files. The OpenFileDialog control will also be useful in these cases.


• OpenFileDialog Properties:

Name Gets or sets the name of the open file dialog (I usually name this control dlgOpen).
AddExtension Gets or sets a value indicating whether the dialog box automatically adds an extension to a file name if the user omits the extension.
CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.
CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.
DefaultExt Gets or sets the default file extension.
FileName Gets or sets a string containing the file name selected in the file dialog box.
Filter Gets or sets the current file name filter string, which determines the choices that appear in "Files of type" box.
FilterIndex Gets or sets the index of the filter currently selected in the file dialog box.
InitialDirectory Gets or sets the initial directory displayed by the file dialog box.
Title Gets or sets the file dialog box title.

• OpenFileDialog Methods:

ShowDialog Displays the dialog box. Returned value indicates which button was clicked by user (OK or Cancel).

• To use the OpenFileDialog control, we add it to our application the same as any control. Since the OpenFileDialog control has no immediate user interface (you control when it appears), the control does not appear on the form at design time. Such Visual Basic .NET controls (the Timer control seen briefly back in Chapter 1 was a similar control) appear in a ‘tray’ below the form in the IDE Design window. Once added, we set a few properties. Then, we write code to make the dialog box appear when desired. The user then makes selections and closes the dialog box. At this point, we use the provided information for our tasks.


• The ShowDialog method is used to display the OpenFileDialog control. For a control named dlgOpen, the appropriate code is:

dlgOpen.ShowDialog()

And the displayed dialog box is:



• The user selects a file using the dialog control (or types a name in the File name box). The file type is selected form the Files of type box (values here set with the Filter property). Once selected, the Open button is clicked. Cancel can be clicked to cancel the open operation. The ShowDialog method returns the clicked button. It returns DialogResult.OK if Open is clicked and returns DialogResult.Cancel if Cancel is clicked. The nice thing about this control is that it can validate the file name before it is returned to the application. The FileName property contains the complete path to the selected file.

• Typical use of OpenFileDialog control:

 Set the Name, Filter, and Title properties.
 Use ShowDialog method to display dialog box.
 Read FileName property to determine selected file


Example 4-3

Picture Box Playground

1. Start a new project. In this project, we will use a OpenFileDialog control to select image files. The selected file will be displayed in four different picture box controls (one for each setting of the SizeMode property).

2. Place 4 labels at the top of a form. Place a picture box control under each of the 4 labels. Place two more labels and a button control under these controls. Finally, place the OpenFileDialog control in the ‘tray’ under the form. The form (which will be rather wide) should look like this:




3. Set the properties of the form and each control:

Form1:
Name frmPlayground
Text Picture Box Playground

Label1:
Text Normal:

Label2:
Text CenterImage:


Label3:
Text StretchImage:

Label4:
Text AutoSize:

PictureBox1:
Name picNormal
BackColor White
BorderStyle FixedSingle
SizeMode Normal

PictureBox2:
Name picCenter
BackColor White
BorderStyle FixedSingle
SizeMode CenterImage

PictureBox3:
Name picStretch
BackColor White
BorderStyle FixedSingle
SizeMode StretchImage

PictureBox4:
Name picAuto
BackColor White
BorderStyle FixedSingle
SizeMode AutoSize

Label5:
Text Size:
TextAlign LeftCenter

Label6:
Name lblSize
BackColor White
BorderStyle Fixed3D
Text [Blank]
TextAlign LeftCenter


Button1:
Name btnImage
Text &Select Image

OpenFileDialog1:
Name dlgOpen
Filter Bitmaps (*.bmp)|*.bmp|Icons (*.ico)|*.ico|Metafiles (*.wmf)|*.wmf|JPEG (*.jpg)|*.jpg|GIF (*.gif)|*.gif
[Type this line carefully! – consult on-line help as reference]
Title Open Image File

When done, the form should look like this:




4. Form level scope declarations:

Dim WSave As Integer, HSave As Integer

5. Use this code in the Form Load event to initialize positions and save size:

Private Sub frmPlayground_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
'start form in upper left corner
Me.Left = 0
Me.Top = 0
'save form width/height for initialization
WSave = Me.Width
HSave = Me.Height
End Sub

6. Use this code in the btnImage Click event:

Private Sub btnImage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImage.Click
'reset autosize picture box and form to initial size
picAuto.Width = picNormal.Width
picAuto.Height = picNormal.Height
Me.Width = WSave
Me.Height = HSave
'display open dialog box
If dlgOpen.ShowDialog = DialogResult.OK Then
picNormal.Image = Image.FromFile(dlgOpen.FileName)
picCenter.Image = Image.FromFile(dlgOpen.FileName)
picStretch.Image = Image.FromFile(dlgOpen.FileName)
picAuto.Image = Image.FromFile(dlgOpen.FileName)
lblSize.Text = Str(picAuto.Width) + " pixels x" + Str(picAuto.Height) + " pixels"
End If
End Sub

This code reads the selected file and displays it in each of the picture box controls.

7. Save the application (saved in Example 4-3 folder in the LearnVBN\VBN Code\Class 4 folder). Run the application and open different types of image files (we’ve included one of each type in the project folder). Notice how the different SizeMode properties affect the display. Images in the AutoSize mode may be very large requiring resizing of the form.

Legacy Controls

• Visual Basic .NET provides a wealth of useful controls in its toolbox. Compared to previous incarnations of Visual Basic, there are many new, improved tools. Visual Basic .NET has also eliminated some controls that existed in Visual Basic. For the most part, elimination of these legacy controls is a good thing. But there are three controls we wish they had not eliminated.

• In the Picture Box Playground example just developed, every time we want to change the image, it is necessary to bring up the open file dialog box. What would be nice is to have the capability of the dialog box built into the form providing a clickable list of image files. As each file name was clicked, the corresponding image would be displayed in each of the picture boxes. Visual Basic offered three controls that allowed this capability.

• The DriveListBox Control was a dropdown box that allowed selection of drives. The DirListBox Control was a list box allowing folder selection. And, the FileLIstBox control was a list box allowing file selection. Using these three controls on a form allowed a ‘built-in’ replication of the open file dialog box. And, the nice thing about these controls is you could choose as many as you like. For example, if you just wanted to present your user a selection of files in a single directory they could not change, you could just use the FileListBox control. The OpenFileDialog control does not allow such a limitation.

• So, are we just left with our ‘wishing and hoping’ these controls were back? Unfortunately, no. Visual Basic .NET still has some of these legacy controls (as part of the Microsoft.Visual Basic.Compatibility.VB6 namespace), but they must be added to the toolbox. To do this, choose the Tools menu option and select Customize Toolbox. When the dialog box appears, select .NET Framework Components. Place check marks next to: DriveListBox, DirListBox and FileListBox. Click OK and the controls will appear in the toolbox and become available for use (on-line help is available for documentation).

• You may see other legacy controls in the Customize Toolbox dialog box. You can decide if you need any other such controls. Be aware, however, that using legacy controls could be dangerous. Microsoft may decide to drop support for such controls at any time. Our hope is that controls similar to the drive, directory and file list tools are added with the next version of Visual Basic .NET – their utility calls out for their inclusion.


DriveListBox Controls

In Toolbox:



On Form (Default Properties):



• The DriveListBox control allows a user to select a valid disk drive at run-time. It displays the available drives in a drop-down combo box. No code is needed to load a drive list box with valid drives; Visual Basic .NET does this for us. We use the box to get the current drive identification.

• DriveListBox Properties:

Name Gets or sets the name of the drive list box (three letter prefix for drive list box name is drv).
BackColor Get or sets the drive list box background color.
Drive Contains the name of the currently selected drive.
DropDownStyle Gets or sets a value specifying the style of the drive list box.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.

• DriveListBox Events:

SelectedValueChanged Triggered whenever the user or program changes the drive selection.

• This control is always used in conjunction with the DirListBox and FileListBox controls – we rarely look at the Drive property.

• Typical use of DriveListBox control:

 Set the Name property.
 Use SelectedValueChanged event to update displayed directories.



DirListBox Control

In Toolbox:



On Form (Default Properties):



• The DirListBox control displays an ordered, hierarchical list of the user's disk directories and subdirectories. The directory structure is displayed in a list box. Like, the drive list box, little coding is needed to use the directory list box - Visual Basic .NET does most of the work for us.

• DirListBox Properties:

Name Gets or sets the name of the directory list box (three letter prefix for directory list box name is dir).
BackColor Get or sets the directory list box background color.
BorderStyle Establishes the border for directory list box.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Path Gets or sets the current directory path.

• DirListBox Events:

Change Triggered when the directory selection is changed.

• Typical use of DirListBox control:

 Set the Name property.
 Use Change event to update displayed files.
 Read Path property for current path.


FileListBox Control

In Toolbox:



On Form (Default Properties):



• The FileListBox control locates and lists files in the directory specified by its Path property at run-time. You may select the types of files you want to display in the file list box. You will notice most of its properties are very similar to those of the list box control.

• FileListBox Properties:

Name Gets or sets the name of the file list box (three letter prefix for file list box name is fil).
BackColor Get or sets the file list box background color.
FileName Contains the currently selected file name.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the file list box.
Path Contains the current path directory.
Pattern Contains a string that determines which files will be displayed. It supports the use of * and ? wildcard characters. For example, using *.dat only displays files with the .dat extension.
SelectedIndex Gets or sets the zero-based index of the currently selected item in a list box.
SelectionMode Gets or sets the method in which items are selected in file list box (allows single or multiple selections).


• FileListBox Events:

SelectedIndexChanged Occurs when the SelectedIndex property has changed.

• If needed, the number of items in the list is provided by the Items.Count property. The individual items in the list are found by examining elements of the Items.Item zero-based array.

• Typical use of FileListBox control:

 Set Name and Pattern properties.
 Monitor SelectedIndexChanged event for individual selections.
 Use Path and FileName properties to form complete path to selected file.



Synchronizing the Drive, Directory, and File List Box Controls

• The drive, directory and file list boxes are controls that can be used independently of each other. As such, there are no common properties or linking mechanisms. When used with each other to obtain a file name, their operation must be synchronized to insure the displayed information is always consistent.

• When the drive selection is changed (drive list box SelectedValueChanged event), you need to update the directory list box path. For example, if the drive list box is named drvExample and the directory list box is dirExample, use the code:

dirExample.Path = drvExample.Drive

• When the directory selection is changed (directory list box Change event), you must update the names displayed in the file list box. With a file list box named filExample, this code is:

filExample.Path = dirExample.Path

• Once all of the selections have been made and you want the file name, you need to form a text string that specifies the complete path to the file. This string concatenates the Path and FileName information from the file list box. This should be an easy task, except for one problem. The problem involves the backslash (\) character. If you are at the root directory of your drive, the path name ends with a backslash. If you are not at the root directory, there is no backslash at the end of the path name and you have to add one before tacking on the file name.


• Example code for concatenating the available information into a proper file name (YourFile):

Dim YourFile As String

If Mid(filExample.Path, Len(filExample.Path), 1) = "\" Then
YourFile = filExample.Path + filExample.FileName
Else
YourFile = filExample.Path + "\" + filExample.FileName
End If

The Mid() statement checks the last character in the Path property to see if it is a backslash. Note we only have to use properties of the file list box. The drive and directory box properties are only used to create changes in the file list box via code.


Example 4-4

Image Viewer

1. Start a new project. In this application, we search our computer's file structure for graphics files and display the results of our search in an picture box control.

2. First, place a group box control on the form. In this group box, place a drive list box, directory list box, file list box, and four label boxes. Make sure you have added the three legacy list box controls to your toolbox using instructions provided earlier. Add a second group box. In that group box, place a picture box control and three radio buttons. The form should look like this:




3. Set properties of the form and each control.

Form1:
Name frmImage
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Image Viewer

GroupBox1:
Name grpFile
BackColor Red
Text [Blank]

Label1:
Name lblImage
BackColor Yellow
BorderStyle Fixed3D
Text [Blank]
TextAlign MiddleLeft

Label2:
ForeColor Yellow
Text Files:

DriveListBox1:
Name drvImage

Label3:
ForeColor Yellow
Text Directories:

DirLIstBox1:
Name dirImage

Label4:
ForeColor Yellow
Text Drives:

FileListBox1:
Name filImage
Pattern *.bmp;*.ico;*.wmf;*.gif;*jpg
[type this line with no spaces]


GroupBox1:
Name grpImage
BackColor Blue
Text [Blank]

PictureBox1:
Name picImage
BackColor White
BorderStyle FixedSingle

RadioButton1:
Name rdoNormal
ForeColor Yellow
Text Normal

RadioButton2:
Name rdoCenter
ForeColor Yellow
Text Center

RadioButton3:
Name rdoStretch
ForeColor Yellow
Text Stretch


My finished form is this:




4. Use this code in the Form Load procedure (initializes Stretch size mode):

Private Sub frmImage_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'initialize stretch mode
rdoStretch.PerformClick()
End Sub

5. Use this code in the drvImage SelectedValueChanged procedure.

Private Sub drvImage_SelectedValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drvImage.SelectedValueChanged
'If drive changes, update directory
dirImage.Path = drvImage.Drive
End Sub

When a new drive is selected, this code forces the directory list box to display directories on that drive.


6. Use this code in the dirImage Change procedure.

Private Sub dirImage_Change(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dirImage.Change
'If directory changes, update file path
filImage.Path = dirImage.Path
End Sub

Likewise, when a new directory is chosen, we want to see the files on that directory.

7. Use this code for the filImage SelectedIndexChanged event.

Private Sub filImage_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filImage.SelectedIndexChanged
'Get complete path to file name and open graphics
Dim ImageName As String
If Mid(filImage.Path, Len(filImage.Path), 1) = "\" Then
ImageName = filImage.Path + filImage.FileName
Else
ImageName = filImage.Path + "\" + filImage.FileName
End If
lblImage.Text = ImageName
picImage.Image = Image.FromFile(ImageName)
End Sub

This code forms the file name (ImageName) by concatenating the directory path with the file name. It then displays the complete name and loads the image into the picture box.

8. Lastly, code the three radio button CheckChanged events to change the display size mode:

Private Sub rdoNormal_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoNormal.CheckedChanged
picImage.SizeMode = PictureBoxSizeMode.Normal
End Sub


Private Sub rdoCenter_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoCenter.CheckedChanged
picImage.SizeMode = PictureBoxSizeMode.CenterImage
End Sub

Private Sub rdoStretch_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoStretch.CheckedChanged
picImage.SizeMode = PictureBoxSizeMode.StretchImage
End Sub

9. Save your project (saved in Example 4-4 folder in LearnVBN\VBN Code\Class 4 folder). Run and try the application. Find bitmaps, icons, metafiles, gif files, and JPEGs (an example of each is included in the project folder). Here’s how the form should look when displaying the example JPEG file (a photo from my Mexican vacation):





Class Review

• After completing this class, you should understand:

 The concept of Z Order for a control
 Useful properties, events, methods and typical uses for the numeric updown and domain updown controls
 Properties, events, methods, and uses for the horizontal and vertical scroll bar controls
 The five types of graphics files that can be displayed by the picture box control
 How the picture box SizeMode property affects Image display
 How to load image files at both design time and run time
 How to use the file open common dialog box to obtain file names for opening files
 How the legacy drive, directory, and file list controls work and when they could be used




Practice Problems 4

Problem 4-1. Tic-Tac-Toe Problem. Build a simple Tic-Tac-Toe game. Use ‘skinny’ label controls for the grid and picture box controls for markers (use different pictures to distinguish players). Click the image controls to add the markers. Can you write logic to detect a win?

Problem 4-2. Number Guess Problem. Build a game where the user guesses a number between 1 and 100. Use a scroll bar for entering the guess and change the extreme limits (Minimum and Maximum properties) with each guess to help the user adjust their guess.

Problem 4-3. File Times Problem. Using the drive, directory and file list controls, write an application that lists all files in a directory. For every file, find what time the file was created (use the FileDateTime() function to get time details). Determine the most popular hours of the day for creating files.





Exercise 4

Student Database Input Screen

You did so well with last chapter’s assignment that, now, a school wants you to develop the beginning structure of an input screen for its students. The required input information is:

1. Student Name
2. Student Grade (1 through 6)
3. Student Sex (Male or Female)
4. Student Date of Birth (Month, Day, Year)
5. Student Picture (Assume they can be loaded as jpeg files)

Set up the screen so that only the Name needs to be typed; all other inputs should be set with option buttons, scroll bars, and common dialog boxes. When a screen of information is complete, display the summarized profile in a message box. This profile message box should resemble this:



Note the student’s age must be computed from the input birth date - watch out for pitfalls in doing the computation. The student’s picture does not appear in the profile, only on the input screen.

Belajar vb.net volume 3#

Learn Visual Basic .NET


3. Exploring the Visual Basic .NET Toolbox


Review and Preview

• We have now learned the three steps in developing a Windows application and have been introduced to the Basic language. In this class, we begin a journey where we look at each tool in the Visual Basic .NET toolbox. We will revisit some tools we already know and learn a lot of new tools. Examples of how to use each control will be presented.



Function Overloading

• As we delve further into Visual Basic .NET, we will begin to use many of its built-in functions for dialog boxes, drawing graphics, and other tasks. Before using these functions (we will use the MessageBox function soon), you need be aware of an object-oriented concept known as overloading.

• Overloading lets a function vary its behavior based on its input arguments. Visual Basic .NET will have multiple functions with the same name, but with different argument lists. The different argument lists may have different numbers of arguments and different types of arguments.

• What are the implications of overloading? What this means to us is that when using a Visual Basic .NET function, there will may several different ways to use that function. In these notes, we will show you a few ways, but not all. You are encouraged to use on-line help to investigate all ways to use a function.

• Another implication is that, when typing code for a function, the Intellisense feature of the Visual Basic .NET IDE will appear with a drop-down list of all implementations of a particular function. As you type in your implementation, Intellisense adjusts to the particular form of the function it “thinks” you are using. Suggestions are made for possible arguments – it’s like magic! Sometimes, Intellisense guesses right, sometimes not. You must insure the implementation is the one you desire. If, after typing in a function use, Intellisense does not recognize it as proper usage, it will be flagged with an error indication (underlined) and you are given some direction for correcting the error.

• Overloading is a powerful feature of Visual Basic .NET. You will quickly become accustomed to using multiple definitions of functions and how Intellisense interacts with you, the programmer.


MessageBox Dialog

• One of the most often used functions in Visual Basic .NET is the MessageBox function. This function lets you display messages to your user and receive feedback for further information. It can be used to display error messages, describe potential problems or just to show the result of some computation. The MessageBox function is versatile, with the ability to display any message, an optional icon, and a selected set of Button buttons. The user responds by clicking a button in the message box

• You've seen message boxes if you've ever used a Windows application. Think of all the examples you've seen. For example, message boxes are used to ask you if you wish to save a file before exiting and to warn you if a disk drive is not ready. For example, if while writing these notes in Microsoft Word, I attempt to exit, I see this message box:





In this message box, the different parts that you control have been labeled. You will see how you can format a message box any way you desire.

• To use the MessageBox function, you decide what the Text of the message should be, what Caption you desire, what Icon and Buttons are appropriate, and which DefaultButton you want. To display the message box in code, you use the MessageBox Show method.


• The MessageBox function is overloaded with several ways to implement the Show method. Some of the more common ways are:

MessageBox.Show(Text)
MessageBox.Show(Text, Caption)
MessageBox.Show(Text, Caption, Buttons)
MessageBox.Show(Text, Caption, Buttons, Icon)
MessageBox.Show(Text, Caption, Buttons, Icon, DefaultButton)

In these implementations, if DefaultButton is omitted, the first button is default. If Icon is omitted, no icon is displayed. If Buttons is omitted, an ‘OK’ button is displayed. And, if Caption is omitted, no caption is displayed.

• You decide what you want for the message box Text and Caption information (string data types). The other arguments are defined by Visual Basic .NET predefined constants. The Buttons constants are defined by the MessageBoxButtons constants:

Member Description
AbortRetryIgnore Displays Abort, Retry and Ignore buttons
OK Displays an OK button
OKCancel Displays OK and Cancel buttons
RetryCancel Displays Retry and Cancel buttons
YesNo Displays Yes and No buttons
YesNoCancel Displays Yes, No and Cancel buttons

The syntax for specify a choice of buttons is the usual dot-notation:

MessageBoxButtons.Member

So, to display an OK and Cancel button, the constant is:

MessageBoxButtons.OKCancel

You don’t have to remember this, however. When typing the code, the Intellisense feature will provide a drop-down list of button choices when you reach that argument! Again, like magic! This will happen for all the arguments in the MessageBox function.


• The displayed Icon is established by the MessageBoxIcon constants:

Member Description
IconAsterisk Displays an information icon
IconInformation Displays an information icon
IconError Displays an error icon (white X in red circle)
IconHand Displays an error icon
IconStop Displays an error icon
IconExclamation Displays an exclamation point icon
IconWarning Displays an exclamation point icon
IconQuestion Displays a question mark icon

To specify an icon, the syntax is:

MessageBoxIcon.Member

Note there are eight different members of the MessageBoxIcon constants, but only four icons (information, error, exclamation, question) available. This is because the current Windows operating system only offers four icons. Future implementations may offer more.

• When a message box is displayed, one of the displayed buttons will have focus or be the default button. If the user presses , this button is selected. You specify which button is default using the MessageBoxDefaultButton constants:

Member Description
DefaultButton1 First button in message box is default
DefaultButton2 Second button in message box is default
DefaultButton3 Third button in message box is default

To specify a default button, the syntax is:

MessageBoxDefaultButton.Member

The specified default button is relative to the displayed buttons, left to right. So, if you have Yes, No and Cancel buttons displayed and the second button is selected as default, the No button will have focus (be default).


• When you invoke the Show method of the MessageBox function, the function returns a value from the DialogResult constants. The available members are:

Member Description
Abort The Abort button was selected
Cancel The Cancel button was selected
Ignore The Ignore button was selected
No The No button was selected
OK The OK button was selected
Retry The Retry button was selected
Yes The Yes button was selected

• MessageBox Example:

This little code snippet (the first line is very long):

If MessageBox.Show("This is an example of a message box", "Message Box Example", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) = DialogResult.OK Then
'everything is OK
Else
'cancel was pressed
End If

displays this message box:



Of course, you would need to add code for the different tasks depending on whether OK or Cancel is clicked by the user.


• Another MessageBox Example:

Many times, you just want to display a quick message to the user with no need for feedback (just an OK button). This code does the job:

MessageBox.Show("Quick message for you.", "Hey You!")

The resulting message box:




Notice there is no icon and the OK button (default if no button specified) is shown. Also, notice in the code, there is no need to read the returned value – we know what it is! You will find a lot of uses for this simple form of the message box (with perhaps some kind of icon) as you progress in Visual Basic .NET.

• We now start our study of the Visual Basic .NET toolbox, looking at important properties, methods and events for many controls. We start this study with the most important ‘control,’ the form.


Form Object



• The Form is the object where the user interface is drawn. It is central to the development of Visual Basic .NET applications. The form is known as a container object, since it ‘holds’ other controls. One implication of this distinction is that controls placed on the form will share BackColor, ForeColor and Font properties. To change this, select the desired control (after it is placed on the form) and change the desired properties. Another feature of a container control is that when its Enabled property is False, all controls in the container are disabled. Likewise, when the container control Visible property is False, all controls in the container are not visible.

• Here, we present some of the more widely used Properties, Methods and Events for the form. Recall properties described the appearance and value of a control, methods are actions you can impose on controls and events occur when something is done to the control (usually by a user). This is not an exhaustive list – consult on-line help for such a list. You may not recognize all of these terms now. They will be clearer as you progress in the course. The same is true for the remaining controls presented in this chapter.

• Form Properties:

Name Gets or sets the name of the form (three letter prefix for form name is frm).
AcceptButton Gets or sets the button on the form that is clicked when the user presses the key.
BackColor Get or sets the form background color.
CancelButton Gets or sets the button control that is clicked when the user presses the key.
ControlBox Gets or sets a value indicating whether a control box is displayed in the caption bar of the form.
Enabled If False, all controls on form are disabled.
Font Gets or sets font name, style, size.

Form Properties (continued)

ForeColor Gets or sets color of text or graphics.
FormBorderStyle Sets the form border to be fixed or sizeable.
Height Height of form in pixels.
Help Gets or sets a value indicating whether a Help button should be displayed in the caption box of the form.
Icon Gets or sets the icon for the form.
Left Distance from left of screen to left edge of form, in pixels.
MaximizeButton Gets or sets a value indicating whether the maximize button is displayed in the caption bar of the form.
MinimizeButton Gets or sets a value indicating whether the minimize button is displayed in the caption bar of the form.
StartPosition Gets or sets the starting position of the form when the application is running.
Text Gets or sets the form window title.
Top Distance from top of screen to top edge of form, in pixels.
Width Width of form in pixels.

• Form Methods:

Close Closes the form.
Focus Sets focus to the form.
Hide Hides the form.
Refresh Forces the form to immediately repaint itself.
Show Makes the form display by setting the Visible property to True.
Print Prints text string on the form.

• The normal syntax for invoking a method is to type the control name, a dot, then the method name. For form methods, the name to use is Me. This is a Visual Basic .NET keyword used to refer to a form. Hence, to close a form, use:

Me.Close()


• Form Events:

Activated Occurs when the form is activated in code or by the user.
Click Occurs when the form is clicked by the user.
Closing Occurs when the form is closing.
DoubleClick Occurs when the form is double clicked.
Load Occurs before a form is displayed for the first time.
Paint Occurs when the form is redrawn.

• Typical use of Form object (for each control in this, and following chapters, we will provide information for how that control is typically used):

 Set the Name and Text properties
 Set the StartPosition property (in this course, this property will almost always be set to CenterScreen)
 Set the FormBorderStyle to some value. In this course, we will mostly use FixedSingle forms. You can have resizable forms in Visual Basic .NET (and there are useful properties that help with this task), but we will not use resizable forms in this course.
 Write any needed initialization code in the form’s Load event. To access this event in the Code window, select the Base Class Events object, then the Load event.



Button Control

In Toolbox:



On Form (Default Properties):



• We've seen the Button control before. It is probably the most widely used Visual Basic .NET control. It is used to begin, interrupt, or end a particular process. Here, we provide some of the more widely used properties, methods and events for the button control.

• Button Properties:

Name Gets or sets the name of the button (three letter prefix for button name is btn).
BackColor Get or sets the button background color.
Enabled If True, button is visible, but cannot accept clicks.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
Image Gets or sets the image that is displayed on a button control.
Text Gets or sets string displayed on button.
TextAlign Gets or sets the alignment of the text on the button control.

• Button Methods:

Focus Sets focus to the button.
PerformClick Generates a Click event for a button.

• Button Events:

Click Event triggered when button is selected either by clicking on it or by pressing the access key.


• Typical use of Button control:

 Set the Name and Text property.
 Write code in the button’s Click event.
 You may also want to change the Font, Backcolor and Forecolor properties.

Label Control

In Toolbox:



On Form (Default Properties):



• A Label control is used to display text that a user can't edit directly. We've seen, though, in previous examples, that the text of a label box can be changed at run-time in response to events.

• Label Properties:

Name Gets or sets the name of the label (three letter prefix for label name is lbl).
AutoSize Gets or sets a value indicating whether the label is automatically resized to display its entire contents.
BackColor Get or sets the label background color.
BorderStyle Gets or sets the border style for the label.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
Text Gets or sets string displayed on label.
TextAlign Gets or sets the alignment of text in the label.

• Label Methods:

Refresh Forces an update of the label control contents.

• Label Events:

Click Event triggered when user clicks on a label.
DblClick Event triggered when user double-clicks on a label.


• Typical use of Label control for static, unchanging display:

 Set the Name (though not really necessary for static display) and Text property.
 You may also want to change the Font, Backcolor and Forecolor properties.

• Typical use of Label control for changing display:

 Set the Name property. Initialize Text to desired string.
 Assign Text property (String type) in code where needed.
 You may also want to change the Font, Backcolor and Forecolor properties.


TextBox Control

In Toolbox:



On Form (Default Properties):



• A TextBox control is used to display information entered at design time, by a user at run-time, or assigned within code. The displayed text may be edited.

• TextBox Properties:

Name Gets or sets the name of the text box (three letter prefix for text box name is txt).
AutoSize Gets or sets a value indicating whether the height of the text box automatically adjusts when the font assigned to the control is changed.
BackColor Get or sets the text box background color.
BorderStyle Gets or sets the border style for the text box.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
HideSelection Gets or sets a value indicating whether the selected text in the text box control remains highlighted when the control loses focus.
Lines Gets or sets the lines of text in a text box control.
MaxLength Gets or sets the maximum number of characters the user can type into the text box control.
MultiLine Gets or sets a value indicating whether this is a multiline text box control.
PasswordChar Gets or sets the character used to mask characters of a password in a single-line TextBox control.
ReadOnly Gets or sets a value indicating whether text in the text box is read-only.
ScrollBars Gets or sets which scroll bars should appear in a multiline TextBox control.

TextBox Properties (continued)

SelectedText Gets or sets a value indicating the currently selected text in the control.
SelectionLength Gets or sets the number of characters selected in the text box.
SelectionStart Gets or sets the starting point of text selected in the text box.
Tag Stores a string expression.
Text Gets or sets the current text in the text box.
TextAlign Gets or sets the alignment of text in the text box.
TextLength Gets length of text in text box.

• TextBox Methods:

AppendText Appends text to the current text of text box.
Clear Clears all text in text box.
Copy Copies selected text to clipboard.
Cut Moves selected text to clipboard.
Focus Places the cursor in a specified text box.
Paste Replaces the current selection in the text box with the contents of the Clipboard.
Undo Undoes the last edit operation in the text box.

• TextBox Events:

Click Occurs when the user clicks the text box.
GotFocus Occurs when the control receives focus.
KeyDown Occurs when a key is pressed down while the control has focus.
KeyPress Occurs when a key is pressed while the control has focus – used for key trapping.
LostFocus Triggered when the user leaves the text box. This is a good place to examine the contents of a text box after editing.
TextChanged Occurs when the Text property value has changed.


• Typical use of TextBox control as display control:

 Set the Name property. Initialize Text property to desired string.
 If displaying more than one line, set MultiLine property to True.
 Assign Text property in code where needed.
 You may also want to change the Font, Backcolor and Forecolor properties.

• Typical use of TextBox control as input device:

 Set the Name property. Initialize Text property to desired string.
 If it is possible to input multiple lines, set MultiLine property to True.
 In code, give Focus to control when needed. Provide key trapping code in KeyPress event. Read Text property when LostFocus event occurs.
 You may also want to change the Font, Backcolor and Forecolor properties.

• Use of the TextBox control should be minimized if possible. Whenever you give a user the option to type something, it makes your job as a programmer more difficult. You need to validate the information they type to make sure it will work with your code (recall the Savings Account example in the last class, where we need key trapping to insure only numbers were being entered). There are many controls in Visual Basic .NET that are ‘point and click,’ that is, the user can make a choice simply by clicking with the mouse. We’ll look at such controls through the course. Whenever these ‘point and click’ controls can be used to replace a text box, do it!


Example 3-1

Password Validation

1. Start a new project. The idea of this project is to ask the user to input a password. If correct, a message box appears to validate the user. If incorrect, other options are provided.

2. Place a two buttons, a label box, and a text box on your form so it looks something like this:



3. Set the properties of the form and each object.

Form1:
Name frmPassword
AcceptButton btnValid
CancelButton btnExit
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Password Validation

Label1:
BorderStyle Fixed3D
Font Size 10
Font Style Bold
Text Please Enter Your Password:
TextAlign MiddleCenter


Text1:
Name txtPassword
Font Size 14
PasswordChar *
Tag [Whatever you choose as a password]
Text [Blank]

Button1:
Name btnValid
Text &Validate

Button2:
Name btnExit
Text E&xit

Your form should now look like this:




4. Use the following code in the btnValid Click event.

Private Sub btnValid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValid.Click
'This procedure checks the input password
Dim Response As DialogResult
If txtPassword.Text = CStr(txtPassword.Tag) Then
'If correct, display message box
MessageBox.Show("You've passed security!", "Access Granted", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
Else
'If incorrect, give option to try again
Response = MessageBox.Show("Incorrect password", "Access Denied", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)
If Response = DialogResult.Retry Then
txtPassword.SelectionStart = 0
txtPassword.SelectionLength = Len(txtPassword.Text)
Else
Me.Close()
End If
End If
txtPassword.Focus()
End Sub

This code checks the input password to see if it matches the stored value. If so, it prints an acceptance message. If incorrect, it displays a message box to that effect and asks the user if they want to try again. If Yes (Retry), another try is granted. If No (Cancel), the program is ended. Notice the use of SelectionLength and SelectionStart to highlight an incorrect entry. This allows the user to type right over the incorrect response.

5. Use the following code in the Form_Load event.

Private Sub frmPassword_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'make sure focus starts in text box
txtPassword.Focus()
End Sub


6. Use the following code in the btnExit_ Click event.

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub

7. Try running the program. Try both options: input correct password (note it is case sensitive) and input incorrect password. Save your project (saved in Example 3-1 folder in the LearnVBN\VBN Code\Class 3 folder).

If you have time, define a constant, TRYMAX = 3, and modify the code to allow the user to have just TRYMAX attempts to get the correct password. After the final try, inform the user you are logging him/her off. You’ll also need a variable that counts the number of tries (make it a Static variable).


CheckBox Control

In Toolbox:



On Form (Default Properties):



• As mentioned earlier, Visual Basic .NET features many ‘point and click’ controls that let the user make a choice simply by clicking with the mouse. These controls are attractive, familiar and minimize the possibility of errors in your application. We will see many such controls. The first, the CheckBox control, is examined here.

• The CheckBox control provides a way to make choices from a list of potential candidates. Some, all, or none of the choices in a group may be selected. Check boxes are used in all Windows applications (even the Visual Basic .NET IDE). Examples of their use would be to turn options on and off in an application or to select from a ‘shopping’ list.

• CheckBox Properties:

Name Gets or sets the name of the check box (three letter prefix for check box name is chk).
BackColor Get or sets the check box background color.
Checked Gets or sets a value indicating whether the check box is in the checked state.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
Text Gets or sets string displayed next to check box.
TextAlign Gets or sets the alignment of text of the check box.

• CheckBox Methods:

Focus Moves focus to this check box.


• CheckBox Events:

CheckedChange Occurs when the value of the Checked property changes.
Click Triggered when a check box is clicked. Checked property is automatically changed by Visual Basic .NET.

• When a check box is clicked, if there is no check mark there (Checked = False), Visual Basic .NET will place a check there and change the Checked property to True. If clicked and a check mark is not there (Checked = False), then a check mark will appear and the Checked property will be changed to True. The check box can also be configured to have three states: checked, unchecked or indeterminate. Consult on-line help if you require such behavior.

• Typical use of CheckBox control:

 Set the Name and Text property. Initialize the Checked property.
 Monitor Click or CheckChanged event to determine when button is clicked. At any time, read Checked property to determine check box state.
 You may also want to change the Font, Backcolor and Forecolor properties.


RadioButton Control

In Toolbox:



On Form (Default Properties):



• RadioButton controls provide the capability to make a “mutually exclusive” choice among a group of potential candidate choices. This simply means, radio buttons work as a group, only one of which can be selected. Radio buttons are seen in all Windows applications. They are called radio buttons because they work like a tuner on a car radio – you can only listen to one station at a time! Examples for radio button groups would be twelve buttons for selection of a month in a year, a group of buttons to let you select a color or buttons to select the difficulty in a game.

• A first point to consider is how do you define a ‘group’ of radio buttons that work together? Any radio buttons placed on the form will act as a group. That is, if any radio button on a form is ‘selected’, all other buttons will be automatically ‘unselected.’ What if you need to make two independent choices; that is, you need two independent groups of radio buttons? To do this requires one of two grouping controls in Visual Basic .NET: the GroupBox control or the Panel control. Radio buttons placed on either of these controls are independent from other radio buttons. We will discuss the grouping controls after the RadioButton control. For now, we’ll just be concerned with how to develop and use a single group of radio buttons.

• RadioButton Properties:

Name Gets or sets the name of the radio button (three letter prefix for radio button name is rdo).
BackColor Get or sets the radio button background color.
Checked Gets or sets a value indicating whether the radio button is checked.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text or graphics.
TextAlign Gets or sets the alignment of text of the radio button.


• RadioButton Methods:

Focus Moves focus to this radio button.
PerformClick Generates a Click event for the button, simulating a click by a user.

• RadioButton Events:

CheckedChange Occurs when the value of the Checked property changes.
Click Triggered when a button is clicked. Checked property is automatically changed by Visual Basic .NET.

• When a radio button is clicked, it’s Checked property is automatically set to True by Visual Basic .NET. And, all other radio buttons in that button’s group will have a Checked property of False. Only one button in the group can be checked.

• Typical use of RadioButton control:

 Establish a group of radio buttons.
 For each button in the group, set the Name (give each button a similar name to identify them with the group) and Text property. You might also change the Font, BackColor and Forecolor properties.
 Initialize the Checked property of one button to True.
 Monitor the Click or CheckChanged event of each radio button in the group to determine when a button is clicked. The ‘last clicked’ button in the group will always have a Checked property of True.


GroupBox Control

In Toolbox:



On Form (Default Properties):



• We've seen that both radio buttons and check boxes usually work as a group. Many times, there are logical groupings of controls. For example, you may have a scroll device setting the value of a displayed number. The GroupBox control provides a convenient way of grouping related controls in a Visual Basic .NET application. And, in the case of radio buttons, group boxes affect how such buttons operate.

• To place controls in a group box, you first draw the GroupBox control on the form. Then, the associated controls must be placed in the group box. This allows you to move the group box and controls together. There are several ways to place controls in a group box:

 Place controls directly in the group box using any of the usual methods.
 Draw controls outside the group box and drag them in.
 Copy and paste controls into the group box (prior to the paste operation, make sure the group box is selected).

To insure controls are properly place in a group box, try moving it and make sure the associated controls move with it.

• Like the Form object, the group box is a container control, since it ‘holds’ other controls. Hence, controls placed in a group box will share BackColor, ForeColor and Font properties. To change this, select the desired control (after it is placed on the group box) and change the desired properties. Another feature of a group box control is that when its Enabled property is False, all controls in the group box are disabled. Likewise, when the group box control Visible property is False, all controls in the group box are not visible.


• As mentioned, group boxes affect how radio buttons work. Radio buttons within a GroupBox control work as a group, independently of radio buttons in other GroupBox controls. Radio buttons on the form, and not in group boxes, work as another independent group. That is, the form is itself a group box by default. We'll see this in the next example.

• GroupBox Properties:

Name Gets or sets the name of the group box (three letter prefix for group box name is grp).
BackColor Get or sets the group box background color.
Enabled Gets or sets a value indicating whether the panel is enabled. If False, all controls in the group box are disabled.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Text Gets or sets string displayed in title region of group box.
Visible If False, hides the group box (and all its controls).

• The GroupBox control has some methods and events, but these are rarely used. We are more concerned with the methods and events associated with the controls in the group box.

• Typical use of GroupBox control:

 Set Name and Text property (perhaps changing Font, BackColor and ForeColor properties).
 Place desired controls in group box. Monitor events of controls in group box using usual techniques.



Panel Control

In Toolbox:



On Form (Default Properties):



• The Panel control is another Visual Basic .NET grouping control. It is nearly identical to the GroupBox control in behavior. The Panel control lacks a Text property (titling information), but has optional scrolling capabilities. Controls are placed in a Panel control in the same manner they are placed in the GroupBox. And, radio buttons in the Panel control act as an independent group.

• Panel Properties:

Name Gets or sets the name of the panel (three letter prefix for panel name is pnl).
AutoScroll Gets or sets a value indicating whether the panel will allow the user to scroll to any controls placed outside of its visible boundaries.
BackColor Get or sets the panel background color.
BorderStyle Get or set the panel border style.
ContextMenu Gets or sets the shortcut menu associated with this panel.
Enabled Gets or sets a value indicating whether the panel is enabled. If False, all controls in the panel are disabled.
Visible If False, hides the panel (and all its controls).

• Like the GroupBox control, the Panel control has some methods and events, but these are rarely used. We only are concerned with the methods and events associated with the controls in the panel.

• Typical use of Panel control:

 Set Name property.
 Place desired controls in panel control.
 Monitor events of controls in panel using usual techniques.




Handling Multiple Events in a Single Event Procedure

• In the few applications we’ve built in this course, each event procedure handles a single event. Now that we are grouping controls like check boxes and radio buttons, it would be nice if a single procedure could handle multiple events. For example, if we have 4 radio buttons in a group, when one button is clicked, it would be preferable to have a single procedure where we decide which button was clicked, as opposed to having to monitor 4 separate event procedures. Let’s see how to do this.

• We use the radio button example to illustrate. Assume we have four radio buttons (RadioButton1, RadioButton2, RadioButton3, RadioButton4). The form for the Click event procedure for RadioButton1 is:

Private Sub RadioButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.Click
.
End Sub

The name assigned to this procedure by Visual Basic .NET (RadioButton1_Click) is arbitrary. We could change it to anything we want and it would still handle the Click event for RadioButton1. Why, you ask?

• The important clause in the procedure structure is the Handles statement:

Handles RadioButton1.Click

This clause assigns the RadioButton1.Click event to this particular procedure. This clause cannot be changed. We can assign additional events to this procedure by appending other control events to the Handles clause. For example, if we want this procedure to also handle the Click event for RadioButton2, we can change the clause to:

Handles RadioButton1.Click, RadioButton2.Click

Then if either of these two radio buttons is clicked, the procedure named RadioButton1_Click will be invoked.

• The Handles clause allows us to attach any event of any control to any procedure we want! It is best to append like events of like controls. It is possible to process dissimilar events of dissimilar controls with a single event procedure, but you need to be careful.

• Let’s complete the example we’ve been doing and add the remaining two radio buttons (RadioButton3 and RadioButton4) to the event procedure. While we’re at it, we’ll rename the event procedure (new name is MyButtons_Click) to clear up any possible misunderstanding of the name. The code GroupBoxwork that does this is:

Private Sub MyButtons_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadioButton1.Click, RadioButton2.Click, RadioButton3.Click, RadioButton4.Click
.
End Sub

• If we have a single procedure responding to events from multiple controls, how do we determine which particular event from which particular control invoked the procedure. In our example with a single procedure handling the Click event for 4 radio buttons, how do we know which of the 4 buttons was clicked to enter the procedure? The sender argument of the event procedure provides the answer.

• Each event procedure has a sender argument (the first argument of two) which identifies the control whose event caused the procedure to be invoked. With a little BASIC coding, we can identify the Name property (or any other needed property) of the sending control. For our radio button example, that code is:

Dim rdoExample As RadioButton
Dim ButtonName As String
'Determine which button was clicked
rdoExample = CType(sender, RadioButton)
ButtonName = rdoExample.Name

In this code, we define a variable (rdoExample) to be the type of the control attached to the procedure (a RadioButton in this case). Then, we assign this variable to sender (after converting sender to the proper control type). Once this variable is established, we can determine any property we want. In the above example, we find the radio button’s Name property. With this information, we now know which particular button was clicked and we can process any code associated with clicking on this radio button.


Control Arrays

• When using controls that work in groups, like check boxes and radio buttons, it is sometimes desirable to have someway to quickly process every control in that group. A concept of use in this case is that of a control array.

• In the last chapter, we learned about variable arrays – variables referred by name and index to allow quick processing of large amounts of data. The same idea applies here. We can define an array of controls, using the same statements used to declare a variable array. For example, to declare an array of 20 buttons, use:

Dim MyButtons(20) As Button

Actually, there are 21 buttons since indices start at 0 and go to 20. This array declaration is placed according to desired scope, just like variables. For form level scope, place the statement at the top of the form code. For procedure level scope, place it in the respective procedure. Once the array has been declared, each element of the ‘control array’ can be referred to by its name (MyButton) and index. An example will clarify the advantage of such an approach.

• Say we have 10 check boxes (chkBox01, chkBox02, chkBox03, chkBox04, chkBox05, chkBox06, chkBox07, chkBox08, chkBox09, chkBox10) on a form and we need to examine each check box’s Checked property. If that property is True, we need to process 30 lines of additional code. For one check box, that code would be:

If chkBox01.Checked Then
[do these 30 lines of code]
End If

We would need to repeat this 9 more times (for the nine remaining check boxes), yielding a total of 32 x 10 = 320 lines of code. And, if we needed to add a few lines to the code being processed, we would need to add these lines in 10 different places – a real maintenance headache. Let’s try using an array of check boxes to minimize this headache.


• Here’s the solution. Define an array of 10 checkbox controls and assign the array values to existing controls:

Dim CheckBoxes(10) As CheckBox
MyCheck(1) = chkBox01
MyCheck(2) = chkBox02
MyCheck(3) = chkBox03
MyCheck(4) = chkBox04
MyCheck(5) = chkBox05
MyCheck(6) = chkBox06
MyCheck(7) = chkBox07
MyCheck(8) = chkBox08
MyCheck(9) = chkBox09
MyCheck(10) = chkBox10

Again, make sure the declaration statement is properly located for proper scope. Having made these assignments, the code for examining the Checked property of each has been reduced to these few lines:

Dim I As Integer
.
.
For I = 1 To 10
If MyCheck(I).Checked Then
[do these 30 lines of code]
End If
Next I

The 320 lines of code have been reduced to about 45 (including all the declarations) and code maintenance is now much easier.

• Obviously, it is not necessary to use control arrays, but they do have their advantages. You will start to see such arrays in the course examples and problems, so you should understand their use.

Example 3-2

Pizza Order

1. Start a new project. We'll build a form where a pizza order can be entered by simply clicking on check boxes and radio buttons.

2. Draw three group boxes. In the first, draw three radio buttons, in the second, draw two radio buttons, and in the third, draw six check boxes. Draw two radio buttons on the form. Add two buttons. Make things look something like this.



3. Set the properties of the form and each control.

Form1:
Name frmPizza
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Pizza Order

GroupBox1:
Text Size

GroupBox2:
Text Crust Type


GroupBox3
Text Toppings

RadioButton1:
Name rdoSmall
Checked True
Text Small

RadioButton2:
Name rdoMedium
Text Medium

RadioButton3:
Name rdoLarge
Text Large

RadioButton4:
Name rdoThin
Checked True
Text Thin Crust

RadioButton5:
Name rdoThick
Text Thick Crust

RadioButton6:
Name rdoIn
Checked True
Text Eat In

RadioButton7:
Name rdoOut
Text Take Out

CheckBox1:
Name chkCheese
Text Extra Cheese

CheckBox2:
Name chkMushrooms
Text Mushrooms


CheckBox3:
Name chkOlives
Text Black Olives

CheckBox4:
Name chkOnions
Text Onions

CheckBox5:
Name chkPeppers
Text Green Peppers

CheckBox6:
Name chkTomatoes
Text Tomatoes

Button1:
Name btnBuild
Text &Build Pizza

Button2:
Name btnExit
Text E&xit

The form should look like this now:




4. Form level scope variable declarations:

Dim PizzaSize As String
Dim PizzaCrust As String
Dim PizzaWhere As String
Dim Topping(6) As CheckBox

This makes the size, crust, and location variables global to the form. The array of check box controls will help us determine which toppings are selected. As mentioned in the notes, it is common to use ‘control arrays’ when working with check boxes and radio buttons.

5. Use this code in the Form_Load procedure. This initializes the pizza size, crust, eating location and topping controls.

Private Sub frmPizza_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Initialize parameters
PizzaSize = rdoSmall.Text
PizzaCrust = rdoThin.Text
PizzaWhere = rdoIn.Text
'Define an array of topping check boxes
Topping(1) = chkCheese
Topping(2) = chkMushrooms
Topping(3) = chkOlives
Topping(4) = chkOnions
Topping(5) = chkPeppers
Topping(6) = chkTomatoes
End Sub

Here, the form level variables are initialized to their default values, corresponding to the default radio buttons. The Topping variables are set to their values.

6. Use this code to define single Click events for each of the three groups of radio buttons:

Private Sub rdoSize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoSmall.Click, rdoMedium.Click, rdoLarge.Click
Dim rdoSize As RadioButton
'Determine which button was clicked and change size
rdoSize = CType(sender, RadioButton)
PizzaSize = rdoSize.Text
End Sub


Private Sub rdoCrust_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdoThin.Click, rdoThick.Click
Dim rdoCrust As RadioButton
'Determine which button was clicked and change crust
rdoCrust = CType(sender, RadioButton)
PizzaCrust = rdoCrust.Text
End Sub

Private Sub rdoWhere_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rdoIn.Click, rdoOut.Click
Dim rdoWhere As RadioButton
'Determine which button was clicked and change where
rdoWhere = CType(sender, RadioButton)
PizzaWhere = rdoWhere.Text
End Sub

In each of these routines, when an radio button is clicked, the value of the corresponding button’s Text is loaded into the respective variable.

7. Use this code in the btnBuild_Click event.

Private Sub btnBuild_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBuild.Click
'This procedure builds a message box that displays your pizza type
Dim Message As String
Dim I As Integer
Message = PizzaWhere + ControlChars.Cr
Message += PizzaSize + " Pizza" + ControlChars.Cr
Message += PizzaCrust + ControlChars.Cr
'Check each topping using the array we set up
For I = 1 To 6
If Topping(I).Checked Then
Message += Topping(I).Text + ControlChars.Cr
End If
Next I
MessageBox.Show(Message, "Your Pizza", MessageBoxButtons.OK)
End Sub


This code forms the first part of a message for a message box by concatenating the pizza size, crust type, and eating location (recall ControlChars.Cr is a constant representing a ‘carriage return’ that puts each piece of ordering information on a separate line). Next, the code cycles through the six topping check boxes (defined by our Topping array) and adds any checked information to the message. The code then displays the pizza order in a message box.

8. Use this code in the btnExit_Click event.

Private Sub btnExit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub

9. Get the application working. Notice how the different selection buttons work in their individual groups. Save your project (saved in Example 3-2 folder in the LearnVBN\VBN Code\Class 3 folder).

If you have time, try these modifications:

A. Add a new program button that resets the order form to the initial default values. You’ll have to reinitialize the three global variables, reset all check boxes to unchecked, and reset all three radio button groups to their default values.

B. Modify the code so that if no toppings are selected, the message “Cheese Only” appears on the order form. You’ll need to figure out a way to see if no check boxes were checked.

ListBox Control

In Toolbox:



On Form (Default Properties):



• Check boxes are useful controls for selecting items from a list. But, what if your list has 100 items? Do you want 100 check boxes? No, but fortunately, there is a tool that solves this problem. A Listbox control displays a list of items (with as many items as you like) from which the user can select one or more items. If the number of items exceeds the number that can be displayed, a scroll bar is automatically added. Both single item and multiple item selections are supported.

• ListBox Properties:

Name Gets or sets the name of the list box (three letter prefix for list box name is lst).
BackColor Get or sets the list box background color.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the list box.
SelectedIndex Gets or sets the zero-based index of the currently selected item in a list box.
SelectedIndices Zero-based array of indices of all currently selected items in the list box.
SelectedItem Gets or sets the currently selected item in the list box.
SelectedItems SelectedItems object of the list box.
SelectionMode Gets or sets the method in which items are selected in list box (allows single or multiple selections).

ListBox Properties (continued)

Sorted Gets or sets a value indicating whether the items in list box are sorted alphabetically.
Text Text of currently selected item in list box.
TopIndex Gets or sets the index of the first visible item in list box.

• ListBox Methods:

ClearSelected Unselects all items in the list box.
FindString Finds the first item in the list box that starts with the specified string.
GetSelected Returns a value indicating whether the specified item is selected.
SetSelected Selects or clears the selection for the specified item in a list box.

• ListBox Events:

SelectedIndexChanged Occurs when the SelectedIndex property has changed.

• Some further discussion is need to use the list box Items object, SelectedItems object and SelectionMode property. The Items object has its own properties to specify the items in the list box. It also has its own methods for adding and deleting items in the list box. Two properties of use: Item is a zero-based array of the items in the list and Count is the number of items in the list. Hence, the first item in a list box named lstExample is:

lstExample.Items.Item(0)

The last item in the list is:

lstExample.Items.Item(lstExample.Items.Count - 1)

The minus one is needed because of the zero-based array.


• To add an item to a list box, use the Add method, to delete an item, use the Remove method and to clear a list box use the Clear method. For our example list box, the respective commands are:

Add Item: lstExample.Items.Add(ItemToAdd)
Delete Item: lstExample.Items.Remove(IndexOfItem)
Clear list box: lstExample.Items.Clear

List boxes normally list string data types, though other types are possible.

• In a similar fashion, the SelectedItems object has its own properties to specify the currently selected items in the list box Of particular use is Count which tells you how many items are selected. This value, in conjunction with the SelectedIndices array, identifies the set of selected items.

• The SelectionMode property specifies whether you want single item selection or multiple selections. When the property is SelectionMode.One, you can select only one item (works like a group of option buttons). When the SelectionMode property is set to SelectionMode.MultiExtended, pressing and clicking the mouse or pressing and one of the arrow keys extends the selection from the previously selected item to the current item. Pressing and clicking the mouse selects or deselects an item in the list. When the property is set to SelectionMode.MultiSimple, a mouse click or pressing the spacebar selects or deselects an item in the list.

• The CheckedListBox is a nearly identical control in Visual Basic .NET. The only difference is, with the CheckedListBox, a check mark appears before selected items. Other than that, performance is identical to the ListBox control.

• Typical use of ListBox control:

 Set Name property, SelectionMode property and populate Items object (usually in Form_Load procedure).
 Monitor SelectedIndexChanged event for individual selections.
 Use SelectedIndex and SelectIndices properties to determine selected items.


ComboBox Control

In Toolbox:



On Form (Default Properties):



• The ListBox control is equivalent to a group of check boxes (allowing multiple selections in a long list of items). The equivalent control for a long list of radio buttons is the ComboBox control. The ComboBox allows the selection of a single item from a list. And, in some cases, the user can type in an alternate response.

• ComboBox Properties:

ComboBox properties are nearly identical to those of the ListBox, with the deletion of the SelectionMode property and the addition of a DropDownStyle property.

Name Gets or sets the name of the combo box (three letter prefix for combo box name is cbo).
BackColor Get or sets the combo box background color.
DropDownStyle Specifies one of three combo box styles.
Font Gets or sets font name, style, size.
ForeColor Gets or sets color of text.
Items Gets the Items object of the combo box.
MaxDropDownItems Maximum number of items to show in dropdown portion.
SelectedIndex Gets or sets the zero-based index of the currently selected item in list box portion.
SelectedItem Gets or sets the currently selected item in the list box portion.
SelectedText Gets or sets the text that is selected in the editable portion of combo box.
Sorted Gets or sets a value indicating whether the items in list box portion are sorted alphabetically.

• ComboBox Events:

KeyPress Occurs when a key is pressed while the combo box has focus.
SelectedIndexChanged Occurs when the SelectedIndex property has changed.

• The Items object for the ComboBox control is identical to that of the ListBox control. You add and delete items in the same manner and values are read with the same properties.

• The DropDownStyle property has three different values. The values and their description are:

Value Description
DropDown Text portion is editable; drop-down list portion.
DropDownList Text portion is not editable; drop-down list portion.
Simple The text portion is editable. The list portion is always visible. With this value, you’ll want to resize the control to set the list box portion height.

• Typical use of ComboBox control:

 Set Name property, DropDownStyle property and populate Items object (usually in Form_Load procedure).
 Monitor SelectedIndexChanged event for individual selections.
 Read SelectedText property to identify choice.


Example 3-3

Flight Planner

1. Start a new project. In this example, you select a destination city, a seat location, and a meal preference for airline passengers.

2. Place a list box, two combo boxes, three labels and two buttons on the form. The form should appear similar to this:



3. Set the form and object properties:

Form1:
Name frmFlight
FormBorderStyle FixedSingle
StartPosition CenterScreen
Text Flight Planner

ListBox1:
Name lstCities
Sorted True

ComboBox1:
Name cboSeat
DropDownStyle DropdownList


ComboBox2:
Name cboMeal
DropDownStyle Simple
Text [Blank]

(You’ll want to resize this control after setting properties).

Label1:
Text Destination City

Label2:
Text Seat Location

Label3:
Text Meal Preference

Button1:
Name btnAssign
Text &Assign

Button2:
Name btnExit
Text E&xit

Now, the form should look like this:




4. Use this code in the Form_Load procedure:

Private Sub frmPlanner_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Add city names to list box
lstCities.Items.Clear()
lstCities.Items.Add("San Diego")
lstCities.Items.Add("Los Angeles")
lstCities.Items.Add("Orange County")
lstCities.Items.Add("Ontario")
lstCities.Items.Add("Bakersfield")
lstCities.Items.Add("Oakland")
lstCities.Items.Add("Sacramento")
lstCities.Items.Add("San Jose")
lstCities.Items.Add("San Francisco")
lstCities.Items.Add("Eureka")
lstCities.Items.Add("Eugene")
lstCities.Items.Add("Portland")
lstCities.Items.Add("Spokane")
lstCities.Items.Add("Seattle")
lstCities.SelectedIndex = 0
'Add seat types to first combo box
cboSeat.Items.Add("Aisle")
cboSeat.Items.Add("Middle")
cboSeat.Items.Add("Window")
cboSeat.SelectedIndex = 0
'Add meal types to second combo box
cboMeal.Items.Add("Chicken")
cboMeal.Items.Add("Mystery Meat")
cboMeal.Items.Add("Kosher")
cboMeal.Items.Add("Vegetarian")
cboMeal.Items.Add("Fruit Plate")
cboMeal.Text = "No Preference"
End Sub

This code simply initializes the list box and the list box portions of the two combo boxes.


5. Use this code in the btnAssign_Click event:

Private Sub btnAssign_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAssign.Click
'Build message box that gives your assignment
Dim Message As String
Message = "Destination: " + lstCities.Text + ControlChars.Cr
Message += "Seat Location: " + cboSeat.Text + ControlChars.Cr
Message += "Meal: " + cboMeal.Text + ControlChars.Cr
MessageBox.Show(Message, "Your Assignment", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub

When the Assign button is clicked, this code forms a message box message by concatenating the selected city (from the list box lstCities), seat choice (from cboSeat), and the meal preference (from cboMeal).

6. Use this code in the btnExit_Click event:

Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub

7. Run the application. Save the project (saved in Example3-3 folder in LearnVBN\VBN Code\Class 3 folder).



Class Review

• After completing this class, you should understand:

 How to use the MessageBox dialog assigning messages, icons and buttons
 Useful properties, events, and methods for the form, button, text box, label, check box, and radio button controls
 Where the above listed controls can and should be used
 How GroupBox and Panel controls are used to group controls, particularly radio buttons
 How several events can be handled by a single event procedure
 The concept of ‘control arrays’ and how to use them
 How to use list box and combo box controls




Practice Problems 3

Problem 3-1. Message Box Problem. Build an application that lets you see what various message boxes look like. Allow selection of icon, buttons displayed, default button, and input message. Provide feedback on button clicked on displayed message box.

Problem 3-2. Tray Problem. Here’s a sheet of cardboard (L units long and W units wide). A square cut X units long is made in each corner:













If you cut out the four shaded corners and fold the resulting sides up along the dotted lines, a tray is formed. Build an application that lets a user input the length (L) and width (W). Have the application decide what value X should be such that the tray has the largest volume possible.

Problem 3-3. List Box Problem. Build an application with two list boxes. Select items from one box. Click a button to move selected items to the other list box. If you then double-click an item in the second list box, have it return to the first box.

Problem 3-4. Combo Box Problem. Build an application with a Simple style combo box. Populate with some kind of information. If the user decides to type in their own selection (that is, they don’t choose one of the listed items), add that new item to the list box portion of the combo box.


Exercise 3

Customer Database Input Screen

A new sports store wants you to develop an input screen for its customer database. The required input information is:

1. Name
2. Age
3. City of Residence
4. Sex (Male or Female)
5. Activities (Running, Walking, Biking, Swimming, Skiing and/or In-Line Skating)
6. Athletic Level (Extreme, Advanced, Intermediate, or Beginner)

Set up the screen so that only the Name and Age (use text boxes) and, perhaps, City (use a combo box) need to be typed; all other inputs should be set with check boxes and radio buttons. When a screen of information is complete, display the summarized profile in a message box. This profile message box should resemble this: