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.
If
SelectedItemis returning astringobject, then you are populating your ComboBox with strings. If you overrideToStringin your POCOs, the ComboBox will automatically display that value while returning the desired object withSelectedItem.As stated in MSDN, you should also override
Equalsin 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.