Sharmaine Tan Si Ying
Sharmaine Tan Si Ying

Reputation: 13

How do I save System.Drawing.Color value in an array? Cannot implicitly convert type 'object' to 'system drawing color'

I am having errors Cannot implicitly convert type 'object' to 'System.Drawing.Color'.

My code is as follows:

   ArrayList columnSelection = new ArrayList();
   ArrayList colourSelection = new ArrayList();

-

   for (int i = 0; i < 6; i++)
        {
            colourSelection[i] = System.Drawing.Color.Red;
        }

-

String selection = ddlSelectColumn.SelectedValue;
String colour = ddlSelectColour.SelectedValue;

String colour1 = "System.Drawing.Color.";
colour = colour1 + colour;

for (int i = 0; i < 6; i++)
{
  if (ddlSelectColumn.SelectedValue.ToString().Equals(i.ToString()))
  {
    colourSelection[i] = colour;
  }
}

for (int a = 0; a < 6; a++)
{
  Chart3.Series[a].Color = colourSelection[a]; <---- Error message here
}

This is my whole code, please let me know how can I solve this error. Thank you in advanced.

Upvotes: 1

Views: 1788

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460208

If colourSelection is actually a string[] or an objct[] which contains the names, you can use Color.FromName("Red"); to get the Color-instance:

for (int a = 0; a < 6; a++)
{
  Chart3.Series[a].Color = Color.FromName(colourSelection[a].ToString()); 
}

But then you don't need to prefix it with System.Drawing.Color, so replace this:

String colour1 = "System.Drawing.Color."; colour = colour1 + colour;

with

String colour1 = colour;

Upvotes: 0

DavidG
DavidG

Reputation: 119017

Your colourSelection[] is an array of object instead of System.Drawing.Color. Either change it to be of the correct type (this is the preferred option as it provides type checking) or cast to Color:

Chart3.Series[a].Color = (System.Drawing.Color)colourSelection[a];

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

It seems colourSelection is an array of objects. You can't assign an object to a Color, you need to cast it:

Chart3.Series[a].Color = (Color)colourSelection[a];

You can also use as operator for a safer cast, if you are not sure the underlying type of your object.

Upvotes: 1

Related Questions