ComboBox.SelectedText always returning empty string

D

Dano

Hi all,

I know I must be missing something very simple here, but this little problem
is baffling me.

If you have a combobox called cmbMyCombo and add a bunch of strings to it,
say, "Apple", "Pear" and "Orange", and then call the
cmbMyCombo.SelectedIndex it will tell you the index of the item that was
selected. However, you would think that if you called
cmbMyCombo.SelectedText it would give you the TEXT of whatever was selected
(i.e. Apple, Pear etc), but all it does is return an empty string. Does
anyone know why this is?

Dano
 
T

Tim Wilson

I assume that the DropDownStyle is set to "DropDownList". From the help:
"If DropDownStyle is set to ComboBoxStyle.DropDownList, the return is an
empty string ("")."
 
D

Dano

Yes ... doublechecked. It is set to DropDownList. In fact it doesn't seem
to matter what it is set to, it always returns an empty string.

Dano
 
T

Tim Wilson

The "SelectedText" property returns the selected text in the editable
portion of the control. And if DropDownStyle is set to
ComboBoxStyle.DropDownList it will return, as the expected behavior, an
empty string. The whole purpose of this property is so that when the user
selects all, or a portion, of the text in the "edit" portion of ComboBox you
can programmatically determine what that selection is. I suspect that when
you are trying to see the"SelectedText" when the DropDownStyle is set to the
ComboBoxStyle.DropDown you are causing the focus to be taken away from the
ComboBox, and thus the "SelectedText" value is empty - nothing selected. In
this situation try using the "SelectedItem" property instead.

if (this.comboBox1.SelectedItem is string)
{
MessageBox.Show((string)this.comboBox1.SelectedItem);
}
 
D

Dano

Ahhhhh .... that would explain it. You see the code is running after a
button click in which case any highlighted text in the dropdown loses focus.
Thanks so much for clearing that up for me!

Dano
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top