views:

86

answers:

4

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.

+7  A: 

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);
}
madgnome
Thank you! this was exactly what I needed. I would have settled for simply all colors and then find a way to filter them to avoid the menu and desktop colors myself. Thank you very much!
Pieter888
A: 

Like this.

Andrei Bularca
+2  A: 

This is what I think you want:

foreach (Color color in new ColorConverter().GetStandardValues())
{
    MessageBox.Show(color.ToString());
}

it will loop through all the standard values for color, and should work for what you need

Richard J. Ross III
+2  A: 

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);
Konrad Rudolph