Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 762
B. Clay Shannon-B. Crow Raven Avatar asked Apr 24 '12 20:04

B. Clay Shannon-B. Crow Raven


People also ask

What is the difference between SelectedItem and SelectedValue?

The SelectedItem represents an object in the Items collection and the TreeView displays the value of a single property of the selected item. The SelectedValuePath property specifies the path to the property that is used to determine the value of the SelectedValue property.

What is SelectedItem in ComboBox?

When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index.


2 Answers

SelectedValue is probably the best one to use
SelectedText will give you the selected text of the editable portion, Selected Item will return you the object and selected index will return you the index. Usually for applications SelectedValue is extracted and used. Check out Combobox from MSDN

SelectedIndex   Gets or sets the index specifying the currently selected item.                (Overrides ListControl.SelectedIndex.)
SelectedItem    Gets or sets currently selected item in the ComboBox.
SelectedText    Gets or sets the text that is selected in the editable portion of a ComboBox.
SelectedValue   Gets or sets the value of the member property specified by the ValueMember property. (Inherited from ListControl.)
like image 68
Habib Avatar answered Sep 22 '22 19:09

Habib


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.

like image 44
Aaron Deming Avatar answered Sep 25 '22 19:09

Aaron Deming