c# - A bit of confusion regarding ComboBoxes, ValueMember and DisplayMember -


this 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 msdn page, if no .displaymember set combobox control, uses default tostring of object, that's reason why i'm overriding tostring method.

the result expected:

enter image description here

here's how i'm loading 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 set .valuemember of control, seems display defaults 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 set valuemember default displaymember tostring method?

please note display combination of 2 properties on person class. :)

i add property:

public string displayname {     { return string.format("{0} {1}", name, lastname); } }  public override string tostring() { return displayname; } 

and set .displaymember = "displayname";


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -