Most efficient way to bind a Listbox with SelectionMode=Multiple
Posted
by Draak
on Stack Overflow
See other posts from Stack Overflow
or by Draak
Published on 2010-06-03T21:40:09Z
Indexed on
2010/06/03
21:44 UTC
Read the original article
Hit count: 248
Hi, I have an ASP.NET webform that has a listbox (lbxRegions
) with multi-select option enabled. In my db, I have a table with an xml field that holds a list of regions. I need to populate the listbox with all available regions and then "check off" the list items that match the regions in the db table. The list options also need to be ordered by region name. So, I wrote the following code that works just fine -- no problems. But I was wondering if anyone can think of a better (more succinct, more efficient) way to have done the same thing. Thanks in advance.
Dim allRegions = XElement.Load(Server.MapPath(Request.ApplicationPath) & "\Regions.xml").<country>.<regions>.<region>
Dim selectedRegions = (From ev In dc.Events Where ev.EventId = 2951).Single.CEURegions.<country>.<regions>.<region>
Dim unselectedRegions = allRegions.Except(selectedRegions)
Dim selectedItems = From x In selectedRegions Select New ListItem() _
With {.Value = x.@code, .Text = x.Value, .Selected = True}
Dim unselectedItems = From x In unselectedRegions Select New ListItem() _
With {.Value = x.@code, .Text = x.Value}
Dim allItems = selectedItems.Union(unselectedItems).OrderBy(Function(x) x.Text)
lbxRegions.Items.AddRange(allItems.ToArray())
P.S. You can post code in C# if you like.
© Stack Overflow or respective owner