Even if you place controls inside form control, you won't be able to retrieve the value on postback.
The problem with dynamic control is you will need to reload the control (with same id) on every post back of the page.
Otherwise, they'll not be in the control tree, and you won't be able to find them.
Here is a sample. It loads TextBox control dynamically, and displays the value back when Submit button is clicked.
ASPX
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Button runat="server" ID="OkButton" OnClick="OkButton_Click" Text="Ok" />
<asp:Button runat="server" ID="SubmitButton" OnClick="SubmitButton_Click" Text="Submit" />
<asp:Label runat="server" ID="MessageLabel" />
Code Behind
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
LoadControls();
}
}
protected void OkButton_Click(object sender, EventArgs e)
{
LoadControls();
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
var myTextBox = FindControlRecursive(PlaceHolder1, "MyTextBox") as TextBox;
MessageLabel.Text = myTextBox.Text;
}
private void LoadControls()
{
// Ensure that the control hasn't been added yet.
if (FindControlRecursive(PlaceHolder1, "MyTextBox") == null)
{
var myTextBox = new TextBox {ID = "MyTextBox"};
PlaceHolder1.Controls.Add(myTextBox);
}
}
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
thisin this context? Probably a Page right? And if the form with therunat="server"attribute is within the Page, then it stands to reason you're not adding your controls to a form with therunat="server"attribute, you're adding them to its parent.