Win
Win

Reputation: 2613

How to set the value of a string to all the values of a dropdownlist asp.net

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

Answers (4)

DGibbs
DGibbs

Reputation: 14618

Use String.Join:

string[] ddlValues = ddl.Items.Cast<ListItem>().Select(x => x.Text).ToArray();
string milestones = string.Join(",", ddlValues));

Upvotes: 3

Dr Schizo
Dr Schizo

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

Tim Schmelter
Tim Schmelter

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

Jack Marchetti
Jack Marchetti

Reputation: 15754

This could work for you as well.

string milestones = string.Join(",", ddl.Items.ToArray());

Upvotes: 1

Related Questions