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

I tried several different solutions found here and elsewhere on the Internet without luck. Perhaps some of you knowledgeable people can help ...

I have a bunch of dynamically created user controls that I store as a collection of controls in session state, so I can display them with every postback.

Each user-created control is a div with other controls inside it.

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

When the user clicks Duplicate, I call my web method, which handles the event.

When my web method finds a duplicate of the control, I want to make a copy of this control and add it to the page (another function is to save it in the control collection (on the Unload page)

 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 InnerException:

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

Can someone help me point me in the right direction to get this to work?

Thanks for reading!

+5
source share
1 answer

I did not clearly understand your requirement, but if you can do it on the client side, then the jquery clone method would be a good choice.

.clone() , , , .

JQuery.clone()

-1

All Articles