3
votes

I'm populating a ComboBox in C# from an instance of a class. How to get the selected item by retrieving the reference to the corresponding object ? I already used SelectedValue, SelectedItem, SelectedIndex but they all return the string representation of my object..

Thanks

[EDIT]

A piece of code, to show what I'm trying to do :

The populating part:

foreach (Business.IAuteur auteur in _livreManager.GetAuthors())
            {
                comboAuthor.Items.Add(auteur);
            }

The retrieving part, activated when clicking on the save button :

 private void btnSave_Click(object sender, EventArgs e)
        {
            Business.IAuteur auteur = new Business.Auteur();

            auteur = (Business.IAuteur)comboAuthor.SelectedValue;

            // A short verification that my item has been correctly
            // retrieved
            toolStripStatusLabel1.Text = auteur.Nom;
        }

The error message, pointing here: toolStripStatusLabel1.Text = auteur.Nom;

Object reference not set to an instance of an object.

1
Please show how you are adding the items to the combobox. Naturally if you add strings to it, you'll only get strings back.Alex J

1 Answers

5
votes

If SelectedItem is returning a string object, then you are populating your ComboBox with strings. If you override ToString in your POCOs, the ComboBox will automatically display that value while returning the desired object with SelectedItem.

As stated in MSDN, you should also override Equals in your POCO so it can be found in the Items collection if necessary.

EDIT: Addressing your code.
Lose the .ToString() call when adding to the ComboBox and follow my advice above.