Monday, August 17, 2009

Get Selected Items From Multiple ASP.NET ListBox and Merge them using LINQ

A few questions floating around on the forums is how to get the selected items from two different list boxes and merge them into one result. LINQ is a good technology to handle this. Here's the code to do this in LINQ.

Add two list boxes to your page:
























And here is the LINQ query

C#

var query = from p in ListBox1.Items.OfType()
.Concat(ListBox2.Items.OfType())
.Where(o => o.Selected)
select new
{
Text = p.Text
};

foreach (var item in query)
{
// print item
}

VB.NET

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button1.Click
Dim query = From p In ListBox1.Items.OfType(Of ListItem)() _
.Concat(ListBox2.Items.OfType(Of ListItem)()) _
.Where(Function(o) o.Selected) _
Select New With {Key .Text = p.Text}

For Each item In query
' Print item.Text
Next item

End Sub

Thanks to David Anton for translating the code to VB.NET

OUTPUT

image

No comments:

Post a Comment