I want to make a ComboBox
filled with all the colors from System.Drawing.Color
But I can't seem to collect all the colors from that collection
I've already tried using a foreach
to do the job like this:
foreach (Color clr in Color) { }
But all I get is an error.
So how can I loop trough all the colors?
Any help will be appreciated.
You could take color from KnownColor
KnownColor[] colors = Enum.GetValues(typeof(KnownColor)); foreach(KnownColor knowColor in colors) { Color color = Color.FromKnownColor(knowColor); }
or use reflection to avoid color like Menu, Desktop... contain in KnowColor
Type colorType = typeof(System.Drawing.Color); // We take only static property to avoid properties like Name, IsSystemColor ... PropertyInfo[] propInfos = colorType.GetProperties(BindingFlags.Static | BindingFlags.DeclaredOnly | BindingFlags.Public); foreach (PropertyInfo propInfo in propInfos) { Console.WriteLine(propInfo.Name); }
Similar to @madgnome’s code, but I prefer the following since it doesn’t require parsing the string names (a redundant indirection, in my opinion):
foreach (var colorValue in Enum.GetValues(typeof(KnownColor))) Color color = Color.FromKnownColor((KnownColor)colorValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With