Often ASP pages need to be created dynamically, based on data from a database for example. It is not possible to use the designer, unless you can use a repeater. When you can't, then it can be a stressfull time. Here is a small example. Don't forget, when you create your controls in the CreateChildControls method, they are stateless. After a postback they lose state. So best add the controls in the constructor.

I have a control that inherits from table row. Here is the code to fill this control:

public CCCActivityRow(string activityGuid, string unitGuid, string modGuid, bool insertMode)
{
//un = Units.GetUnit(unitGuid);
_activityGuid = activityGuid;
_unitGuid = unitGuid;
_modGuid = modGuid;
_insertMode = insertMode;
if (InsertMode)
{
BuildTable();
}
else
{
BuildTableUpdate();
}
}
private void BuildTableUpdate()
{
List<CCGrade> activegrades = Grades.GetGradesForUnit(_unitGuid);
if (activegrades != null)
{
TableCell tdDescr = new TableCell();
Label lblDescr = new Label();
lblDescr.Text = "Opzetten kamer";
tdDescr.Controls.Add(lblDescr);
HiddenField hdd = new HiddenField();
tdDescr.Controls.Add(lblDescr);
Controls.Add(tdDescr);
foreach (CCGrade grade in activegrades)
{
TableCell td = new TableCell();
td.Attributes.Add("class", "detailright");
TextBox txt = new TextBox();
txt.ID = "update." + grade.Guid;
txt.Width = 40;
td.Controls.Add(txt);
Controls.Add(td);
}
TableCell tdAction = new TableCell();
tdAction.Attributes.Add("class", "detailright");
Button btnSave = new Button();
btnSave.Click += new EventHandler(btnSave_Click);
btnSave.Text = "Save";
tdAction.Controls.Add(btnSave);
Controls.Add(tdAction);
}
else
{
TableCell tdDescr = new TableCell();
Label lblDescr = new Label();
lblDescr.Text = "This unit has no active grades!";
tdDescr.Controls.Add(lblDescr);
Controls.Add(tdDescr);
}
}

The onclick event of the save button is called when the button is clicked. Now we need to get the values out of the control. We loop over all controls in this class and read the ones we need.

void btnSave_Click(object sender, EventArgs e)
{
//Eerst een activity object aanmaken
CCActivity act = new CCActivity();
act.ModuleGuid = _modGuid;
 
foreach (Control c in this.Controls)
{
if (c.GetType() == typeof(TableCell))
{
Control txt = ((TableCell)c).Controls[0];
if (txt.GetType() == typeof(TextBox))
{
string id = ((TextBox)txt).ID;
string value = ((TextBox)txt).Text;
if (String.IsNullOrEmpty(value))
{
value = "0";
}
if (id.StartsWith("insertD"))
{
act.Description = value;
}
else
{
CCActivityGrade acgr = new CCActivityGrade();
acgr.Hours = int.Parse(value);
acgr.GradeGuid = id.Replace("insertT.","");
act.ActivityGrades.Add(acgr);
}
}
}
}
//Save Activity
}