简体   繁体   中英

How do you 'clone' WebControls in C# .NET?

My basic question is, in .NET, how do I clone WebControls?

I would like to build a custom tag, which can produce multiple copies of its children. Ultimately I intend to build a tag similar to in JSP/Struts.

But the first hurdle I have is the ability to duplicate/clone the contents of a control.

Consider this rather contrived example;

<custom:duplicate count="2">
    <div>
        <p>Some html</p>
        <asp:TextBox id="tb1" runat="server" />
    </div>
</custom:duplicate>

The HTML markup which is output would be something like,

<div>
    <p>Some html</p>
    <input type="text" id="tb1" />
</div>
<div>
    <p>Some html</p>
    <input type="text" id="tb1" />
</div>

Note: I know i have the id duplicated, I can come up with a solution to that later!

So what we would have is my custom control with 3 children (I think) - a literal control, a TextBox control, and another literal control.

In this example I have said 'count=2' so what the control should do is output/render its children twice.

What I would hope to do is write some "OnInit" code which does something like:

List<WebControl> clones;
for(int i=1; i<count; i++)
{
    foreach(WebControl c in Controls) 
    {
        WebControl clone = c.Clone();
        clones.Add(clone);
    }
}

Controls.AddRange(clones);

However, as far as I can tell, WebControls do not implement ICloneable, so its not possible to clone them in this way.

Any ideas how I can clone WebControls?

What's wrong with using a Repeater and binding a dud data source. It'll duplicate the templated controls and handle the ID creation and all.

Just as a reference for others which really want to clone a custom server control .

public class MyCustomServerCtrl
{

   ...

   public MyCustomServerCtrl Clone()
   {
      return MemberwiseClone() as MyCustomServerCtrl;
   }

}

But note: this is needed very rarely and if so, most probably just when you're having some really specific logic. It should be avoided when possible. Generally it should be enough to use existing controls like Repeater, ListView etc..

The way to do this in ASP.NET is using templates. There are samples in MSDN for this, just look for templated controls / ITemplate.

The WebControl.CopyBaseAttributes method copies the AccessKey, Enabled, ToolTip, TabIndex, and Attributes properties from the specified Web server control to the Web server control that this method is called from.

MSDN Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM