In my application, depending on needs, Some TabPages will be added to a TabControl programatically. Each page will contain a ListView and two ListBoxes:
//Color Picker
var colorBox = new ListBox
{
DataSource = Enum.GetValues(typeof (KnownColor)),
Height = 40,
Width = tabFiles.Width/3,
Dock = DockStyle.Bottom
};
page.Controls.Add(colorBox);
//Style Picker
var styleBox = new ListBox
{
DataSource = Enum.GetValues(typeof(SymbolType)),
Height = 40,
Width = tabFiles.Width / 3,
Dock = DockStyle.Bottom
};
page.Controls.Add(styleBox);
Now later I want to send the selected color and symbol to another class using the code below, it compiles but at runtime it fires invalid cast. How can I fix this?
Color color = (Color)((ListBox)tabFiles.TabPages[i].Controls[1]).SelectedItem;
SymbolType symbol = (SymbolType)((ListBox)tabFiles.TabPages[i].Controls[2]).SelectedItem;
P.S: I know that color and symbol are added to page with index 1 and 2 respectivly.
Thanks.
You are getting a perfectly valid runtime exception.
System.Drawing.KnownColoris anenumwhich you are casting to aSystem.Drawing.Colorwhich is astruct, they are two very different types.The hint is in your own code. You are setting the
DataSourceof yourListBoxfrom an enumeration:If you cannot change your data source, I suggest you convert from KnownColor to Color before casting using the
Color.FromKnownColor()method.