如何在Panel Control中动态创建控件

时间:2014-02-26 11:54:48

标签: vb.net for-loop

我想在Panel中创建5个PictureBox控件

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

每次我运行时,面板上的最后一个位置只有一个图片框控件。如何在不使用FlowLayoutPanel

的情况下将5个图片框放在此面板中

我还没有使用任何"步骤"对于它,但每次n增加,如n + = 2.为什么这样增加,即使我声明n = n + 1?

2 个答案:

答案 0 :(得分:2)

您似乎在向Panel添加了对同一个图片框的五个引用。我建议你移动:

Dim a As PictureBox = New PictureBox

在For循环中,作为执行的第一个语句。

答案 1 :(得分:2)

您可以像这样简化代码:

    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)