ListBox Server Control
ListBox control is used same as DropDownList Control. It also displays collection of items. Where as the difference is in DropDown you can select only one item here in the ListBox control you can select One or more items.
ListBox code when user can select single item
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem>ASP.NET</asp:ListItem>
<asp:ListItem>C#.NET</asp:ListItem>
<asp:ListItem>VB.NET</asp:ListItem>
<asp:ListItem>JAVASCRIPT</asp:ListItem>
</asp:ListBox>
ListBox code when user can select multiple items by using “selectionmode” property. Use Control button on your keyboard to select multiple items
<asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
<asp:ListItem>ASP.NET</asp:ListItem>
<asp:ListItem>C#.NET</asp:ListItem>
<asp:ListItem>VB.NET</asp:ListItem>
<asp:ListItem>JAVASCRIPT</asp:ListItem>
</asp:ListBox>
Let’s see small example on this ListBox with C# coding.
.aspx
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server">
</asp:ListBox>
<br />
<br />
<asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
<asp:ListItem>ASPNET</asp:ListItem>
<asp:ListItem>C#NET</asp:ListItem>
<asp:ListItem>VBNET</asp:ListItem>
<asp:ListItem>JAVASCRIPT</asp:ListItem>
</asp:ListBox>
<br />
<br />
<asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
.cs
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Add(TextBox1.Text);
}
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = "You selected from the ListBox:<br>";
foreach(ListItem li in ListBox2.Items)
{
if (li.Selected)
{
Label1.Text += li + "<br>";
}
}
}
Requirement can be like, if you select listbox item automatically the event should call for this we use AutoPostback=true and SelectedIndexCnaged event as shown below.
.aspx
<asp:ListBox ID="ListBox3" runat="server" SelectionMode="Multiple"
AutoPostBack="true" onselectedindexchanged="ListBox3_SelectedIndexChanged">
<asp:ListItem>ASPNET</asp:ListItem>
<asp:ListItem>C#NET</asp:ListItem>
<asp:ListItem>VBNET</asp:ListItem>
<asp:ListItem>JAVASCRIPT</asp:ListItem>
</asp:ListBox>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<br />
<br />
.cs
protected void ListBox3_SelectedIndexChanged(object sender, EventArgs e)
{
Label2.Text = "You selected from the ListBox:<br>";
foreach (ListItem li in ListBox3.Items)
{
if (li.Selected)
{
Label2.Text += li + "<br>";
}
}
}
No comments:
Post a Comment