kunz398 kunz398 - 1 year ago 58
Vb.net Question

Easier way to clear all images in VB.Net

so i have a software when ever i click a button a image is displayed but when i click the next button another image is displayed making the previous image false

'When Button1 is clicked do'
PicBasketball.Visible = True

PicBoxing.Visible = False
PicSoccer.Visible = False
PicCanoeing.Visible = False
PicGolf.Visible = False
PicSwimming.Visible = False
PicRugby.Visible = False

Just wondering if there is a easier method to do this instead of setting each image false

Answer Source

If you're trying to show your images at the same position of your form (i.e. your picture boxes are put in the very same spot), you could get use of a List(Of T) and use only one picture box instead. Each image is then accessible via an index, which you should save in a variable to keep track of which image you are currently showing.

'Class level (outside any Sub or Function, but inside Public Class).
Dim Images As New List(Of Image)
Dim ImageIndex As Integer = 0

Adding images:

Images.Add(Image.FromFile("your file path here"))
Images.Add(your image object)

Removing images:

Images.RemoveAt(zero-based index)

Next image:

ImageIndex += 1
If ImageIndex >= Images.Count Then ImageIndex = 0 'Going back to the beginning if we're at the last image.

YourPictureBox.Image = Images(ImageIndex)

Previous image:

ImageIndex -= 1
If ImageIndex < 0 Then ImageIndex = Images.Count - 1 'Going to the last image if we're in the beginning.

YourPictureBox.Image = Images(ImageIndex)

Things to keep in mind when using a List(Of T):

  • Accessing an image is done by passing its index to the list:

    Images(3) 'Returns the fourth (4th) image.
  • The index is zero-based, meaning the first item has index 0, the second index 1 and so on (as seen in the above example index 3 = the 4th item).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download