Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# combobox overridden ToString

I am experiencing some problems while working with ComboBox.

The display member for my combobox is not being populated by the overridden ToString method of class MAP.

Here is my code:

Form1.cs:

private void Form1_Load(object sender, EventArgs e) {  
    ...  
    ...      
    MAPList MAP = new MAPList();  
    comboBox1.DataSource = MAP.All;  
    comboBox1.ValueMember = "Code";  
    ...  
    ...  
}

MAPList.cs:

public class MAPList {  
    public readonly List<MAP> All;

    public MAPList() {
        All = new List<MAP>();

        var MapData = // Getting map data

        foreach(MAP m in MapData) {
            All.Add(new Map(m.Name, m.Code));
        }
    }
}

MAP.cs:

public class MAP {
    public readonly string Name;

    private string code;
    public string Code { get { return code; } }

    public RadioCode(string Name, string Code) {
        this.Name = Name;
        this.code = Code;
    }

    public override string ToString() {
        return String.Format("{0}: {1}", Name, Code);
    }
}
like image 678
Moon Avatar asked Sep 08 '10 05:09

Moon


2 Answers

ToString will not be called if you set ValueMember. If you do not set ValueMember it will work as expected but then of course Code will not be used as the selected value of the ComboBox.

Alternatively, if you wish to use ValueMember you may also want to set DisplayMember. You can create a property on your MAP that is used for display, i.e.:

public class MAP
{
    public readonly string Name;

    private string code;

    public string Code { get { return code; } }
    public string Display { get { return ToString(); } }

    public MAP(string Name, string Code)
    {
        this.Name = Name;
        this.code = Code;
    }

    public override string ToString()
    {
        return String.Format("{0}: {1}", Name, Code);
    }
}

In the form you can then set DisplayMember:

MAPList MAP = new MAPList();
comboBox1.DataSource = MAP.All;
comboBox1.ValueMember = "Code";
comboBox1.DisplayMember = "Display";
like image 147
Jakob Christensen Avatar answered Sep 18 '22 00:09

Jakob Christensen


This is because you've set your ValueMember property to "Code", so the values in the combobox are not your Map objects but rather the strings corresponding to their Code properties.

If you remove this line:

comboBox1.ValueMember = "Code";

...it will work as you expect.

If you want the ComboBox to display its items according to your Map type's ToString method, then Jakob's answer is right on: create a property on your Map type that provides a string formatted exactly how you want it, and set the DisplayMember property of the ComboBox to the name of this property.

like image 39
Dan Tao Avatar answered Sep 19 '22 00:09

Dan Tao