Combobox and first item display at runtime

dcasmr

Member
Joined
May 28, 2005
Messages
15
Programming Experience
Beginner
I found something trying to get my combobox to display either the first item or any item at run time. Initially, I was using ComboBox.SelectedIndex = 0, but did not like the fact that it was stuck at that value.

Trying around, I set the Text property of the Combobox to one of the element in the combobox and it worked fine ... Can anyone confirm that's the best way of doing it?

Thanks,
dcasmr
 
Moved to more appropriate forum.

I can confirm that that is not the best way of doing it. If you want to select an item from the ComboBox's list you should be setting either the SelectedItem or SelectedIndex property. Noone's saying that you have to set the SelectedIndex to zero. You can set it to any valid index, just as you can set the SelectedItem to any valid item.
 
Thanks for your feedback. It looks to me when I put down ComboBox.SelectedIndex = 2 for example, when I run the program, it does not show the third element of my list in combobox. But, when I use the third element as the Text in the text property, it does exactly what I wanted it to do. At runtime, instead of having a blank combobox display, I see my third item instead of Blank.....
Thanks
 
Then you're doing something wrong. Attached is the code I used to set the SelectedIndex of four ComboBoxes, which all worked as expected. I've also added another screen shot that shows what each of the four ComboBoxes contains.
 

Attachments

  • ComboBox.JPG
    ComboBox.JPG
    44.6 KB · Views: 110
Note that if your ComboBox has its DropDownStyle set to DropDown, setting the Text property to a String that looks the same as one of the items in the list still doesn't actually select that item anyway. If the DropDownStyle is set to DropDownList it will though, but if you want to select an itme then you should select an item directly, not indirectly by setting the Text.
 
Check the combobox size

I have ran into this before (I think I remember). I had to resize the combobox (make it bigger) to fully display the text. Test this by oversizing the combobox once and see if the selected index is displayed. Has something to do with trailing spaces in the items list.

Hope that helps...
 
Back
Top