Forum Moderators: open

Message Too Old, No Replies

Get All ListBox Values in C#

         

IntegrityWebDev

4:25 am on Mar 7, 2010 (gmt 0)

10+ Year Member



I have this code:
mail.Body += "Types of Material: " + lbTypeofMaterial.SelectedItem + "<br />";


But after some testing I realize that this only gets the FIRST selected value of the ListBox.

I can't seem to find a good solid example that will get all values of multiple value listbox....any thoughts?

Thanks,
Chris

johnblack

5:30 am on Mar 7, 2010 (gmt 0)



You need the collection lbTypeofMaterial.SelectedItems

foreach (selectedItem in lbTypeofMaterial.SelectedItems)
{
mail.Body += "Types of Material: " + selectedItem + "<br />";
}

That's not syntactically correct but you'll get the idea hopefully

IntegrityWebDev

8:26 pm on Mar 7, 2010 (gmt 0)

10+ Year Member



Using your help I came up with this code:
string lbTypeofMaterialALL;
foreach (string selectedItem in lbTypeofMaterial.SelectedItems)
{
lbTypeofMaterialALL += selectedItem + ", ";
}
mail.Body += "Types of Material: " + lbTypeofMaterialALL + "<br />";


But I get this error:
CS1061: 'System.Web.UI.WebControls.ListBox' does not contain a definition for 'SelectedItems' and no extension method 'SelectedItems' accepting a first argument of type 'System.Web.UI.WebControls.ListBox' could be found (are you missing a using directive or an assembly reference?)


This is a web form.

Thanks!
Chris

marcel

9:18 pm on Mar 7, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Almost, here is something that should work:

string lbTypeofMaterialALL;
foreach (ListItem li in lbTypeofMaterial.Items)
{
if (li.Selected)
{
lbTypeofMaterialALL += li.Value + ", ";
}
}
mail.Body += "Types of Material: " + lbTypeofMaterialALL + "<br />";

IntegrityWebDev

9:47 pm on Mar 7, 2010 (gmt 0)

10+ Year Member



Thanks Marcel...I got it to work (using your method) just as your reply came in! THANKS!

macfam929

6:49 pm on May 27, 2010 (gmt 0)

10+ Year Member



I am using your code above Marcel, but do not want it to add the comma and space after the last selected value. Can you show me how the code would change to make this work?!
Thanks. The code that you have is what I have been searching for all day.

IntegrityWebDev

7:00 pm on May 27, 2010 (gmt 0)

10+ Year Member



If you are just wanting to trim the last comma and space I think you want a TrimEnd maybe?

[msdn.microsoft.com...]

Do the TrimEnd after you have done all of your other string manipulation.

-Chris