How could I copy a control and place it in another location?

daveofgv

Well-known member
Joined
Sep 17, 2008
Messages
218
Location
Dallas, TX
Programming Experience
1-3
Hello All -

Does anyone know how to copy a control (button, panel etc...) and place the control with the same click event on another part of a form while keeping the original in the same location?

I have a custom user control that I created that has special features on click. If I have the control on the left side and want to drag it over to the right side I want the control duplicated, as this control can be duplicated unlimited times, and still have the same click event.

Hope I am not confusing.

(Kinda like Visual Studio ide).... you can drag and drop a button on a form many times.

Thanks

daveofgv
 
The easiest way to use the same event handler is to call AddHandler for an event.

Since you didn't state what event you wanted to duplicate, I'll use your button example with a click event:

NOTE: This code is not tested, but should be close enough to give you an idea of how to do this.

VB.NET:
  Private Sub NewButtonClickEventHandler(ByVal sender As Object, ByVal e As EventArgs)
    ' Do what ever you need to do here with the button click event
  End Sub

  Private Sub Form1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragDrop
    ' I left it up to you to determine what is being dropped

    ' Create the new control
    Dim oNewControl As Control
    oNewControl = New Windows.Forms.Button()

    With oNewControl
      ' Place the control at the mouse drop location
      .Location = New Point(e.X, e.Y)

      ' You will want to change this so it uses a unique name with every 
      ' control created or you can leave it unassigned to get a default name
      .Name = "MyNewButton"
    End With
    AddHandler oNewControl.Click, AddressOf NewButtonClickEventHandler

    ' Very important to add the control to a container control
    ' In this case, the Windows Form
    Me.Controls.Add(oNewControl)
  End Sub
 
Back
Top