View Single Post
  #5  
Old 05-14-2008, 08:49 AM
AtmaWeapon's Avatar
AtmaWeapon AtmaWeapon is offline
Fabulous Florist

Forum Leader
* Guru *
 
Join Date: Feb 2004
Location: Austin, TX
Posts: 9,416
Default

Getting the selected item out of a combo box is kind of tricky, and it's made more difficult by the fact that some of the properties sound more helpful than they are. I'm going to outline what each property does, and then make a suggestion about what to do.

Keep in mind there are three modes for the combo box, and the mode it is in is dictated by the DropDownStyle property. Some of the properties behave differently based on this mode. I will try to explain the properties whose behavior changes as well.

SelectedIndex will return the index specifying the selected item, or -1 if there is no selection. This is probably the most useful "SelectedXXXX" property, because it's the same in every mode. If it didn't return -1, you can get the text of the selected item easily:
Code:
Dim index As Integer = cBox.SelectedIndex

If index <> -1 Then
    MessageBox.Show(cBox.Items(index).ToString())
End If
Personally, I tend to use this property the most because I don't like having to think about things too hard.

SelectedItem will return the currently selected item in the combo box, or Nothing if there is no selected item. It's basically a shortcut to the code snippet I posted above.

SelectedText is the one that confuses people. Do not use this property to determine what item is selected in the combo box. It only returns anything at all if the combo box's DropDownStyle property is set to DropDown. Even then, it only returns anything if the user has highlighted text in the control. What it returns isn't even guaranteed to be an item that exists in the list, because the user can type anything. Only use this property when you want to see what the user has typed, then highlighted in a combo box that allows the user to type values.

SelectedValue should only be used in specific cases. It works together with the ValueMember property to help with situations where you want the combo box to display a different value than you use. For example, if I'm storing some custom Person class in the combo box, and I want the combo box to display the person's name but I want to get the person's ID number from the selection, I'd set DisplayMember to "Name", ValueMember to "Id", and use SelectedValue to get the id number.

My suggestion is to use SelectedItem to determine what item the user selected. You can handle the SelectedIndexChanged event to do something when the index changes. In this event handler, you should check the SelectedItem and choose the appropriate picture for the picture box.
Reply With Quote