views:

78

answers:

1

Hi,

I have written a custom server control which (pseudo-code) looks like

public class MyCustomCtrl : WebControl
{
   private Button innerCtrl; //some arbitrary object, doesn't matter

   ...

   protected override void CreateChildControls()
   {
      //initialization etc, as standard...

   }

}

Now I have the case that I have to copy this custom server control. Basically it is added by the programmer declaratively on the aspx or ascx code. At run-time multiple instances of this control have to be created which are then added to some parent control. This is however handled in the context of that parent control.

Anyway, it is a bit difficult to explain the context of use. My main question however is on whether it is safe to use "cloning", especially to invoke the MemberwiseClone() on web controls? What I did so far is to add a method like

public class MyCustomCtrl : WebControl
{
   ...

   public object Clone(){
      MyCustomCtrl clone = MemberwiseClone() as MyCustomCtrl;
      clone.InnerCtrl = this.innerCtrl.Clone() as Button; //or whatever type

      return clone;
   }
}

I mean the ASP.net control hierarchy is quite a complex model. So I wanted to hear whether some of you knows any drawbacks that may occur with such a solution.

+1  A: 

No, this is not a safe operation for a very general reason: MemberwiseClone is a shallow copy, not a deep copy.

So stuff like the ViewState is shared between your original control and the clone. But also the Controls collection is shared, so any change to the original Controls collection propagates to the clone. And controls use many more hidden references to maintain state (like style, events, etc.), so MemberwiseClone is a very dangerous thing to do.

The only way to reuse controls as a kind of template, is by actually using templates (ITemplate), which have an InstantiateIn method which creates a new control hierarchy. I suggest you look at controls like Repeater which do this.

Ruben
hm..that's what I expected. I've already developed controls using templates and actually the one above is used in the context of a control that wraps the repeater control. Simply speaking, the user defines once the control "MyCustomCtrl" on the ParentControl which internally wraps a repeater. Therefore when processing the ItemTemplate of the repeater, I have to copy the MyCustomCtrl and attach it to each RepeaterItem (the row basically). That's why I need copying functionality.
Juri