Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, March 24, 2009 8:10 PM
Hi,
I'm using a multi select ListBox on a page to select Names and ID numbers. This is how I have the ListBox set up:
lstNewSelectAnalyst.DataTextField = "AnalystName";
lstNewSelectAnalyst.DataValueField = "AnalystID";
The AnalystName is a varchar and AnalystID is an int.
I want to string together the AnalystID and send it to a stored procedure to split it. My problem is getting the code below to work correctly. With the code I have, it will only take one of the selected values and add it to the string. For example, If I select Jane and Will with IDs of 100 and 101, it will only add 101 to the string, so it looks like: 101|
foreach ( ListItem li in lstNewSelectAnalyst.Items )
{
if ( li.Selected == true )
{
strAnalystID = lstNewSelectAnalyst.SelectedValue;
strAnalystID += "|";
}
}
What am I doing wrong here? Is there something I'm missing to get it to catch all the selected values? Is this the wrong way to even go about doing this?
Thanks for the help!
All replies (6)
Tuesday, March 24, 2009 8:24 PM ✅Answered
You need:
foreach ( ListItem li in lstNewSelectAnalyst.Items )
{
if ( li.Selected == true )
{
strAnalystID = li.Value;
strAnalystID += "|";
}
}
If this answers your question, please mark the question as answered.
Tuesday, March 24, 2009 8:36 PM ✅Answered
You could also use some Linq for this one:
String.Join("|", lstNewSelectAnalyst.Items
.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.ToArray());
David Morton - http://blog.davemorton.net/
Tuesday, March 24, 2009 8:15 PM
Get rid of the ".SelectedValue" in your foreach line.
Tuesday, March 24, 2009 8:16 PM
I think you need to be using the ListBox's SelectedItems property, not SelectedValue. SelectedValue will only ever have one value.
If this answers your question, please mark the question as answered.
Tuesday, March 24, 2009 8:20 PM
toolman said:
Get rid of the ".SelectedValue" in your foreach line.
Sorry, I intended it to say ".Items"
However, if I remove that, I get the error:
foreach statement cannot operate on variables of type 'System.Web.UI.WebControls.ListBox' because 'System.Web.UI.WebControls.ListBox' does not contain a public definition for 'GetEnumerator'
Tuesday, March 24, 2009 11:13 PM
David nice to see you use the extension methods. You usually use the query syntax. [Well that's not entirely true, I have seen you use both]John Grove - TFD Group, Senior Software Engineer, EI Division, http://www.tfdg.com