Andrew
Andrew

Reputation: 5083

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?

Upvotes: 10

Views: 12145

Answers (4)

Oğuzhan
Oğuzhan

Reputation: 1

If you want to read an item text which is in a combobox, you can use [comboboxname].SelectedItem.ToString().

If you want to read an item value, use [comboboxname].SelectedValue.

Upvotes: 0

Bhavik Patel
Bhavik Patel

Reputation: 1

Try this one. It helps when the DropDownStyle property is set to DropDownList.

public string GetProdName(int prodID)
{
    string s = "";
    try
    {
        ds = new DataSet();
        ds = cmng.GetDataSet("Select ProductName From Product where ProductID=" + prodID + "");
        if (cmng.DSNullCheck(ds) && cmng.DSRowCheck(ds))
        {
            s = ds.Tables[0].Rows[0][0].ToString();
        }
    }
    catch {
    }
    return s;
}

In the click event:

lblProduct.Text = GetProdName((int)ddlProduct.SelectedValue);

Upvotes: 0

David
David

Reputation: 73564

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

Upvotes: 14

Christian Payne
Christian Payne

Reputation: 7169

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)

Upvotes: 3

Related Questions