The Testing Department is calling again, and they're telling you to get rid of all the beautiful buttons that you've placed on the main form of your program. But, you say, it's a program that lets the user buy computer parts. We have to list what computer parts are available. That's just it, they say: A list should go in a list box.
So you've added your list box by dragging it from the toolbox, and now it's staring at you: a blank white box. How do you add items to the list box?
You can add items to a list box at either design time or at run time; the first item will have index 0, the next index 1, and so on in the list box. At design time, you can use the Items property, which is a very handy array of the items in the list box, and at run time, you can use both the Items property and the Add (formerly AddItem) method.
How do you keep track of the total number of items in a list box? You use the Items.Count property; that is, if you loop over the items in the control, you'll use Items.Count as the maximum value to loop to. You can access items individually in a list box by index using the Items property, like this: strText = ListBox1.Items(5).
At design time, you can add items directly to your list box by typing them into the Items property in the Properties window. Selecting the Items property displays the String Collection Editor, which you can see in Figure 7.5, and you can type item after item into the list box that way.
At run time, you either can use the indexed Items property as detailed above, or the Items property's Add or Insert methods this way. Here's an example from the ListBoxes example on the CD-ROM. In this case, I'm using the Add method to add items to a list box at run time. To see this code work, click the "Fill list box" button in the example:
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ListBox1.BeginUpdate() Dim intLoopIndex As Integer For intLoopIndex = 1 To 20 ListBox1.Items.Add("Item " & intLoopIndex.ToString()) Next intLoopIndex ListBox1.EndUpdate() End Sub
Running the above code gives us the list box in Figure 7.6.
Note that when you place items in a list box, they are stored by index, and you can refer to them by their index with the List property. When you use the Insert method, you can specify the index location at which to insert an item, like this: ComboBox1.Items.Insert (3, "Item 3").
You also can use the AddRange method to add a collection of objects to a list box all at once; here's an example where I'm adding an array of strings to a list box all at once:
Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim DataArray(4) As String Dim intLoopIndex As Integer For intLoopIndex = 0 To 4 DataArray(intLoopIndex) = New String("Item " & intLoopIndex) Next intLoopIndex ListBox1.Items.AddRange(DataArray) End Sub