views:

170

answers:

1

Hi,

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.

+5  A: 

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.

Austin Salonen
Ok, done. I still have an error message, check the edit!
Amokrane
Ok it's working, with SelectedItem. No need to override Equals after all!Thanks !
Amokrane
If you ever want to *set* the SelectedItem, you will need to override Equals. I tend to do that as a habit now just to avoid surprises in the future.
Austin Salonen