I have a VB.Net application which has spelling words that a child can type in and it verifies the spelling. On the form, I have a Next and Back button, which advances a PictureBox
with items contained in an ImageList
. I have 3 items in the ImageList
collection with an index[2]
.
Here's the code that I'm using to advance the Next button to display the next image in the collection:
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
'Get images and place them in the Imagebox on each click.
Static count As Integer = 1
If count > ImageList1.Images.Count - 1 Then
count = 0
End If
PictureBox1.Image = ImageList1.Images(count)
count += 1
End Sub
While this works, I cannot figure out how to get this to work in the reverse order. Here's the OnLoad
event handler that starts with the first image in the collection:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Set picturebox with initial picture
PictureBox1.Image = ImageList1.Images(0)
txtSpell.Focus()
End Sub
How can I get the Back button to go backwards in the index from it's current point in the index which is shown in the PicutureBox
control? This is where I'm stumped. Tried to re-write the code several times, if I click Next once, I go to the next image index[1]
and if click the Back button, it takes me to index[0]
.
But if click next again, PictureBox jumps to index[2]
the last image, rather than going back to index[1]
. If I click Back again, the code is blowing up.
Move your count
variable (which is badly named, BTW - I've used CurrIdx
instead) to a higher visibility. In the previous button's click handler, decrement the index; if it drops below 0, reset it to the ImageList.Images.Count - 1
again. I'd also move the code that actually sets the image index to its own procedure, so that you're not repeating yourself and it's more clear. Something like this should work for you:
Private CurrIdx As Integer = 0
Private Sub UpdateImage()
PictureBox1.Image = ImageList1.Images(CurrIdx)
End Sub
Private Sub PrevButton_Click(sender As Object, e As EventArgs) Handles PrevButton.Click
CurrIdx -= 1
If CurrIdx < 0 Then
CurrIdx = ImageList1.Images.Count - 1
End If
UpdateImage()
End Sub
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
CurrIdx += 1
If CurrIdx > ImageList1.Images.Count - 1 Then
CurrIdx = 0
End If
UpdateImage()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
UpdateImage()
End Sub