Thursday, 3 May 2012

Beginning .Net , C# Tips : Get multiple selected items from listbox using LINQ

If you want to get multiple selected items from listbox without using FOR loop using LINQ you can achieve that.

Here are sample Example For this:
C# Example :
System.Web.UI.WebControls.ListBox lst = new System.Web.UI.WebControls.ListBox();
lst.Items.Add(new ListItem("C# Programming", "1"));
lst.Items.Add(new ListItem("VB.Net Programming", "2"));
lst.Items.Add(new ListItem("SQL Server", "3"));
lst.SelectionMode = ListSelectionMode.Multiple;
lst.Items[0].Selected = true;
lst.Items[2].Selected = true;
List<ListItem> selectedItems = (from li in lst.Items.Cast<ListItem>() where li.Selected == true select li).ToList<ListItem>();

VB.net Example :
Dim lst As New System.Web.UI.WebControls.ListBox
lst.Items.Add(New ListItem("C# Programming", "1"))
lst.Items.Add(New ListItem("VB.Net Programming", "2"))
lst.Items.Add(New ListItem("SQL Server", "3"))
lst.SelectionMode = ListSelectionMode.Multiple
lst.Items(0).Selected = True
lst.Items(2).Selected = True
Dim selectedItems As List(Of ListItem) = (From li In lst.Items.Cast(Of ListItem)() Where li.Selected = True Select li).ToList()

No comments:

Post a Comment