Why not just use
comboBox.Items.Add(myObject)
? Like this...
public Form1()
{
InitializeComponent();
ComboBox cb = new ComboBox();
Colours[] colours = (Colours[])(Enum.GetValues(typeof(Colours)));
Tastes[] tastes = (Tastes[])(Enum.GetValues(typeof(Tastes)));
foreach (Colours o in colours)
{
cb.Items.Add(o);
}
foreach (Tastes o in tastes)
{
cb.Items.Add(o);
}
this.Controls.Add(cb);
cb.SelectedIndexChanged += new EventHandler(cb_SelectedIndexChanged);
}
With this being said we now need to write a method to determine which
Enum
our value comes from. :)
private Colours CurrentColor;
private Tastes CurrentTaste;
private Colours? GetColour(ComboBox cb)
{
Colours colour;
if (cb.SelectedItem != null)
{
if(!Enum.TryParse<Colours>(cb.SelectedItem.ToString(), out colour))
{
return null;
}
return colour;
}
return null;
}
private Tastes? GetTastes(ComboBox cb)
{
Tastes taste;
if (cb.SelectedItem != null)
{
if (!Enum.TryParse<Tastes>(cb.SelectedItem.ToString(), out taste))
{
return null;
}
return taste;
}
return null;
}
Now all we have to do is call these methods from
comboBox.SelectedIndexChanged
as such
void cb_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
Colours? colour = this.GetColour(cb);
Tastes? taste = this.GetTastes(cb);
if (taste.HasValue)
{
this.CurrentTaste = taste.Value;
}
if (colour.HasValue)
{
this.CurrentColor = colour.Value;
}
}