Welcome to WebmasterWorld Guest from 3.226.243.130

Forum Moderators: ocean10000

Message Too Old, No Replies

Get All ListBox Values in C#

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

Junior Member

5+ Year Member

joined:Dec 4, 2009
posts: 186
votes: 0


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
5:30 am on Mar 7, 2010 (gmt 0)

Full Member

joined:Sept 29, 2005
posts: 216
votes: 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
8:26 pm on Mar 7, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 4, 2009
posts: 186
votes: 0


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
9:18 pm on Mar 7, 2010 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Feb 1, 2005
posts:733
votes: 0


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 />";
9:47 pm on Mar 7, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 4, 2009
posts:186
votes: 0


Thanks Marcel...I got it to work (using your method) just as your reply came in! THANKS!
6:49 pm on May 27, 2010 (gmt 0)

New User

5+ Year Member

joined:May 27, 2010
posts: 2
votes: 0


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.
7:00 pm on May 27, 2010 (gmt 0)

Junior Member

5+ Year Member

joined:Dec 4, 2009
posts:186
votes: 0


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
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members