Friday, December 08, 2006

What the hell is going on with my combo box?

These days I'm very busy with my works. But I found a problem and it can take me about 3 minutes to have a break and I use it to write this post.

The problem I found relates with ComboBox control in .NET Framework 2.0. A ComboBox control has a DataSource property which accepts a List<T> as value. And then you can specify value of ValueMember and DisplayMember for it to use as value and text in combo box.

I have a Tag(int id, string name) and ofcourse a List<Tag> (it is not empty). I filled the list to a combo box, use "id" as ValueMember and "name" as DisplayMember then set SelectedIndex is 0 to make sure that I always select at least one item on the list. When I click the arrow of combo box, the drop down list appears but I don't select any item from list. Then I've got SelectedIndex is -1 while my expected value is 0. At this time I want to crazy 'cause don't understand why it happened.

But later I found that, the problem is the DisplayMember's data. If the first item of the list has a "name" is an empty string, you will have this problem. Seems M$ implemeted to select text value to get the index. But if it's an empty string, the returned index will be -1.

Thanks M$ to make me crazy ;-)

No comments: