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
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
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();
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);
}
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();
}