0

我有以下代码用通用列表的内容填充组合框,尝试使用 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?

4

1 回答 1

3

我会Student用一个返回的属性来扩展这个类 "FirstName + LastName"

喜欢...

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

而不是将此属性分配给DisplayMember

comboBoxStudents.DisplayMember = "DisplayName";
于 2016-02-15T00:21:12.383 回答