Reputation: 23
I'm trying to compare a background image for buttons in an if statement, preferably a Properties.Resourse.image
, however if need be, I can compare the background image of two buttons. The end goal is to see if the button has a background image of grey, and if it does I have an image that I want to change it with. Everything I've tried so far does not work.
First Try
public Form1()
{
InitializeComponent();
foreach (var c in this.Controls)
{
var btn = c as Button;
if (btn != null) btn.BackgroundImage = Properties.Resources.Grey;
}
}
private void btnPlay1_Click(object sender, EventArgs e)
{
if (btn00.BackgroundImage == Properties.Resources.Grey)
{
MessageBox.Show("Is a valid move");
}
}
This didn't work so after doing some research I discovered the .Equals()
function so I tried
if (btn00.BackgroundImage.Equals(Properties.Resources.Grey))
{
MessageBox.Show("Is a valid move");
}
That didn't work so I tried seeing if it worked with other buttons
if (btn00.BackgroundImage.Equals(btn01.BackgroundImage))
{
MessageBox.Show("Is a valid move");
}
However it only works when it is compared against itself
if (btn00.BackgroundImage.Equals(btn00.BackgroundImage))
{
MessageBox.Show("Is a valid move");
}
I've also tried making just a plain variable and comparing that to the button.
Upvotes: 2
Views: 1177
Reputation: 54457
The problem is that using Properties.Resources
will create a new object each time, so even Properties.Resources.Grey == Properties.Resources.Grey
would be false
. What you should do is go to Properties.Resources
once per Image
and assign the result to a field, then use that field repeatedly. That way, there will be only one Image
object and comparisons will work as expected.
Upvotes: 4