【问题标题】:How can I DataBind a List<> of objects to a DropDownList and set the SelectedItem based on a property in the object?如何将对象的 List<> 数据绑定到 DropDownList 并根据对象中的属性设置 SelectedItem?
【发布时间】:2017-07-28 04:45:40
【问题描述】:
如何将对象的List<> 数据绑定到 DropDownList 并根据对象中的属性设置 SelectedItem?
例如,假设我有一个
List<Person>
Person 有 3 个属性...
Person .Name (string)
.Id (int)
.Selected (bool)
我希望第一个 Selected == true 成为列表中的 SelectedItem。
【问题讨论】:
标签:
c#
asp.net
data-binding
drop-down-menu
【解决方案1】:
试试这个:
List<Person> list = new List<Person>();
// populate the list somehow
if ( !IsPostBack )
{
DropDownList ddl = new DropDownList();
ddl.DataTextField = "Name";
ddl.DataValueField = "Id";
ddl.DataSource = list;
ddl.DataBind();
ddl.SelectedValue = list.Find( o => o.Selected == true ).Id.ToString();
}
如果您不能保证总是至少有一个选定的项目,那么您需要通过检查来自list.Find() 调用的返回值来单独处理它,以确保它不是null。
另外,DropDownList ddl = new DropDownList();如果网络表单已经声明,则不需要:
<asp:DropDownList ID="ddl" runat="server" />
【解决方案2】:
我相信这会奏效:
List<Person> people = GetDataFromSomewhere();
DropDownList ddl = new DropDownList();
ddl.DataTextField = "Name";
ddl.DataValueField = "Id";
ddl.DataSource = people;
ddl.DataBind();
ddl.SelectedValue = (from p in people
where p.Selected == true
select p.Id).FirstOrDefault().ToString();
【解决方案3】:
如果“选定”部分是必要的,您还可以使用以下方法进行绑定:
List<Person> ps = new List<Person>();
DropDownList dl = new DropDownList();
dl.Items
.AddRange(ps
.Select(p => new ListItem() {
Text = p.Name
, Value = p.ID
, Selected = p.Selected }).ToArray());
【解决方案4】:
我刚才也有同样的问题,但我发现编写代码以手动添加列表中的项目比描述的其他解决方案更短或更长。
因此,这样的事情应该适合你:
//bind persons
foreach(Person p in personList)
{
ListItem item = new ListItem(p.Name, p.Id.ToString());
item.Selected = p.Selected;
DropDownListPerson.Items.Add(item);
}
只需确保检查 IsPostBack 以及检查列表是否已经包含项目。
【解决方案5】:
绑定到列表后我会做这样的事情。
private void SetSelected(int id)
{
foreach (ListItem li in list.Items)
{
li.Selected = false;
if (li.Value == id.ToString())
{
li.Selected = true;
}
}
}