Many times one need to create controls and add them to an ASP.NET page/control from code. Sharepoint is the master example when this need is more somewhat of a rule than exception.
Looking at the dull Sharepoint webpart code sample at MSDN (in my opinion) show the tedious task of constantly creating, configuring and adding controls to other control containers.
Knowing that Jquery has the abillity to chain methods one after another, and .NET’s abillity to write extension methods the ingridients are set up for some .NET chained method extension voodo ;)
About the sample
In this simple demo I want to show the same pattern for creating a simple UI with first creating control in the same manner as the MSDN example, and secondly with extension methods, after the demo I will show/talk about the solution.
“Msdn-style”
using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page {
protected Button btnSubmit;
protected TextBox txtUsername;
protected void Page_Load(object sender, EventArgs e) {
var t = new HtmlTable();
plcControlContainer.Controls.Add(t);
// row1
var r = new HtmlTableRow();
t.Rows.Add(r);
var c = new HtmlTableCell(); // cell1
r.Cells.Add(c);
var ctrl = new Label();
// set properties
ctrl.Text = "Username";
ctrl.ToolTip = "your selected username";
c.Controls.Add(ctrl);
c = new HtmlTableCell(); // cell2
r.Cells.Add(c);
txtUsername = new TextBox();
c.Controls.Add(txtUsername);
// row 2
r = new HtmlTableRow();
t.Rows.Add(r);
c = new HtmlTableCell(); // cell1
r.Cells.Add(c);
c = new HtmlTableCell(); // cell2
r.Cells.Add(c);
btnSubmit = new Button();
// set properties
btnSubmit.Text = "Submit";
btnSubmit.CssClass = "submit";
btnSubmit.Click += new EventHandler(btnSubmit_Click);
c.Controls.Add(btnSubmit);
}
}
More...