2

I am trying to create a clone of an object instance.

Creating the new instance and copying property values is no problem but the original object instance has some event handlers assigned to its events. How can I copy event handlers to the new instance?

Thanks..

Here is a code sample...

Public Sub ButtonClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
    MessageBox.Show(sender.Name + "was clicked")
End Sub

Public Sub CloneButton()
    Dim newButton = New Button
    newButton.Name = Button1.Name + "_Clone"
    newButton.Text = Button1.Text
    newButton.Width = Button1.Width
    newButton.Height = Button1.Height
    'Some code here to copy Button1's event handler ButtonClick, 
    'so when the new button is clicked "Button1_Clone was clicked" is displayed.
End Sub
e-mre
  • 3,305
  • 3
  • 30
  • 46
  • Language? Platform? Sample code please? – Jon Skeet Apr 01 '11 at 06:32
  • Please edit this into the question instead of as a comment. – Jon Skeet Apr 01 '11 at 14:35
  • Possible duplicate of [How to Attach the Events of an Original Object to a Deep Copied Clone](http://stackoverflow.com/questions/4038465/how-to-attach-the-events-of-an-original-object-to-a-deep-copied-clone) – Breeze Oct 25 '16 at 13:10

1 Answers1

1

This is freakin' old, I know, but I can't believe this guy didn't get an answer, it's been answered on SO before, right here.

Just one thing; in the example code given, miHandler will be Nothing if there is no event handler attached to the sourceObject, you should test for that.

Community
  • 1
  • 1
MarkFisher
  • 516
  • 4
  • 15