DropDownList Items in List

2019-07-13 13:33发布

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

标签: asp.net
5条回答
霸刀☆藐视天下
2楼-- · 2019-07-13 14:01

yep. Set the datasource to the List<string>

查看更多
仙女界的扛把子
3楼-- · 2019-07-13 14:06
myDropDown.DataSource = myListOfStrings;
myDropDown.DataBind();
查看更多
劳资没心,怎么记你
4楼-- · 2019-07-13 14:10

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);
}
查看更多
趁早两清
5楼-- · 2019-07-13 14:15

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();
查看更多
姐就是有狂的资本
6楼-- · 2019-07-13 14:24

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();
}
查看更多
登录 后发表回答