问题
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!
回答1:
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
来源:https://stackoverflow.com/questions/34250770/c-sharp-using-a-list-of-objects-to-populate-combobox-and-keeping-object-properti