Reputation: 2613
I have a dropdownlist that is populated from a database, when a user clicks the add all button on the web page I want to set the value of a string 'milestones' to a comma delimited string that holds all the values of the dropdownlist. Is there a simple way of doing this?
Upvotes: 1
Views: 1407
Reputation: 14618
Use String.Join:
string[] ddlValues = ddl.Items.Cast<ListItem>().Select(x => x.Text).ToArray();
string milestones = string.Join(",", ddlValues));
Upvotes: 3
Reputation: 4362
DropDownList d = new DropDownList();
d.Items.Add(new ListItem("1", "Foo"));
d.Items.Add(new ListItem("2", "Bar"));
string[] items = d.Items.Cast<ListItem>().Select(x => x.Value).ToArray();
Upvotes: 0
Reputation: 460138
You can use Linq to select all items of the DropDownList
, use String.Join
to concat them:
string milestoneNames = string.Join(",",
ddlMileStone.Items.Cast<ListItem>().Select(i => i.Text));
If you want all values instead:
string milestoneValues = string.Join(",",
ddlMileStone.Items.Cast<ListItem>().Select(i => i.Value));
Upvotes: 3
Reputation: 15754
This could work for you as well.
string milestones = string.Join(",", ddl.Items.ToArray());
Upvotes: 1