Saturday, March 24, 2012

ListBox - Trouble Grabbing Multiple Selected Values

Hi,

I'm using ASP.NET 1.1/C#, and I'm having trouble grabbing multiple selected values from a Listbox. Here's the ListBox on the aspx page (note the "multiple" attribute):

<asp:ListBox Runat="server" ID="lstExpertise" CssClass="adminDropDownStyle" Rows="13" multiple />

This ListBox is properly populated in the Page_Load.

Here's the code-behind code that I'm having trouble with. I wrote it to grab the user's selected values:

// build string containing selected values (e.g. "32|117|74|117|90|")
strExpertise = string.Empty;

foreach(ListItem item in this.lstExpertise.Items)
{
if (item.Selected)
{
strExpertise = strExpertise + item.Value + "|";
}
}

The problem I'm having is that the "if (item.Selected)" statement only sees thefirst item selected by the user (I looped through the foreach statement in debug mode to discover this). This if statement never sees any subsequent items selected by the use. So, for example, instead of building a string that looks like this, "32|117|74|117|90|" -- this code always builds a string that looks like this, "32|", no matter how many selections the user made.

I'm sure I'm missing something obvious, and I'd appreciate any insight you can offer.

Thanks!

That should read SelectionMode="Multiple", not multiple.

Also, don't forget that each value must be unique (I noticed in your example that you had 117 twice).


You solved my problem. Thanks a lot!

0 comments:

Post a Comment