How can I combine two class members to be a combobox's joint DisplayMember?

121 views Asked by At

I've got the following code to populate a combobox with the contents of a generic list, trying to use a concatenation of FirstName and LastName as the combobox's DisplayMember:

private void PopulateStudentsComboBox()
{
    if (System.IO.File.Exists(AYttFMConstsAndUtils.STUDENTS_FILENAME))
    {
        if (null == _studentsList)
        {
            var students = System.IO.File.ReadAllText(AYttFMConstsAndUtils.STUDENTS_FILENAME);
            _studentsList = JsonConvert.DeserializeObject<List<Student>>(students);
        }
        // Sort by firstname            
        _studentsList = _studentsList.OrderBy(i => i.FirstName).ToList();
        comboBoxStudents.DataSource = _studentsList; 
        string firstNameLastName = "FirstName LastName";
        comboBoxStudents.DisplayMember = firstNameLastName;
        comboBoxStudents.ValueMember = "StudentID";
    }
}

This doesn't work; the ValueMember becomes the DisplayMember.

This works:

. . .
comboBoxStudents.DataSource = _studentsList; 
comboBoxStudents.DisplayMember = "FirstName";
comboBoxStudents.ValueMember = "StudentID";
. . .

...but doesn't cut the mustard - I need both given and surnames, not just the given name (or vice versa).

How can I combine two class fields to comprise a combobox's DisplayMember?

1

There are 1 answers

2
Cadburry On BEST ANSWER

I would extend the Student class with a Property which returns "FirstName + LastName"

like...

...
    public string DisplayName
        {
            get
            {
                return string.Format("{0} {1}", this.FirstName, this.LastName);
            }
        }
...

than assign this property to the DisplayMember

comboBoxStudents.DisplayMember = "DisplayName";