On Page_Init, if is post back, I check if a button called Button1 was clicked, if so I add a LiteralControl to a Panel called Panel1:
Panel1.Controls.Add(new LiteralControl("Enter Code:<input type=\"text\" name=\"txtCode\"></td>"));
As you can see, it is just the text "Enter Code:" followed by a TextBox called txtCode.
I have a second button (Button2) that, when clicked, I would like to retrieve the text entered in txtCode:
protected void Button2_Click(object sender, EventArgs e)
{
foreach (Control c in Panel1.Controls)
{
if (c is LiteralControl) ...
}
}
I'm not sure how to do this... How can I get the text entered in txtCode?
You can always use the Request.Form collection:
It will contain all values posted with the current request, regardless of being server side controls or not.
The generated input doesn't persist its value after turn around (HTTP GET then POST) because it is not System.Web.UI.Control that has ViewState. So the value that user enters is in form collection and you can try to get it from there (Request.Form), but an easier way is to add a TextBox in Init(..). After that a ViewState of the textbox should be loaded on POST and you can access user's input in its Text property.
In Init():
In Button_Click: