如何在 vb.net 中将面板控件动态克隆到相同的窗体

How to clone the panel control to the same form dynamically in vb.net

我的需要是在我的表单中的同一面板下生成现有面板的副本

我已经编写了一些代码来完成我想要的工作,但它不会根据我的需要工作,但它会破坏主面板并生成一个副本,但我不想破坏第一个,我想要保留所有面板...

这是我在按钮“+”点击事件中调用的函数

Friend Function AddNewPanel() As System.Windows.Forms.Panel
        Dim Pnl As New System.Windows.Forms.Panel
        Pnl = MediPanel  'This is the main panel that I want to copy
        Pnl.Top = 500
        'Pnl.Left = 100        
        ParentPanel.Controls.Add(Pnl)  'ParentPanel in which I want to generate a copy
        Return Pnl
    End Function

This is what I exactly want but This is actually happened

所以,我想在按下“+”按钮时生成面板的副本,而且之前的面板不应该被破坏..

动态生成新控件。当您的表单加载时,为您的按钮设置一个标记,指示原始面板的底部位置。

button1.tag = Medipanel.Bottom

当您点击 + 按钮时

Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click

   Dim new_panel As New Panel
   With new_panel
     .Location = New Point(Medipanel.Left, Cint(button1.tag) + 5)
     .Size = New Size (Medipanel.Width, Medipanel.Height)
     ....
   End With

   Dim some_label = New Label
   With some_label
    .AutoSize = True
    .Name = "label"
    .Location = New Point(0, 0)  ''' Position in the new panel
    .Text = "Some Text" 
   End With
   new_panel.Controls.Add(some_label)

   Dim some_button as New Button
   With some_button
        .Tag = "some value" '''' A way to Identify the button if clicked
        ....
        ....
        AddHandler some_button.click, AddressOf some_button_click 
        '''' The Sub that determines what happens when that button is clicked.
   End With

   ....
   ....     

   ParentPanel.Controls.Add(new_panel)

   button1.tag = new_panel.bottom '''' Set the bottom position of the last panel added.

End Sub

单击新按钮时:

Private Sub some_button_click(sender As Object, e As EventArgs)

   Dim sending_button As Button = DirectCast(sender, Button)
   Dim ref As String = DirectCast(sending_button.Tag, String)

   ''''Perform your stuff here

End Sub

这只会添加一个新控件,不会破坏旧控件。