Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 3: User Interface Design: Visual Basic Controls and Events
Last change: February 13 2016 18:47:26.

Setting the Initial State at Runtime: The Form Load Event

In many cases, when your program starts and before the computer shows your form, you want certain controls and variables to be in a specific state. For example, you may want to populate a list box with data that are not available until run time. Or, you may want a combo box to show an initial choice. In what event should you place the code for this purpose? It is the Form Load event.
The Form Load event occurs when the form is loaded into the memory and before the form is displayed. At this stage, all the controls’ properties are set to their initial states; that is, their default settings or the settings that you made for them during design time. You may want to change some of these settings so that the controls will appear the way you want when the form first appears. Imagine that your form has a combo box named cboWeekdays with its list set at design time to Sunday, Monday, and so on. You would like for this box to show Sunday (the first element in its list) as soon as the program starts. How can you do this?
First, recall that one way to set a desired selection for the list box is to assign a proper value to its SelectedIndex. You can do the same for the combo box. Because Sunday is the first position in the list, you can assign 0 to that property. (Again, recall that the first item has an index value of 0.) The code should appear as:

cboWeekDays.SelectedIndex = 0

So where should this line go? Because you want to show the setting as soon as the program starts, the code should be placed in the Form Load event. The complete code should appear as:

Private Sub Form1_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cboWeekDays.SelectedIndex = 0 End Sub

You might be tempted to code the preceding described requirement as follows:
cboWeekDays.Text = “Sunday”
This line of code may not always work, however. When the DropDownStyle is set to DropDownList, the Text property will be read-only and cannot be set by direct assignment. In this case, you can make the combo box display the desired text only by setting the SelectedIndex property.
Last change: February 13 2016 18:47:28.