【问题标题】:How can I combine two class members to be a combobox's joint DisplayMember?如何将两个班级成员组合成一个组合框的联合 DisplayMember?
【发布时间】:2016-05-25 18:56:32
【问题描述】:

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

【问题讨论】:

  • 覆盖 ToString 以显示您想要的任何内容,然后将 DisplayMember 留空。或创建一个人造属性并将其用作 DisplayMember

标签: c# combobox generic-list valuemember


【解决方案1】:

我会用返回的属性扩展Student"FirstName + LastName"

喜欢...

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

比将此属性分配给DisplayMember

comboBoxStudents.DisplayMember = "DisplayName";

【讨论】:

  • 完美/优雅/我怎么没想到?
  • 有时它需要第三只眼睛 ;)
猜你喜欢
  • 2016-04-27
  • 2015-10-04
  • 1970-01-01
  • 2021-08-19
  • 2011-01-12
  • 1970-01-01
  • 2012-07-29
  • 2020-11-14
  • 2019-08-27
相关资源
最近更新 更多