Re: Iterate through enum of system.drawing.color

Tech-Archive recommends: Fix windows errors by optimizing your registry



On Tue, 25 Aug 2009 18:07:30 -0700, Adam Sandler <corn29@xxxxxxxxxx> wrote:

Hello:

I'm trying to iterate through an enum of Colors. I'll post a very
basic example of the code for clarity. Here's the declaration:

enum myColor { Red, Blue, Black };

For now, I just have a foreach inside a button event handler:

private void button3_Click(object sender, EventArgs e)
{
foreach (System.Drawing.Color c in Enum.GetNames(typeof
(myColor)))
{
this.BackColor = c;
}
}

This bit of code does not compile. I get an error on the foreach
which says "Cannot convert type 'string' to 'System.Drawing.Color'".

Okay... I kinda get it. But I'm also under the impression that I have
to use System.Enum to parse the collection... this will not work
either: foreach (System.Drawing.Color c in myColor)

There are two reasons that won't work, and one of those reasons is the same reason you can't enumerate the names with a Color variable. It's the wrong type. Your enumerator variable is of type "Color" and the putative type of your collection would be "myColor", a completely different type from Color.

The other reason is that "myColor" is a type, not an object, and so it can't provide any enumerator that could be used in the "foreach" statement anyway.

So, the question is, how can I iterate through an enum of colors and
then use the results to assign to properties... re: the line
this.BackColor = c ???

Impossible to say without a code example that shows how you are currently mapping your enum to the Color type. But I can at least tell you how to make your enumeration work:

foreach (myColor mc in Enum.GetValues(typeof(myColor)))
{
// do something with 'mc'
}

You still can't assign the value of "mc" to something of type "Color". But at least that will allow you to enumerate the values of your enum.

Note that it's not clear to me why you have the enum at all. Unless you have some kind of indexed collection (e.g. array) that contains actual Color values that you retrieve using the int value of your enum, what's the point? Why not just have an actual collection of Color values that you use directly? We can try to provide answers to specific questions, but I suspect you'll get better value from replies that help address whatever the underlying problem you're trying to solve is. On the face of it, you don't appear to be going about it in the most efficient, simple way.

Pete
.


Quantcast