Joe.wang
Joe.wang

Reputation: 11791

Bind custom object of list to ListBox

All, Say you have a list of object which class is named 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;}
}

And Say you have a ListBox which id is personListBox. and It is trying to bind with the List of Person.

List<Person> list= new List<Person>();
list.add(...);
...
list.add(...);

personListBox.DataSource=list;
personListBox.DataTextField = "name";
personListBox.DataValueField = "id";
personListBox.DataBind();

But My question is How can I convert the selected Item to Person? What I image the code looks like below.

    protected void personListBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Person item = (Person)lbBizCategory.SelectedItem;
        //string majorName = item.major.MajorName;

    }

Unfortunatedly, It doesn't work. Is there any way to make it ? thanks.

Upvotes: 0

Views: 302

Answers (2)

citronas
citronas

Reputation: 19365

You probably still have a reference to your list. Try

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

Upvotes: 1

Vidhya Sagar Reddy
Vidhya Sagar Reddy

Reputation: 1641

We cannot directly typecast the selectedItem to the Person type..!! Instead, we can have a Person object created and assign the value of the object's property to the selectedItem, which is like:

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

By the way, we cannot add values to the list as you wrote: List list= new List(); list.add(...); Since list can now accept only Person type; so we need to create person object, fill the object's properties and later add the object to the list as:

Person person=new Person();
person.name="sagar";
person.id=1;
....
list.add(person);

Upvotes: 0

Related Questions