如何将两个班级成员组合成一个组合框的联合DisplayMember?

时间:2016-02-15 00:10:37

标签: c# combobox generic-list valuemember

我已经获得了以下代码,用通用列表的内容填充组合框,尝试使用FirstName和LastName的串联作为组合框的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";
    }
}

这不起作用; ValueMember成为DisplayMember。

这有效:

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

...但是没有削减芥末 - 我需要给定的姓氏和姓氏,而不仅仅是给定的名字(反之亦然)。

如何组合两个类字段组成一个组合框的DisplayMember?

1 个答案:

答案 0 :(得分:3)

我会使用返回的Property扩展Student"FirstName + LastName"

像...

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

将此属性分配给DisplayMember

comboBoxStudents.DisplayMember = "DisplayName";