Results 1 to 3 of 3

Thread: Using dim to for picturebox events

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jan 2012
    Posts
    142

    Using dim to for picturebox events

    Hello, is it possible to
    dim i as integer = 1 to 10
    dim allpicboxes as *control?* = picturebox("picbox" & i.tostring())

    and then use the variable to e.g. change the picboxes images?
    so like

    allpicboxes.image = my.resources.something

    thanks

  2. #2
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Posts
    12,389

    Re: Using dim to for picturebox events

    Something that I do is I store all the images in a list(of image) and do something like this:
    vb Code:
    1. Option Strict On
    2. Option Explicit On
    3.  
    4. Public Class Form1
    5.     Dim list As New List(Of Image)
    6.     Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    7.         For i As Integer = list.Count To 0 Step -1
    8.             PictureBox1.Image = list.Item(i)
    9.         Next
    10.     End Sub
    11. End Class
    "Code is like humor. When you have to explain it, it is bad." - Cory House
    VbLessons | HtmlLessons | CssLessons | Code Tags | Sword of Fury - Jameram

  3. #3
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Using dim to for picturebox events

    If all the pictureboxes are in the same controls collection, you can access them like:
    Code:
    For i = 0 To 10
     DirectCast(<some container>.Controls("PictureBox " & i.toString),Picturebox).Image = <whatever>
    Next
    The key is that all controls have a controls collection. Since the form inherits from Control, it also has a controls collection. Each control is in some controls collection. Therefore, if the pictureboxes are all on the form, then they are all in the forms controls collection. If the pictureboxes are all on a panel, then they are in the panels controls collection, and so on.

    Once you know which controls collection the pictureboxes are in, the next thing to note is that controls collections hold Controls. Since Control doesn't have an Image property, you have to cast the control into the right type. Since you know that the control is a picturebox, you can use DirectCast to cast the control into type Picturebox. Once you have done that, you can access any of the picturebox properties. If the properties you want to access are part of Control, such as Name and Location, you wouldn't need to perform the cast.
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width