简体   繁体   中英

C# Using a list of objects to populate combobox and keeping object properties accessible

I'm having some difficulty populating a combobox with the values inside a list. The list contains the following.

public List<Classroom> classes= new List<Classroom>();

CONTAINS:

public List<Students> Members{ get;}

public Classroom(string naam, string code, int maxPersonen)
{
    Name= name;
    Code = code;
    MaxPeople= maxpeople;
    Members= new List<Members>();
}

i'm trying to populate my combobox with List classes and show each of these classes as following (currently using this):

foreach(Classroom classrooom in repository.classes)
{
    cmbClass.Items.Add(classroom.Name + " (" + classroom.Code + ")");
}

I want to visually show them like this, but still be able to access every other property of the classroom that is selected (when using).

Hope this is clear enough to understand! Thanks in advance!

You need to bind the list as a datasource to the combobox rather than adding one by one. And, add read only property DisplayName to classroom to return Name + " (" + Code + ")" to use it as a display value. You can add datasource, set display value and the selected item property will return the object.

    cmbClass.DataSource = classes;
    cmbClass.DisplayMember = classroom.DisplayName; 

Reference - ComboBox Class: https://msdn.microsoft.com/en-us/library/system.windows.forms.combobox%28v=vs.110%29.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM