开发者

A bit of confusion regarding ComboBoxes, ValueMember and DisplayMember

This is on Windows Forms, .NET 4.0.

public cla开发者_Go百科ss 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);
    }
}

I read on the MSDN page, that if no .DisplayMember is set to the comboBox control, it uses the default ToString of the object, that's the reason why I'm overriding the toString method.

The result is as expected:

A bit of confusion regarding ComboBoxes, ValueMember and DisplayMember

Here's how I'm loading the data:

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" }
    };
}

The problem arises, when I set the .ValueMember of the control, it seems display defaults to use that value.

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" }
    };
}

A bit of confusion regarding ComboBoxes, ValueMember and DisplayMember

How would I set the valueMember but default the DisplayMember to the ToString method?

Please note that the display is a combination of two properties on the Person class. :)


I would just add an extra property:

public string DisplayName {
    get { return String.Format("{0} {1}", Name, Lastname); }
}

public override string ToString() { return DisplayName; }

and set the .DisplayMember = "DisplayName";

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜