C# - retrieve the selected value from a combobox

28,702

Solution 1

SelectedValue will return the value of the property defined in ValueMember, SelectedItem will return the entire object that is selected, if you want to get another value other than your SelectedValue you will have to cast as the object in your ComboBox then you can access your Name property.

string temp = (cboTypeOfMaterial.SelectedItem as YourObjectType).Name;

Solution 2

Try to access the element via SelectedItem which will give you the whole object associated with that entry and then you can access the properties you need, in your case ID.

Solution 3

What you can do is to create a custom class for the entries in the comboBox. This can look like:

public class ComboBoxItem
{
    public string Display { get; set; }
    public int Id { get; set; }
    public override string ToString()
    {
        return this.Display;
    }
}

Then you can get the selected ComboBoxItem through the following code:

ComboBoxItem cbi = (ComboBoxItem)cboTypeOfMaterial.SelectedValue;
if(cbi != null)
   // Access the Property you need

Solution 4

I know this is an old question, but I'm surprised no one has mentioned:

ComboBox1.GetItemText(ComboBox1.SelectedItem)

which returns the text representation of the selected item (i.e. the DisplayMember) and is helpful in cases involving a data bound ComboBox, or any ListControl for that matter.

Share:
28,702
Leron
Author by

Leron

Updated on July 09, 2022

Comments

  • Leron
    Leron almost 2 years

    I have a comboBox with ValueMember = ID and DisplayMember = Name. I need the value that is associated with that name so I do something like this:

    if (cboTypeOfMaterial.SelectedIndex != -1)
                {
                    string temp = cboTypeOfMaterial.SelectedValue.ToString();
                    //More code here...
                }
    

    Which returns the ID value as a string. For example - "7".

    If I try :

    if (cboTypeOfMaterial.SelectedIndex != -1)
                    {
                        string temp = cboTypeOfMaterial.DisplayMember.ToString();
                        //More code here...
                    }
    

    I get the string Name which is the key.

    And what I need is to get the value of the selected element's Name

  • Leron
    Leron about 11 years
    Thanks, this works and is something new for so I'm gonna use it!