Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms ComboBox: text vs. selectedtext

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?

like image 676
Andrew Avatar asked Feb 21 '11 20:02

Andrew


People also ask

Is used to fetch the Selected Value from ComboBox in windows forms?

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.

What is ComboBox control in C#?

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.


2 Answers

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:

  • Democrat
  • Republican
  • Independent
  • Other

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

like image 109
David Avatar answered Sep 20 '22 02:09

David


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)

like image 33
Christian Payne Avatar answered Sep 17 '22 02:09

Christian Payne