简体   繁体   中英

How to create control dynamically in a Panel Control

I want to create 5 PictureBox controls in a Panel

Dim a As PictureBox = New PictureBox
Dim loc As Point = New Point(0, 0)

    For n As Integer = 0 To 4
        a.Location = loc
        a.Size = New Size(100, 100)
        a.BorderStyle = BorderStyle.Fixed3D
        a.BackColor = Color.Aqua
        Panel1.Controls.Add(a)
        n = n + 1
        loc = a.Location + New Point(50, 50)
    Next

Everytime I run there is only one picturebox control in the panel at the last location it get from the loop. How to have my 5 pictureboxes in this panel without using FlowLayoutPanel

There is also another problem about the loop which I didn't use any "step" for it but for each time n increase like n + = 2. why is this increasing like this even I declare n = n + 1?

You seem to be adding five references to the same picture box to the Panel. I would suggest you move the:

Dim a As PictureBox = New PictureBox

to within the For loop, as the first statement executed.

You can simplify your code like this:

    Dim PicBoxes(4) As PictureBox

    For Index As Integer = 0 To PicBoxes.Length - 1

        PicBoxes(Index) =
            New PictureBox With
                {
                  .Location = New Point(50 * Index, 50 * Index),
                  .Size = New Size(100, 100),
                  .BorderStyle = BorderStyle.Fixed3D,
                  .BackColor = Color.Aqua
                }

    Next Index

    Panel1.Controls.AddRange(PicBoxes)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM