0

I am doing a images slider button and i want to do this:

 For i = 1 To 8
     If PBimgprincipal.Image Is ("Picturebox"& i &".jpg").image Then PBimgprincipal.Image = Image.FromFile("picturebox" & i + 1 & ".jpg")
 Next

I already tried with

If PBimgprincipal.Image Is DirectCast(Controls("PBimg" & i), PictureBox).Image Then PBimgprincipal.Image = Image.FromFile("Figure" & i + 1 & ".jpg")
R14
  • 15
  • 4
  • It may be cool to use a single line for an `If...Then` but when that line is quite long it reduces readability of your code. – Mary Aug 07 '20 at 01:11

2 Answers2

0

You can find a control by name:

Dim matchingControls = Me.Controls.Find("PBimg" & i, true)

If matchingControls.Length > 0 Then DirectCast(matchingControls(0), PictureBox).Image = "blah"

But I'm not really sure I understood your point. Why not just scan afolder for images, keep the names in an array, then move a slider, which lets you retrieve a name from the array, load the image, and show it in a single picturebox?

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

As I am sure you found out the = operator is not defined for Image. There is a `.Equals method.

If PictureBox1.Image.Equals(Image.FromFile($"Picturebox{i}.jpg")) Then

I am using an interpolated string for the file name.

This will not solve your problem because the default implementation of equals means the 2 objects pointing to the same object in memory which is not the case. You can override the Equals function to do a size and pixel by pixel comparison but there is probably a simpler way.

Keep track of what image is being displayed in a class level variable.

Private ImageNumber As Integer

Then increment ImageNumber each time the user clicks the NextImage button up to 8.

Private Sub NextImage_Click(sender As Object, e As EventArgs) Handles NextImage.Click
    If ImageNumber = 8 Then
        ImageNumber = 1
    Else
        ImageNumber += 1
    End If
    PictureBox1.Image = Image.FromFile($"Picturbox{ImageNumber}.jpg")
End Sub

Start the whole thing off in the Forms Load event.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    PictureBox1.Image = Image.FromFile("Picturebox1.jpg")
    ImageNumber = 1
End Sub
Mary
  • 14,926
  • 3
  • 18
  • 27
  • Note that Image.FromFile locks the file on disk until the image is released in code. See https://stackoverflow.com/questions/18250848/how-to-prevent-the-image-fromfile-method-to-lock-the-file – Caius Jard Aug 07 '20 at 11:15