jQuery and ASP.NET

July 27, 2009

Retrieve Selected Items of an ASP.NET ListBox using LINQ




I had recently written a post on Programmatically Select Multiple Items of an ASP.NET ListBox. A user ‘JukeBox’ mailed back asking me if it was possible to retrieve the selected items of a ListBox using LINQ. Here’s how to do so:

<div>
<
asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<
asp:ListItem Value="One" Selected="True" />
<
asp:ListItem Value="Two" />
<
asp:ListItem Value="Three" />
<
asp:ListItem Value="Four" Selected="True" />
<
asp:ListItem Value="Five" />
</
asp:ListBox>
<
br />
<
br />
<
asp:Button ID="btnSel" runat="server" Text="Get Selected"
onclick="btnSel_Click" />
</
div>

C#

protected void btnSel_Click(object sender, EventArgs e)
{
var selItems = from ListItem li in ListBox1.Items
where li.Selected == true
select
li.Text;

Response.Write("Selected Item(s): </br>");
foreach (var item in selItems)
{
Response.Write(item.ToString() + "</br>");
}
}

VB.NET

Protected Sub btnSel_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim selItems = _
From li As ListItem In ListBox1.Items _
Where li.Selected = True _
Select li.Text

Response.Write("Selected Item(s): </br>")
For Each item In selItems
Response.Write(item.ToString() & "</br>")
Next item
End Sub

On clicking the Button, the selected items are fetched as shown below:

image



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Retrieve Selected Items of an ASP.NET ListBox using LINQ"
 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions