How to clone / copy a control (with child controls) using asp.net?

5.2k Views Asked by At

I've tried a few different solutions found on here and elsewhere on the web without luck so far. Maybe one of you knowledgeable lot might be able to help...

I have a bunch of dynamically created controls by the user which I'm storing as a control collection in the session state so I can display them on every postback.

Each control that the user generates is a div with other controls inside it.

I have a button on each control that will allow the user to either delete the control or duplicate it.

When the user hits "Duplicate" I am calling my web method which handles the event.

When my web method finds the control to be duplicated, I want to make a copy of that control and add it to the page (another function deals with saving it to the control collection (on page_Unload)

 Dim DupCtrl As Control = Nothing

        Dim int As Integer = myDynControls.Count
        For i = 0 To int - 1

            If myDynControls(i).ID.Contains(ctrlID) Then
                DupCtrl = Clone_Control(myDynControls(i))
                Exit For
            End If

        Next
End Function

And the Clone_Control function :

Public Shared Function Clone_Control(OriginalControl As Object) As Object

    Dim type As Type = OriginalControl.[GetType]()
    Dim properties As Reflection.PropertyInfo() = type.GetProperties()
    Dim retObject As [Object] = type.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, Nothing, OriginalControl, Nothing)
    For Each propertyInfo As Reflection.PropertyInfo In properties
        If propertyInfo.CanWrite Then
            propertyInfo.SetValue(retObject, propertyInfo.GetValue(OriginalControl, Nothing), Nothing)
        End If
    Next
    Return retObject
End Function

Unfortunately; the line that starts PropertyInfo.SetValue.... always errors with :

"Exception has been thrown by the target of an invocation."

and when I look at the InnerException:

"Cannot get inner content of dynDiv_FormCtrl_Wrapper_10432 because the contents are not literal."

Can anyone please help point me in the right direction to get this working ?

Thanks for reading !

1

There are 1 best solutions below

1
On

I didn't understand clearly your requirment, but if you can do this in client side then jquery clone method would be a good pick.

The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

For more info Jquery .clone()