使用按钮更改一个图片框中的两个图像 (VB.NET)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15819164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:07:02  来源:igfitidea点击:

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

vb.netif-statementpicturebox

提问by Exn

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.

我一直试图弄清楚为什么它长时间不起作用,任何帮助将不胜感激。

回答by Steve

You variable numis local to the method, so you could change it how you like, but everytime this code is called the variable numis 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

您的变量num是该方法的局部变量,因此您可以根据自己的喜好更改它,但是每次调用此代码时,num都会重新创建该变量并赋予默认初始值 False。
仅从您将其设置为方法的退出点开始,它就会为 True

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

要解决此问题,您需要将其声明为Shared或在类全局级别的过程之外声明它

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

回答by syed mohsin

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.

您的 num 变量在方法中,因此当您调用您的方法时,它会一次又一次地初始化并且不记得您上次设置的内容(真或假)。尝试这个。

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