Form_Load event

A programmer often wants to initialize variables or do other work (for example, create new data files) as soon as a program begins execution -- before the user has a chance to do anything. That can be done using a Form_Load event handler.

In our ListBox example, we initialized the Item collection (the alternative adjectives) at design time. Alternatively, we could have initialized the Item collection at execution time using the Add method of the Item collection.

Since we would like the Item collection to be initialized before the user has a chance to do anything, we initialize it in the Form_Load event handler. By the time the form finishes loading, the Item collection will have been set up. The listing of the Form_Load event handler would be:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
   lbxAdj.Items.Add("cute")
   lbxAdj.Items.Add("loveable")
   lbxAdj.Items.Add("beautiful")
   lbxAdj.Items.Add("yummy")
   lbxAdj.Items.Add("handsome")
   lbxAdj.Items.Add("intelligent")
   lbxAdj.Items.Add("strong")
   lbxAdj.Items.Add("fine")
End Sub

Note that the button_click event is the same regardless of whether the Items are initialized at design or run time:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
   lblOut.Text = "You are so " & lbxAdj.SelectedItem & "!!"
End Sub

Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.