Now you've created your new list box, and it's a beauty. The boss is very pleased with it when you show your new program at the company's expo. The boss clicks the list box with the mouse—and nothing happens. The boss asks: Didn't you connect that list box to code? Oh, you think.
You can use the SelectedIndexChanged event, which is the default event for list boxes, to handle the case where the selected item changes in a list box. In the ListBoxes example on the CD-ROM, I indicate which item was clicked in the list box using this event (adding one to the item's index, which is 0-based), like this:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As _ System.Object, ByVal e As System.EventArgs) Handles _ ListBox1.SelectedIndexChanged TextBox1.Text = "You selected item " & ListBox1.SelectedIndex + 1 End Sub
You can see the results in Figure 7.7; in that figure, I've clicked Item 6 in the list box, which the code reports in the text box as you see.
You also can use Click and DoubleClick with list boxes. How you actually use them is up to you, because different programs have different needs. For example, if a list box sets a new font which doesn't become active until a font chooser dialog box is closed, it's fine to respond to the Click event to display a sample of the font the user has selected in text box. On the other hand, if you display the names of programs to launch in a text box, you should probably launch a program only after a user double-clicks it in the list box to avoid mistakes.
You can use the Click event just much as you'd use the Click event in a button, with a Click event handler. Here, I'll display the index of the item in the list box the user has clicked:
Private Sub ListBox1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles ListBox1.Click TextBox1.Text = ListBox1.SelectedIndex End Sub
And it's the same for DoubleClick— you just add a DoubleClick handler with the code you want:
Private Sub ListBox1_DoubleClick(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles ListBox1.DoubleClick TextBox1.Text = ListBox1.SelectedIndex End Sub
A DoubleClick event also triggers the Click event, because to double-click an item, you must first click it.