delete
delete

Reputation:

A bit of confusion regarding ComboBoxes, ValueMember and DisplayMember

This is on 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);
    }
}

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:

enter image description here

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

enter image description here

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. :)

Upvotes: 1

Views: 2576

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062640

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

Upvotes: 4

Related Questions