|
ListBox
The ListBox Web server control displays a list of items from which we can make a selection.
We can select one or more items from the list of items displayed. The class hierarchy
for this control is as follows:
Object
Control
WebControl
ListControl
ListBox
ListBox Event
The default event of the list box is the SelectedIndexChanged which
looks like this is code:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles ListBox1.SelectedIndexChanged
'Implementation Omitted
End Sub
|
Notable Properties of the ListBox are as follows:
Items: Gets/Sets the collection of items in the control
Rows: Gets/Sets the number of rows in the list box
SelectionMode: Gets/Sets the list box's selection mode,
can be set to single or multiple
ListBox Samples
Single Selection ListBox
Drag a ListBox, Button and a TextBox control on to the form. Add some items to
the ListBox using the Items property. The following lines of code will display the
item you select from the list box in a textbox when the button is clicked.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
TextBox1.Text = "You Selected" & " " & ListBox1.SelectedItem.Text
End Sub
|
Multiple Selection ListBox
Modifying the above sample to make the ListBox allow us to select multiple
items, select the ListBox and in it's properties window set the SelectionMode proeprty
to Multiple. The following lines of code will display the selected items in the textbox
when the button is clicked:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_
System.EventArgs) Handles Button1.Click
Dim i As Integer
TextBox1.Text = "You Selected" & " "
For i = 0 To ListBox1.Items.Count - 1
If ListBox1.Items(i).Selected Then
TextBox1.Text = TextBox1.Text & ListBox1.Items(i).Text & " "
End If
Next
End Sub
|
Live Code Demo
Single Selection ListBox
Multiple Selection Listbox
|