tags:

views:

141

answers:

5

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

+2  A: 

yep. Set the datasource to the List<string>

Mitch Wheat
+2  A: 

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();
Kevin
Seems like the only other answer which shows how to add items TO the List, from the DDL. +1
Cerebrus
+1  A: 
myDropDown.DataSource = myListOfStrings;
myDropDown.DataBind();
d4nt
A: 

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);
}
DeletedAccount
+3  A: 

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();
}
BigBlondeViking
Seems like the only other answer which shows how to add items TO the List, from the DDL. +1
Cerebrus
Bravo..that was spot on!
i love how clean linq makes things, :)
BigBlondeViking