Huu Tin Huu Tin - 1 year ago 108
C# Question

Compare image in picture-box to default image

I assigned

Picturebox.Image
to Default image. But It still pass the If-statement and open new Diaglog. I don't know why? Please help me!

private void saveBtn_Click(object sender, EventArgs e)
{
if (imgBox.Image == Properties.Resources.DefaultImage || imgBox.Image == Properties.Resources.EmptyPhoto)
{
MessageBox.Show("Warning! Cannot save this image!");
}
else
{
SaveNoti save = new SaveNoti();
save.sender = new SaveNoti.SEND(Task_functions);
save.ShowDialog();
}
}

Answer Source

Because each time you read the image from resources you get a new copy and then == will return false (because it obviously compares by reference). If you will ever use bitmaps from resources in GDI+ graphics...you'd better remember this.

Save them somewhere:

static readonly Image DefaultImage = Properties.Resources.DefaultImage;
static readonly Image EmptyPhone = Property.Resources.EmptyPhoto;

Then be sure to always use them to assign imgBox.Image property (where you assign the default value):

imgBox.Image = DefaultImage; // Do not use Properties.Resources.DefaultImage

Now you can check for equality (inside the click handler):

if (imgBox.Image == DefaultImage || imgBox.Image == EmptyPhoto)
{
    MessageBox.Show("Warning! Cannot save this image!");
}

If you use it more than once just extract a method:

private bool IsDefaultImage
    => imgBox.Image == DefaultImage || imgBox.Image == EmptyPhoto;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download