ListBox control contains list of options. We can create ListBox with single option select and multiple option select functionality. We can add a list of option or items in these ways:
At the time declaration:
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>AutoPostBack property of ListBox</title>
- </head>
- <body style="height: 410px; width: 768px">
- <form runat="server">
- <asp:ListBox ID="ListBox1" runat="server">
- <asp:ListItem Text="USA" Value="1" />
- <asp:ListItem Text="India" Value="2" />
- <asp:ListItem Text="Japan" Value="3" />
- </asp:ListBox>
- </form>
- </body>
- </html>
Add items directly to the Item collection:
- <script runat="server">
- Sub Page_Load()
- ListBox1.Items.Add("USA")
- ListBox1.Items.Add("India")
- ListBox1.Items.Add("Japan")
- ListBox1.Items.Add("UK")
- End Sub
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Add items directly to the Item collection</title>
- </head>
- <body style="height: 410px; width: 768px">
- <form runat="server">
- <asp:ListBox ID="ListBox1" runat="server">
- </asp:ListBox>
- </form>
- </body>
- </html>
And in the last if you want to bind control to a DataSource, for example:
In the following example first we create a array list and then we assign this array list to datasource property of ListBox control:
- <script runat="server">
- Sub Page_Load()
- Dim arrList As New ArrayList
- arrList.Add("USA")
- arrList.Add("India")
- arrList.Add("Japan")
- ListBox1.DataSource = arrList
- ListBox1.DataBind()
- End Sub
- </script>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Add items directly to the Item collection</title>
- </head>
- <body style="height: 410px; width: 768px">
- <form runat="server">
- <asp:ListBox ID="ListBox1" runat="server">
- </asp:ListBox>
- </form>
- </body>
- </html>