Sunday, August 22, 2010

How To: Extract Selected Items From An ASP.NET ListBox Using LINQ

(Note: All code examples here use VS.NET 2010 so there is a lot of shortcutting. Just know you will need line continuation underscores "_" and long hand properties if using an earlier version of VS.NET)

If you have wanted to extract all of the 'Selected' items from a ListBox in the past, you probably created a For Each loop similar to the code below:

For Each li As ListItem In Me.ListBox1.Items
If li.Selected Then
'Code here to process selected item
End If
Next
However thank you to LINQ and being that the ListBox control is an enumerable type, you can run a LINQ query against the Listbox's Items to get back all of the selected items. One important note to keep in mind is how powerful LINQ is and how many different objects and types can be used in LINQ queries. This example is specific to an ASP.NET ListBox, but there are many other controls where you could write similar queries to extract out data based on a criteria.

So to begin let's create a simple ListBox with some colors:

<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<asp:ListItem Value="1" Text="Green" />
<asp:ListItem Value="2" Text="Red" />
<asp:ListItem Value="3" Text="Blue" />
<asp:ListItem Value="4" Text="Orange" />
</asp:ListBox>
Now on the button click event we want to extract these colors into our class named 'ColorData'. It has (2) properties: ColorID and ColorDesc. So 1st let's just view the simple ColorData class:

Public Class ColorData

Public Property ColorID As Integer

Public Property ColorDesc As String

End Class
Like mentioned before, we would have iterated through each ListItem Object in the ListBox control, and manually added each set of values to a generic list. With the LINQ query we can do it all in 1 step. Below is the LINQ query that dumps into an Anonymous type named 'myColorData' the results of the query which places only the selected ListBox item values into the collection:

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

'Extract the 'Selected' ListBox items into a generic list of type 'ColorData'
'Use LINQ to extract the items rather than iterating through manually with a For-Each loop

'Also notice the use of an Anonomous type: myColorData which at runtime is resolved to
'a generic list of type ColorData
Dim myColorData = (From li As ListItem In Me.ListBox1.Items
Where li.Selected = True
Select New ColorData With {
.ColorDesc = li.Text,
.ColorID = li.Value})

End Sub
That's it! Of course you could modify the values inline, check to make sure the values were of the correct type, or anything else required. Hopefully this will get you thinking about getting rid of those old For Each loops when accessing data from ASP.NET controls and using LINQ instead.

No comments:

Post a Comment