将列表的自定义对象绑定到ListBox

时间:2013-07-15 12:34:04

标签: asp.net

全部,假设您有一个对象列表,该类名为Person

public class Person
{
   public string name{get;set;}
   public string id{get;set;}
   public int age{get;set;}
   public Major major{get;set;}
}

public class Major{
   public string MajorName{get;set;}
   public string MajorId{get;set;}
}

并说你有一个ListBox,其ID为personListBox。它正试图与List的{​​{1}}绑定。

Person

但我的问题是如何将所选项目转换为List<Person> list= new List<Person>(); list.add(...); ... list.add(...); personListBox.DataSource=list; personListBox.DataTextField = "name"; personListBox.DataValueField = "id"; personListBox.DataBind(); ? 代码如下图所示。

Person

不幸的是,它不起作用。有什么方法可以做到吗?感谢。

2 个答案:

答案 0 :(得分:1)

您可能仍然可以参考您的列表。尝试

 protected void personListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        Person yourPerson = list.First(x => x.id == int.Parse(personListBox.SelectedValue));
    }

答案 1 :(得分:0)

我们不能直接将selectedItem类型转换为Person类型.. !! 相反,我们可以创建一个Person对象 并将对象属性的值赋给selectedItem,如:

Person person=new Person();
person.name=personListBox.SelectedItem.ToString();

顺便说一句,我们不能像你写的那样在列表中添加值:     List list = new List();     list.add(...); 由于列表现在只能接受Person类型;所以我们需要创建人物对象, 填充对象的属性,然后将对象添加到列表中:

Person person=new Person();
person.name="sagar";
person.id=1;
....
list.add(person);
相关问题