1

I'm manipulating an excel file (using Interop). I'm trying to check the background color of a specific cell.

if (xlWorkSheet.Cells[1,j+1].Interior.Color == System.Drawing.Color.Red)
{
    cell1.Interior.Color = System.Drawing.Color.Red;
}

'Operator '==' cannot be applied to operands of type 'double' and 'System.Drawing.Color

I'm not even sure If this error make sense because I have this code which I can use it just fine. So If I can assign, why can't I compare?

cellHeader.Interior.Color = System.Drawing.Color.Red;
Clemens
  • 123,504
  • 12
  • 155
  • 268
Zkai
  • 211
  • 1
  • 3
  • 8

3 Answers3

2

To elaborate on David Smith's answer:

if (xlWorkSheet.Cells[1,j+1].Interior.Color.Equals(System.Drawing.Color.Red))
{
    cell1.Interior.Color = System.Drawing.Color.Red;
}

Certain types in c# cannot be compared using the == operator. It works for a few types, but anything other than primitive types generally use the .Equals() method instead. It serves the same purpose, but works in many more scenarios.

See here for more:

https://www.c-sharpcorner.com/UploadFile/3d39b4/difference-between-operator-and-equals-method-in-C-Sharp/

Cubemaster
  • 507
  • 1
  • 6
  • 20
  • I understand now. Still, that's not working. It's not returning any errors but my code inside the condition is not doing anything. – Zkai Aug 08 '18 at 20:09
  • Can you post a more complete segment of code? To me, it looks like you are setting red cells to be red, which is pointless. Could you maybe edit your question to include the loop that `j` is referencing? – Cubemaster Aug 08 '18 at 20:14
1

Try System.Drawing.Color.Equals:

if (xlWorkSheet.Cells[1,j+1].Interior.Color.Equals(System.Drawing.Color.Red))
maccettura
  • 10,514
  • 3
  • 28
  • 35
David Smith
  • 121
  • 3
0

I had a similar issue comparing two colors. One color was obtained using GetPixel() and the other was just a Color variable. While they appeared the same, the == operator found them different. My solution was to just compare the ToArgb() values.

To clarify... The Eqauls() method worked no differently than the == operator in this case. When I inspected the two colors in the debugger, the ARBG values were exactly the same; however, the floodColor (see code below) was show as a known color while the targetColor was not. There are also some hidden properties that were different. One was Value. I could not get a screen shot of the debugger information.

Here's the new code snippet that works correctly for me:

Color targetColor = ((Bitmap)img).GetPixel(pt.X, pt.Y);
        if (targetColor.ToArgb() != floodColor.ToArgb())
        {...
Bob_M
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 08 '22 at 06:08