Should I use a Winforms combobox's SelectedItem, SelectedText, or SelectedValue?

B. Clay Shannon picture B. Clay Shannon · Apr 24, 2012 · Viewed 18k times · Source

I want to pass a value in a combo box as a param to a SQL statement. The Winforms combobox gives me several options for retrieving the value, namely SelectedItem, SelectedText, and SelectedValue. Which one is best/safest to use in this scenario?

Answer

Aaron Deming picture Aaron Deming · Apr 24, 2012
if (comboBox1.DropDownStyle == DropDownStyle.DropDown || 
    comboBox1.DropDownStyle == DropDownStyle.Simple)
{
    return comboBox1.Text;
}

Text is probably the best one to use. This gets whatever is the currently selected text from the ComboBox as a string.

if (comboBox1.DropDownStyle == DropDownStyle.DropDownList)
{
    return comboBox1.GetItemText(comboBox1.SelectedItem);
}

For this style, you cannot get the text from the ComboBox. This returns the string from the item at the currently SelectedIndex instead.