Reputation:
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
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
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
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