Sometimes, you will come across a need to select multiple items from a ListBox. This code example shows how to create a multi-select Listbox, and also how to iterate through the item collection to retrieve the text values of the selected items.
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.0">
<title>Listbox – Selecting Multiple Items</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
with listbox1.items
.add ("Cherry")
.add ("Vanilla")
.add ("Strawberry")
.add ("Chocolate")
.add ("Banana")
.add ("Apple")
end with
end if
End Sub
Sub doList(Source as Object, E as EventArgs)
Dim Stuff As String
Dim Item As ListItem
For Each Item In ListBox1.Items
If Item.Selected Then
Stuff = Stuff & Item.Text & "<br>"
End If
Next
If Stuff <> "" Then
Label1.Text = "<b>You chose :</b> <br>" & Stuff
Else
Label1.Text = "<b>Hey – Nothing was chosen!</b> "
End If
End Sub
</script>
</head>
<body>
<Form id="form1" runat="server">
<asp:ListBox id="Listbox1"
Height="125px"
width="100px" SelectionMode="Multiple"
runat="server" />
<asp:Button id="button1" Text="Get Items" onclick="doList" runat="server" /><br>
<asp:Label ID="label1" runat="server" />
</Form>
</body>
</html>