Search code examples
vb.netpictureboximagelist

How to Pass A Image In ImageList Collection to PictureBox


To build my skills, I am working on a little application in VB.Net for my kids that will help them with spelling words. All else aside, here's the form thus far:

Spelling App Form

When a user clicks the Next button, the 3 images in my ImageList collection gets pushed to a PictureBox control in that will appear in the upper portion of the form - I have it hidden during runtime. However, I'm only getting one single image to appear in the PictureBox, instead of all of them each time the user clicks Next. Here's the code I have wired the Next Button's click event:

Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
    'Get images and place them in the Imagebox on each click.

    Dim count As Integer
    count += 1
    If count < ImageList1.Images.Count - 1 Then
        count = 0
    End If
    PictureBox1.Image = ImageList1.Images(count)
End Sub

I cannot for the life of me get the other images to appear when clicking through. Can anyone provide me with a solution and tell me where I'm going wrong? Eventually, I want to add audio files I have pre-recorded that plays when the user clicks Next while showing the image:

"Spell the word 'Bicycle'!"

And the PictureBox contains a bicycle image, and so on. I really appreciate the assistance on how I can accomplish this. Thanks.


Solution

  • With Dim count As Integer every time you click the button count is zero cause it is a local variable. Declaring it Static the value is stored even after the button is clicked. It is like declaring it outside like Private count As Integer but only visible inside the button click sub.

    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 = 0
    
        If count > ImageList1.Images.Count - 1 Then
            count = 0
        End If
        PictureBox1.Image = ImageList1.Images(count)
    
        count += 1
    End Sub
    

    Valter