Discovered something interesting and annoying today…pardon me if you’ve already heard this one.
In C# 2.0 if you bind a List<BusinessObject> to a System.Windows.Forms.ComboBox you can set the ValueMember and the DisplayMember to set which properties of your business object will be the “value” and which will be the “display” text. Simple enough.
After playing around a bit, I “discovered” that if you set DisplayMember = “”; (empty string) then it will use the ToString() of the bound object. I say “discovered” because if I had looked on MSDN I would have seen that…but I didn’t, and I found out by accident, so I was happy. Like any good library developer, I’m overriding ToString on my business objects to provide meaningful output. For say, an object representing a person, ToString() yields “Lastname, Firstname”. This is handy when binding these people to a ComboBox because you can’t (that I’ve found) set DisplayMember equal to the concatenation of two properties. So setting the DisplayMember to “” gives me a nice display of “Lastname, Firstname” in the combo box and I’m happy.
So, the stupid trick. The first time I did it the code went a little something like this:
salesRep.ValueMember = "SalesRepID";
salesRep.DisplayMember = "";
And all was good. So today, I’m making a different WinForm, and I have several ComboBoxen, and I’m using my ToString “trick” all happy, and I run the form…and the ID (ValueMember) is showing in the display. Not the ToString. WTF? I go and check it out, it looks good, I check old code to make sure I’m doing the same thing, and I am, I look it up on MSDN (this is when I discover that the setting DisplayMember to empty string is documented
) and all looks good. The code goes a little something like this:
salesRep.DisplayMember = "";
salesRep.ValueMember = "SalesRepID";
So…what’s the problem? Well, the more astute among you probably noticed that I set DisplayMember first this time and second last time. You also probably said “not that it should matter”…
On a whim I changed it to:
salesRep.ValueMember = "SalesRepID";
salesRep.DisplayMember = "";
And ran the app…guess what? DisplayMember was the ToString result as expected. Awesome-O.
Please tell me if I’m some kind of jackass and that there’s a good reason for this behavior…because I can’t for the life of me think of one.
Tags:
Code UI dotnet