Adding references to objects in a comboBox

  • Thread starter Thread starter zfeld
  • Start date Start date
Z

zfeld

How do I add objects to a comboBox?
What I need is something similar to what there was in MFC as

MyObj obj;
ComboBox cb;

int index = cb.Add(obj.name);
cb.AddItemData(&obj, index);

Which can then be retrieved as:

int selectedIndex = cb.GetSelectedIndex();
MyObj selctedObj = reinterpret_cast<MyObj >(cb.GetItemData(selectedIndex ));

Is there any way to store a reference to the object in a C# ComboBox?
 
MyObj obj = new MyObj();
ComboBox cb = new ComboBox();
cb.Add(obj);

obj is a reference to your object.

You can get it as:

MyObj obj = (MyObj) cb.Item(index);

I hope this help you.
Bye.
Ernesto Lores
 
The problem with that, is it will display in the combo box the Tostring() of
MyObj.
The reason that this is a problem is MyObj is a complicated object with many
possible display strings (e.g its name, its author, its publisher, etc.)
The user was going to select vie a radiobutton what he wants to see
displayed in the ComboBox (names, authors, etc.)
I would re-populate the combo box with strings (MyObj.Name, MyObj.Author )
based on his choice but still have a reference to the underlying object when
one item is selected in the comboBox. I therefore can't let use the
ToString() for how would I know as to what to have the overridden ToString()
return (it might be MyObj.Name, or maybe MyObj.Author etc. )

Any other ideas?
 
zfeld said:
The problem with that, is it will display in the combo box the Tostring() of
MyObj.

What you want to do is to add a property to MyObj which returns, as a
string, the text you want displayed in the ComboBox for that object. Then
set the DisplayMember of the ComboBox to the name of that property. See the
example at ListControl.DisplayMember :
http://msdn.microsoft.com/library/d...wsformslistcontrolclassdisplaymembertopic.asp


--
Truth,
James Curran
[erstwhile VC++ MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
 
Back
Top