Page 63 - Open Soource Technologies 304.indd
P. 63
Unit 3: Understanding Controls and Control Events
Sorted: Default value is set to False. Set it to True if you want the items displayed in the ListBox
to be sorted by alphabetical order.
3.4.6.1.2 In the Data Section
Notable property in the Data section of the Properties window is the Items property. The Items
property allows us to add the items we want to be displayed in the list box. Doing so is simple,
click on the ellipses to open the String Collection Editor window and start entering what you
want to be displayed in the ListBox. After entering the items click OK and doing that adds all
the items to the ListBox.
3.4.6.2 ListBox Event
The default event of ListBox is the SelectedIndexChanged which looks like this in code:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As
System.Object, _
ByVal e As System.EventArgs) Handles
ListBox1.SelectedIndexChanged
End Sub
3.4.6.3 Working with ListBoxes
Drag a TextBox and a ListBox control to the form and add some items to the ListBox with it's
items property.
Referring to Items in the ListBox
Items in a ListBox are referred by index. When items are added to the ListBox they are assigned
an index. The first item in the ListBox always has an index of 0 the next 1 and so on.
Code to display the index of an item
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
TextBox1.Text = ListBox1.SelectedIndex
'using the selected index property of the list box to select the index
End Sub
When you run the code and select an item from the ListBox, it's index is displayed in the textbox.
Counting the number of Items in a ListBox
Add a Button to the form and place the following code in it's click event.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles Button1.Click
TextBox1.Text = ListBox1.Items.Count
'counting the number of items in the ListBox with the Items.Count
End Sub
LOVELY PROFESSIONAL UNIVERSITY 57