In my WinForms / C# application, I can choose either Combobox.Text
or Combobox.SelectedText
to return the string value of what's been selected. What's the difference, and when would I choose one over the other?
Getting the selected value Value of the selected item can be retrieved by using the SelectedValue property. It returns the property value bind to the ValueMember property. If the ValueMember is not initialized, it will return the value of the property bind to DisplayMember.
A ComboBox displays a text box combined with a ListBox, which enables the user to select items from the list or enter a new value. The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down.
SelectedText is what's highlighted. Depending on the DropDownStyle property, users can select a part of the visible text.
For example, if the options are:
A user can select the letters "Dem" in Democrat - this would be the SelectedText. This works with the ComboBoxStyle.Simple or ComboBoxStyle.DropDown, but NOT with ComboBoxStyle.DropDownList, since the third style does not allow selecting a portion of the visible item (or adding new items).
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selectedtext.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.comboboxstyle.aspx
However, using the Text property, you can pre-select an option (by setting the Text to "Other", for example, you could select the last item.)
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.text.aspx
I find it easier to see the difference using a text box:
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = "Text in combo box 1";
textBox2.Text = "Text in combo box 2";
button1.Focus();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(textBox2.SelectedText);
}
In textbox2, select part of the text and click the button.
I've used this before for primitive spell checkers, when you only want to highlight part of the textbox (not the whole value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With