如何在点击按钮时添加无限组件

问题描述 投票:0回答:1

我有一个社交媒体WinForm。我有一个功能,基本上是当一个按钮被点击时,会产生一个新的图片框。

Public Sub NewPost()
    picture as new picturebox
    picture.Width = 208
    picture.Height = 264
    picture.Image = Form2.PictureBox1.Image
    picture.Location = New Point(258, 60)
End Sub

问题是它只能生成1个新的图片框,因为每次我想添加一个图片框,我必须做一个新的变量,每次我必须有一个新的名称。我知道我的问题是一个有点混乱,但帮助将是很好的感谢

vb.net winforms social-networking
1个回答
1
投票

如果你想为你的动态PictureBoxes捕捉事件,那么你将不得不放弃你的动态PictureBoxes。WithEvents 模型,转而使用 AddHandler.

下面是一个快速的例子,当点击PictureBox时,它的名字就会显示出来。 请注意,我没有设置一个 Location 因为它们被添加到FlowLayoutPanel中,而FlowLayoutPanel会帮你处理好位置。

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        NewPost()
    End Sub

    Public Sub NewPost()
        Dim picture As New PictureBox
        picture.Width = 208
        picture.Height = 264
        picture.BorderStyle = BorderStyle.FixedSingle
        ' ...etc...

        Dim index As Integer = FlowLayoutPanel1.Controls.Count + 1
        picture.Name = "pb" & index

        AddHandler picture.Click, AddressOf picture_Click

        FlowLayoutPanel1.Controls.Add(picture)
    End Sub

    Private Sub picture_Click(sender As Object, e As EventArgs)
        Dim pb As PictureBox = DirectCast(sender, PictureBox)
        Debug.Print(pb.Name)
    End Sub

End Class

1
投票

因为我每次都要建立一个新的变量。

不一定。 你只是想保持一个 参考 的对象。 这个引用不需要是自己的变量,它也可以是列表中的一个元素。 例如,假设在您的表单中,您有一个列表,其中包括 PictureBox 对象作为类级成员。

Dim pictureBoxes As New List(Of PictureBox)()

然后在你的方法中,你可以直接添加到这个列表中。

Public Sub NewPost()
    Dim pictureBox As New PictureBox
    pictureBox.Width = 208
    pictureBox.Height = 264
    pictureBox.Image = Form2.PictureBox1.Image
    pictureBox.Location = New Point(258, 60)
    Me.pictureBoxes.Add(pictureBox)
End Sub

在这种情况下 pictureBox 变量是本地的 NewPost 方法,并且每次都会被重新创建。 但是 pictureBoxes 是班级成员,并跟踪不断增长的名单。PictureBox 的对象。


0
投票

你可以使用for while循环来创建n个对象。


0
投票

您可以使用现有的ControlCollection

Public Function NewPost() As String
    Dim picture As New PictureBox
    'your code
    picture.Name = "Pb" & Form2.Controls.OfType(Of PictureBox).Count
    Form2.Controls.Add(picture)
    Return picture.Name
End Function

然后你就可以把它收回来

    DirectCast(Form2.Controls(NewPost), PictureBox).Image = Form2.PictureBox1.Image
    'OR
    DirectCast(Form2.Controls("Pb12"), PictureBox).Image = Form2.PictureBox1.Image
© www.soinside.com 2019 - 2024. All rights reserved.