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

Posted by Adz on Stack Overflow See other posts from Stack Overflow or by Adz
Published on 2008-10-02T09:17:57Z Indexed on 2010/05/06 1:18 UTC
Read the original article Hit count: 339

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET