Thursday, May 3, 2012

Fetch Asp.Net Listbox control selected items without looping

Many people wants to retrieve Asp.net Listbox controls selected item values without looping through the whole items collection.
So here is the solution for it basically you can either use LINQ or Lambda Expressions to select the selected items from the control.

Aspx Code

<asp:ListBox ID="lstBox" runat="server"  SelectionMode="Multiple">
    <asp:ListItem Text="WindowsPhone" Value="WindowsPhone"></asp:ListItem>
    <asp:ListItem Text="Android" Value="Android"></asp:ListItem>
    <asp:ListItem Text="iPhone" Value="iPhone"></asp:ListItem>
    <asp:ListItem Text="BlackBerry" Value="BlackBerry"></asp:ListItem>
</asp:ListBox>
<br />
<asp:Button ID="btnRetrieve" runat="server" Text="Get" onclick="btnRetrieve_Click" />

Aspx.cs Code

First we will use LINQ method to retrieve selected items of lstBox control

protected void btnRetrieve_Click(object sender, EventArgs e)
{
        var selecteditems = from li in lstBox.Items.Cast<ListItem>()
                                      where li.Selected == true
                                       select li;      
}

Secondly now we will retrieve selected items of lstBox control through Lambda expression

protected void btnRetrieve_Click(object sender, EventArgs e)
{
       var selecteditems = lstBox.Items.Cast<ListItem>().Where(ee => ee.Selected == true);     
}

2 comments:

  1. This was a really awesome read.Thanks for contributing!

    ReplyDelete
    Replies
    1. Its been always a pleasure to share what you already know

      Delete