As we know that we can use ListBox control as Single select or multiple select. If use single selection mode of the control then we can find out the selected item through SelectedIndex and SelectedItemproperties. if we use Multiple selection mode of the items then how we can find out the selected items, in the following examples we are showing how we can do this:
Find selected items from Single select ListBox:
- <script runat="server">
- Sub Page_Load()
- Label1.Text = ""
- End Sub
- Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
- Label1.Text = "Selected Item: " & ListBox1.SelectedItem.Text
- End Sub
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Create multiselect listBox</title>
- </head>
- <body style="height: 410px; width: 768px">
- <form runat="server">
- <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" >
- <asp:ListItem Text="USA" />
- <asp:ListItem Text="India" />
- <asp:ListItem Text="Japan" />
- <asp:ListItem Text="UK" />
- </asp:ListBox>
- <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button_Click" />
- <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
- </form>
- </body>
- </html>
Find selected items from Multiselect ListBox:
- <script runat="server">
- Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
- Dim stritems As String = ""
- For Each lstitem As ListItem In ListBox1.Items
- If lstitem.Selected Then
- stritems = stritems & ", " & lstitem.Text
- End If
- Next
- Label1.Text = "Selected Items: " & stritems
- End Sub
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Create multiselect listBox</title>
- </head>
- <body style="height: 410px; width: 768px">
- <form runat="server">
- <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" >
- <asp:ListItem Text="USA" />
- <asp:ListItem Text="India" />
- <asp:ListItem Text="Japan" />
- <asp:ListItem Text="UK" />
- </asp:ListBox>
- <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button_Click" />
- <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
- </form>
- </body>
- </html>