I have a problem in PictureBox

mick

New member
Joined
Jun 25, 2007
Messages
2
Programming Experience
Beginner
I wnat the msgbox show when the two PictureBoxs have the same Image !

This is the code that I have a problem with it ! :confused:

VB.NET:
Private Sub Button1_Click(ByVal sender As system.Object, ByVal e As system.EventArgs) Handles Button1.Click
        If PictureBox1.BackgroundImage = PictureBox2.BackgroundImage Then
            MsgBox("ok")
        End If
    End Sub

and haw I can make the PictureBox Reset in code,I try this one but it doesn't work :confused:

VB.NET:
 PictureBox1.BackgroundImage.Reset()
 
Images are references to class instances, so unless they reference the exact same object they do not equal, even if these instances was created from same image file. For reference types you also have to use the Is comparison operator, using "=" operator would error "not defined for those types". Examples:
VB.NET:
        Dim img1 As Image = Image.FromFile("test.bmp")
        Dim img2 As Image = Image.FromFile("test.bmp")
        If img1 Is img2 Then MsgBox("img1 equals img2") 'is not True
        If img1 Is img1 Then MsgBox("img1 equals img1") 'is True
One could assign the same Image reference to both Pictureboxes:
VB.NET:
        PictureBox1.Image = img1
        PictureBox2.Image = img1
        If PictureBox1.Image Is PictureBox2.Image Then
            MsgBox("PictureBox1.Image equals PictureBox2.Image") 'is True
        End If
You can also use the ImageLocation to set the Image to a string path, then you can compare these strings ("=" operator is defined for String type):
VB.NET:
        PictureBox1.ImageLocation = "test.bmp"
        PictureBox2.ImageLocation = "test.bmp"
        If PictureBox1.ImageLocation = PictureBox2.ImageLocation Then
            MsgBox("PictureBox1.ImageLocation equals PictureBox2.ImageLocation") 'is True
        End If
Then again you could also keep track of what images is what and make a mark in the controls Tag property that enables you to compare:
VB.NET:
        PictureBox1.Image = img1
        PictureBox1.Tag = "test.bmp"
        PictureBox2.Image = img2
        PictureBox2.Tag = "test.bmp"
        If PictureBox1.Tag = PictureBox2.Tag Then
            MsgBox("PictureBox1.Tag equals PictureBox2.Tag, so the images are the same because I say so.") 'is True
        End If
Above was used the "Is" and "=" operators, all objects also have an Equals method, so these are also valid:
VB.NET:
If img1.Equals(img1) Then
If PictureBox1.Image.Equals(PictureBox2.Image) Then
If PictureBox1.ImageLocation.Equals(PictureBox2.ImageLocation) Then
If PictureBox1.Tag.Equals(PictureBox2.Tag) Then
...but beware of this way of writing code, if the qualifying expression for the Equals method is Nothing (null reference) the method call will throw an exception, using the operators will handle such case fine!
 
Back
Top