Reputation: 25
I have stored the images in an array, after that, I have added an if statement to check which image is currently showing, here is my code so far but there are no results.
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
Dim img(3) As Image
img(0) = My.Resources.bugs
img(1) = My.Resources.discuss
img(2) = My.Resources.flower
img(3) = My.Resources.mask
If PictureBox1.Image Is img(0) Then
PictureBox1.Image = img(3)
End If
End Sub
Upvotes: 0
Views: 132
Reputation: 54417
There's a serious issue with your code. You should NOT access the same property of My.Resources
over and over like that. That's because it extracts the data and creates a new object every time, so you will be creating four new Image
objects every time the user clicks that Button
. You should extract the resources and populate the array once only.
That's the reason that your If
statement doesn't work. Even if they are created from the same resource, the Image
object currently in the PictureBox
is not the same object as is in your array.
You should store the index of the current image in a field and then, each time you want to go to the next image, you simply increment that field and get the Image
at that index. You can use Mod
to wrap at the end of the array.
Private images As Image() = {My.Resources.bugs,
My.Resources.discuss,
My.Resources.flower,
My.Resources.mask}
Private imageIndex As Integer = 0
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
PictureBox1.Image = images(imageIndex)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
imageIndex = (imageIndex + 1) Mod images.Length
PictureBox1.Image = images(imageIndex)
End Sub
I missed that you said "previous" rather than "next". This will work for that:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
imageIndex -= 1
If imageIndex < 0 Then
imageIndex = images.GetUpperBound(0)
End If
PictureBox1.Image = images(imageIndex)
End Sub
Upvotes: 1