Menus

Tuesday, December 4, 2012

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:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
    <asp:ListItem Text="One" Value="One" />
    <asp:ListItem Text="Two" Value="Two" />
    <asp:ListItem Text="Three" Value="Three" />
    <asp:ListItem Text="Four" Value="Four" />
    <asp:ListItem Text="Five" Value="Five" />
    <asp:ListItem Text="Six" Value="Six" />
    <asp:ListItem Text="Seven" Value="Seven" />
</asp:ListBox>

<asp:ListBox ID="ListBox2" runat="server" SelectionMode="Multiple">
    <asp:ListItem Text="One" Value="One" />
    <asp:ListItem Text="Two" Value="Two" />
    <asp:ListItem Text="Three" Value="Three" />
    <asp:ListItem Text="Four" Value="Four" />
    <asp:ListItem Text="Five" Value="Five" />
    <asp:ListItem Text="Six" Value="Six" />
    <asp:ListItem Text="Seven" Value="Seven" />
</asp:ListBox>



And here is the LINQ query
C#
var query = from p in ListBox1.Items.OfType<ListItem>()
                .Concat(ListBox2.Items.OfType<ListItem>())
                .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