Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a button that can move during runtime. Now i need to create duplicates or copies of this control with the same events and functions. How do i do this?

I use this code to create new buttons during runtime.
VB
Dim btn1 As New System.Windows.Forms.Button
Me.Controls.Add(btn1)

The number of duplicates to be created can not be predicted.
Posted
Updated 17-Jun-15 18:47pm
v2
Comments
Ralf Meier 18-Jun-15 1:17am    
This is the right way to do it.
Where is your problem ?
Member 11644196 18-Jun-15 1:55am    
I need the new buttons to have the same functions and events as the one i already have.
Ralf Meier 18-Jun-15 1:59am    
You mean that the Event-Handler from the new Control must point to the same method as that one which is still existent ?
If yes : which Events do you mean ?
Only the Events or also the Property-Settings ?
Member 11644196 18-Jun-15 2:04am    
Yes. Mouse_down, Mouse_Up and Mouse_Move. And yes, property-settings also.
Ralf Meier 18-Jun-15 14:16pm    
Have you seen my Solution and does it match for you ...?

1 solution

OK ...
This is the Method which refers to (for example) the Click-Event. You could modify it like you need it :
VB
Private Sub WochenElement_Click(sender As Object, e As System.EventArgs)
    Dim mySender As Button = Sender

    ' do what is necessary to be done here
    ' you could also add a 'Handles' directly to the method
End Sub


Now the way to create some Buttons in a Loop :
VB
For i as integer = 1 To 6
    Dim myButton As New Button
    myButton.Backcolor = Color.Gray
    myButton.Name = "Week_" + i.ToString
    ' and other settings
    myButton.Parent = Me
    AddHandler myButton.Click, AddressOf WochenElement_Click
Next

this method-part need to be placed where you want to create the controls.

I hope this solves your question ...

Additional Information :
If you dispose your parent-Control (which hosts your in this way created elements) you have to remove all of this "Manual" created Handlers by RemoveHandler !
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900