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);
}
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);
}
This was a really awesome read.Thanks for contributing!
ReplyDeleteIts been always a pleasure to share what you already know
Delete