Change two images in one picture box using a button (VB.NET)

橙三吉。 提交于 2019-12-24 22:05:03

问题


I've been trying to change the image in a picture box. It works if I want to change it with one image, but I can't get it to change to the other image. It should alternate between the two images when I click the button.

Here is my code:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button1.Click

    Dim num As Boolean

    If num = False Then

        PictureBox3.Image = My.Resources.Beep
        num = True

    Else

        PictureBox3.Image = My.Resources.Skateboard
        num = False

    End If


End Sub

I've been trying to figure out why it doesn't work for a long time, any help wouldbe appreciated.


回答1:


You variable num is local to the method, so you could change it how you like, but everytime this code is called the variable num is recreated and given the default initial value of False.
It will be True just from the point in which you set it to the exit of the method

To resolve the problem you need to declare it Shared or declare it outside the procedure at class global level

Shared option

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button1.Click

    Dim Shared num As Boolean
    If num = False Then
        PictureBox3.Image = My.Resources.Beep
        num = True
    Else
        PictureBox3.Image = My.Resources.Skateboard
        num = False
    End If
End Sub

Class level option

Dim num As Boolean

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button1.Click
.....
End Sub



回答2:


Your num variable is in the method so when you call your method it initializes again and again and doesn't remember what you set it(either true or false) last time. Try this.

Dim num As Boolean

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)  Handles Button1.Click

   If num = False Then
       PictureBox3.Image = My.Resources.Beep
       num = True
   Else
       PictureBox3.Image = My.Resources.Skateboard
       num = False
End If

End Sub


来源:https://stackoverflow.com/questions/15819164/change-two-images-in-one-picture-box-using-a-button-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!