>我有以下代码来填充一个组合框,其中包含泛型列表的内容,尝试使用名字和姓氏的串联作为组合框的显示成员:
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";
. . .
。但不切芥末 - 我需要名字和姓氏,而不仅仅是名字(反之亦然(。
如何组合两个类字段以构成组合框的显示成员?
我会用一个返回的属性来扩展Student
类 "FirstName + LastName"
喜欢。。。
...
public string DisplayName
{
get
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
}
...
而不是将此属性分配给DisplayMember
comboBoxStudents.DisplayMember = "DisplayName";