Wednesday, August 04, 2010

Copy a asp.net web control using clone method

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    PlaceHolder plh = new PlaceHolder();
    Literal literal = new Literal();
    literal.Text = "<a href=\"asp.net\"> link </a>";
    plh.Controls.Add(literal);            
    this.Controls.Add(plh);
    PlaceHolder plh_copied = new PlaceHolder();
    plh_copied = this.Clone(plh_copied, plh) as PlaceHolder;
    plh_copied = this.CopyControls(plh_copied, plh) as PlaceHolder;
    this.Controls.Add(plh_copied);            
}
public object Clone(object target,object source)
{
    if (source == null)
        throw new ArgumentNullException("Source");
    if(source.GetType()!=target.GetType())
        throw new ArgumentException("Type Mismatch");
    foreach (PropertyInfo p in source.GetType().GetProperties())
    {
        if (p.CanRead && p.CanWrite)
            p.SetValue(target, p.GetValue(source, p.GetIndexParameters()), p.GetIndexParameters());
    }
    return target;
}
public Control CopyControls(Control target, Control source )
{
    foreach (Control c in source.Controls)
    {
        Control cc = Activator.CreateInstance(c.GetType()) as Control;
        cc = this.Clone(cc, c) as Control;
        cc = this.CopyControls(cc, c);
        target.Controls.Add(cc);
        if (c.Controls.Count != 0)
        {
            Control d = new Control();
            d = this.CopyControls(d, c);
            target.Controls.Add(d);
        }
    }
    return target;
}

2 comments:

Juicy Jew said...

hi,
very nice solution, thanks!
I wanted to ask, though, if there is any way to also clone (and change) bound properties, for example:
I got this label:



and I want to clone it. I manged to change the "ID" property to "dish2_title_label" and any other static property, but how do I change the Text property - actually change its binding to the "md2_selected_title" column?

thanks,
Asaf

Juicy Jew said...

hi,
very nice solution, thanks!
I wanted to ask, though, if there is any way to also clone (and change) bound properties, for example:
I got this label:



and I want to clone it. I manged to change the "ID" property to "dish2_title_label" and any other static property, but how do I change the Text property - actually change its binding to the "md2_selected_title" column?

thanks,
Asaf

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...