Adding Controls to a Server Control

Usually looks like this:

 
var row = new TableRow(); 
var cell = new TableCell()
    { 
         Height = Unit.Pixel(30) 
    }); 
cell.Controls.Add( new Button() 
    { 
        Text = "Go",
        CommandName = "Go",
        ID = "btnGo" 
    }); 
row.Controls.Add(cell); 

How about this instead:

 
var row = new TableRow(); 
var cell = row.AppendControl(x => 
                  { 
                      x.Height = Unit.Pixel(30); 
                   });
cell.AppendControl(x => 
    { 
        x.Text = "Go";
        x.CommandName = "Go";
        x.ID = "btnGo"; 
    });
 

Implemented with this:

 
public static ControlExtensions 
{ 
    public static TControl AppendControl(this TControl control, Action initialization) 
        where TControl : Control, new() 
    { 
        var controlToAppend = Activator.CreateInstance();
        intialization(controlToAppend);
        control.Controls.Add(controlToAppend); 
        return controlToAppend; 
    } 
} 

I think this reads better especially if you end up appending lots of child controls, thoughts or any other solutions?

Advertisements