Jose
Jose

Reputation:

DropDownList Items in List

Can anyone tell me shortest way to add all items of dropdownlist in a List<string>

I want to populate a List<string> with the values of a DropDownList

Upvotes: 2

Views: 3046

Answers (5)

kemiller2002
kemiller2002

Reputation: 115488

Your post was a little unclear are you adding items to the drop down list or to the list?

To add to the list: var list = new List(DropDownList.Items.Length);

foreach(var item in DropDownList.Items.Length)
   list.Add(item.Text);

To Add to the drop down list:

var list = new List<string> ();
    DropDownList.DataSource = list;
    DropDownList.DataBind();

Upvotes: 3

BigBlondeViking
BigBlondeViking

Reputation: 3963

Depends if you want the ListItem Text and you are able to leverage 3.5

public static List<string> GetStrings(DropDownList dl)
{
    return dl.Items.Cast<ListItem>().Select(i => i.Text).ToList();
}

Upvotes: 8

NikolaiDante
NikolaiDante

Reputation: 18639

Assuming: ddl your dropdown list. ListOfStrings your list of strings.

This should work:

foreach (var str in ListOfStrings)
{
  ddl.Items.Add(new ListItem(str, str);
}

Upvotes: 0

d4nt
d4nt

Reputation: 15769

myDropDown.DataSource = myListOfStrings;
myDropDown.DataBind();

Upvotes: 1

Mitch Wheat
Mitch Wheat

Reputation: 300559

yep. Set the datasource to the List<string>

Upvotes: 2

Related Questions