这是在Windows Forms,.NET 4.0上。
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Lastname { get; set; }
public override string ToString()
{
return String.Format("{0} {1}", Name, Lastname);
}
}
我在MSDN page上读到,如果没有.DisplayMember设置为comboBox控件,它会使用对象的默认ToString,这就是我重写toString方法的原因。
结果如预期:
以下是我加载数据的方式:
private void button2_Click(object sender, EventArgs e)
{
var people = LoadSamplePeople();
comboBox1.DataSource = people;
}
private IEnumerable<Person> LoadSamplePeople()
{
return new List<Person>()
{
new Person(){ Id = 1, Name = "Sergio", Lastname = "Tapia" },
new Person(){ Id = 2, Name = "Daniel", Lastname = "Tapia" }
};
}
问题出现了,当我设置控件的 .ValueMember 时,似乎显示默认使用那个值。
private void button2_Click(object sender, EventArgs e)
{
var people = LoadSamplePeople();
comboBox1.ValueMember = "Id";
comboBox1.DataSource = people;
}
private IEnumerable<Person> LoadSamplePeople()
{
return new List<Person>()
{
new Person(){ Id = 1, Name = "Sergio", Lastname = "Tapia" },
new Person(){ Id = 2, Name = "Daniel", Lastname = "Tapia" }
};
}
我如何设置valueMember但默认DisplayMember为ToString方法?
请注意,显示是Person类的两个属性的组合。 :)
答案 0 :(得分:4)
我只想添加一个额外的属性:
public string DisplayName {
get { return String.Format("{0} {1}", Name, Lastname); }
}
public override string ToString() { return DisplayName; }
并设置.DisplayMember = "DisplayName";