To get selected item, you have to use SELECTEDITEM property of comboBox. And since this is an Object, if you wanna assign it to a string, you have to convert it to string, by using ToString() method:
string myItem = comboBox1.SelectedItem.ToString(); //this does the trick
From the documentation:
You can use the SelectedText property to retrieve or change the currently selected text in a ComboBox control. However, you should be aware that the selection can change automatically because of user interaction. For example, if you retrieve the SelectedText value in a button Click event handler, the value will be an empty string. This is because the selection is automatically cleared when the input focus moves from the combo box to the button.
When the combo box loses focus, the selection point moves to the beginning of the text and any selected text becomes unselected. In this case, getting the SelectedText property retrieves an empty string, and setting the SelectedText property adds the specified value to the beginning of the text.
or try this code
String status = "The status of my combobox is " + comboBoxTest.SelectedItem.ToString();
I think you dont need SelectedText
but you may need
String status = "The status of my combobox is " + comboBoxTest.Text;
All of the previous answers explain what the OP 'should' do. I am explaining what the .SelectedText
property is.
The .SelectedText
property is not the text in the combobox
. It is the text that is highlighted. It is the same as .SelectedText
property for a textbox
.
The following picture shows that the .SelectedText
property would be equal to "ort".
Try this:
String status = "The status of my combobox is " + comboBoxTest.text;
If you bind your Combobox to something like KeyValuePair, with properties in the constructor like so...:
DataSource = dataSource,
DisplayMember = "Value",
ValueMember = "Key"
so dataSource
is of type KeyValuePair...
You end up with having to do this...
string v = ((KeyValuePair)((ComboBox)c).SelectedItem).Value;
(I had a Dynamic form - where c
was of type Control
- so had to cast it to ComboBox)
I face this problem 5 minutes before.
I think that a solution (with visual studio 2005) is:
myString = comboBoxTest.GetItemText(comboBoxTest.SelectedItem);
Forgive me if I am wrong.
Here's how I would approach the problem, assuming you want to change the text of say, a label
private void comboBoxtest_SelectedIndexChanged(object sender, EventArgs e)
{
var combotext = comboBoxtest.Text;
var status = "The status of my combo box is" + combotext;
label1.Text = status;
}
Source: Stackoverflow.com