Next time, use the designer!

It was a sad story like that. I was trying to do a simple-enough application with Visual Studio 2008. I tried to used some custom DAO with a combo box.

It was really very simple. Combo box API in C# has two cool properties, DisplayMember and ValueMember. So it is easy to just display and object in the combo box, with a code like:

public class Foo {
public String Member { } // getter and setter
public String Value { }

ComboBox cb = ... //combo box init

cb.DataSource = new List(); // or any IEnumerable
cb.DisplayValue = "Member";
cb.MemberValue = "Value";

The trick is that the combo uses reflection and gets the actual properties from the textual representation of the assigned values. So far, So Good.

The problem began when i actually defined an event. To be exact, a SelectedIndexChanged event.

I added the code, accessing the actual Combo Box, and then the program started to behave abnormally. It seemed to ignore the ValueMember i already assigned and returned to me the whole object, instead of the selected property. The second time you accessed it, the combo box returned the correct value. Amazing, right?

To be honest, i was puzzled, i was sure that it was my mistake, but haven’t found a solution until a few hours later (dealt with some other stuff too, my PhD for example :-p).

The problem was at the declaration, when i assigned the DataSource, then the SelectedIndexChanged event triggers. That happened before i assigned the correct property to the combo box, and the first time it was executed, it returned the default value (which is the object), the second (and so on) the correct property.

If i originally used the designer a little bit more, instead of hacking and slashing through properties, i could have avoided the whole mess …

It was all there right?
It was all there right?