In one of the forums, a user recently asked how to select multiple items of an ASP.NET ListBox. Here’s how
<div>
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem Value="One" />
<asp:ListItem Value="Two" />
<asp:ListItem Value="Three" />
<asp:ListItem Value="Four" />
<asp:ListItem Value="Five" />
</asp:ListBox>
</div>
C#
protected void Page_Load(object sender, EventArgs e)
{
ListBox1.SelectionMode = ListSelectionMode.Multiple;
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if(i == 0 || i == 2 || i == 4)
{
ListBox1.Items[i].Selected = true;
}
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
ListBox1.SelectionMode = ListSelectionMode.Multiple
For i As Integer = 0 To ListBox1.Items.Count - 1
If i = 0 OrElse i = 2 OrElse i = 4 Then
ListBox1.Items(i).Selected = True
End If
Next i
End Sub
The code shown above selects the first, third and fifth items of a ListBox as in the screenshot below
c# code sample is busted (if statement)
ReplyDeleteThanks rptHarry! Its fixed now
ReplyDeleteHandy. Can i also get list of selected items using pure LINQ?
ReplyDeleteJukeBox: I quickly created a sample and put it over here
ReplyDeleteRetrieve Selected Items of an ASP.NET ListBox using LINQ
HTH
Hi ,
ReplyDeleteI want to get the selected items from list box(multiple items) and need to store it on collection.
List aa = new List();
foreach (ListBoxItem Li in lstUnit.SelectedItems)
{
aa.Add(Li.Name);
}
I was trying with this coede and not able to get it ,could any body help it out.