First off, I've seen a ton of posts for this same question but what I don't understand is when somebody gives an answer about "recreating the controls to page init" or ... I have the code to dynamically CREATE the text boxes but I'm not sure what else I need to add. I don't completely understand the page life cycle of asp.net web apps. I've googled this and I dont know if I'm incompetent or if all of the answers given are for people with more understanding than me.
PLEASE provide an example of what you explain.
Basically The user enteres a # into the textbox for how many "favorite books" they want to save into the database, he/she clicks the generate button.
that # of rows will populate with two textboxes, one for title and one for author. Then I would have a button they click that would save the textbox values into the database.
I know it's a simple exercise but I'm new to asp.net and it's just an exercise I came up by myself that I'm trying to learn. I'm open to new design for this but the one thing I prefer not to do is create the textboxes statically. Thanks! <3
this is the asp.net code I have
<form id="form1" runat="server">
<div>
How many favorite books do you have ?
<asp:TextBox ID="TextBox1" runat="server" Width="50px"></asp:TextBox>
<br />
<asp:Button ID="btnBookQty" runat="server" Text="GenerateBooks" OnClick="btnBookQty_Click" />
<br />
<br />
<asp:Panel ID="pnlBooks" runat="server"></asp:Panel>
</div>
</form>
and my c# code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class databasetest_panels_favBookWebsite : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnBookQty_Click(object sender, EventArgs e)
{
int count = Convert.ToInt32(TextBox1.Text);
for (int i = 1; i <= count; i++)
{
TextBox tb = new TextBox();
TextBox tb2 = new TextBox();
tb.Text = "Book " + i.ToString() + " Title";
tb2.Text = "Book " + i.ToString() + " Author";
tb.ID = "TextBoxTitle" + i.ToString();
tb2.ID = "TextBoxAuthor" + i.ToString();
pnlBooks.Controls.Add(tb);
pnlBooks.Controls.Add(tb2);
pnlBooks.Controls.Add(new LiteralControl("<br />"));
}
}
}
You don't really need to keep track of your programmatically or dynamically added controls. It's true that somehow someone has to keep track of them, but it's not you who should be doing so.
Understanding the Page Life-cycle in ASP.NET Web Forms is a must for any ASP.NET developer. Sooner or later you'll run into this sort of problems that would be greatly simplified if you really understood the underlying mechanics of the page.
Each time a request is made to the server, the whole page must be assembled from scratch. You can read (please do) on the web the many steps or stages that make up the Page Life-cycle for an ASP.NET page, but for you to have a rough idea on how this works:
When the request is made, the .aspx file is parsed and a memory source code created from it. This stage is known as the Instantiation stage, and the page's control hierarchy is created at this point.
After that, page goes through the Initialization phase, in which the page's Init event is fired. This is "the place" to add controls dynamically.
LoadViewState phase comes next. At this point, the information of the controls that are part of the page's control hierarchy get their "state" updated to make them return to the state they were before the postback. (This stage doesn't happen on the first time the page is accessed, it's a postback-only stage).
LoadPostData phase is when the data that has been posted to the server (by submitting the form) is loaded into controls. This stage is barely known to beginner ASP.NET developers, because they assume that all "state preservation" that is automatically enforced by ASP.NET engine comes from the magical Viewstate.
NOTE: If you are really serious about this, you can learn A LOT from this guy here: Understanding ASP.NET View State
What you need to remember from all the above now is that: in order for your dynamically generated controls to "have" their data "glued" together into the control's state after submitting the form by clicking this button Then I would have a button they click that would save the textbox values into the database., you need to add the controls to the page at each round-trip to the server.
The recommended way of doing so is in the Page_Init, because it comes before the LoadViewsate and LoadPostData stages where the control's state is populated.
In your case though, you don't know how many controls to add until the user fills that information on the first form submission. So, you need to find a way to add the controls to the page each time the page loads after the user entered the number of desired controls.
NOTE: You could get away with adding the controls on the btnBookQty_Click and have their data preserved correctly, because ASP.NET "plays catch-up" on the controls, but that's beyond the scope and purpose of this answer.
Add a private field to act as a boolean flag and to indicate the number of controls to add.
Create a private method that add the controls into the page, taking as argument the number of controls to add.
Call that method from within the Page_Init event handler, only if the flag dictates that some fields must be added.
In btnBookQty's click event handler set the flag to the number provided by the user of the page, and...
Call the method to create the dynamically generated controls from within btnBookQty_Click.
Here's a template code of what you need. Notice how HowManyControls property is stored in the Session to "remember" that value across postbacks:
private int HowManyControls {
get
{
if (Session["HowManyControls"] == null) return 0;
else return (int)Session["HowManyControls"];
}
set
{
Session["HowManyControls"] = value;
}
}
protected void Page_Init(object sender, EventArgs e)
{
if (Page.Ispostback && HowManyControls > 0)
{
//generate the controls dynamically
GenerateControls(HowManyControls);
}
}
protected void btnBookQty_Click(object sender, EventArgs e)
{
//get the number of controls to generate dynamically from the user posted values
HowManyControls = Convert.ToInt32(TextBox1.Text);
//generate the controls dynamically
GenerateControls(HowManyControls);
}
protected void btnSaveToDatabase_Click(object sender, EventArgs e)
{
//iterate on the control's collection in pnlBook object.
for (int i = 1; i <= HowManyControls; i++)
{
//save those value to database accessing to the control's properties as you'd regularly do:
TextBox tb = (TextBox)pnlBooks.FindControl("TextBoxTitle" + i.ToString());
TextBox tb2 = (TextBox)pnlBooks.FindControl("TextBoxAuthor" + i.ToString();
//store these values:
tb.Text;
tb2.Text;
}
}
private void GenerateControls(int count)
{
if (count == 0) { return; }
for (int i = 1; i <= count; i++)
{
TextBox tb = new TextBox();
TextBox tb2 = new TextBox();
tb.Text = "Book " + i.ToString() + " Title";
tb2.Text = "Book " + i.ToString() + " Author";
tb.ID = "TextBoxTitle" + i.ToString();
tb2.ID = "TextBoxAuthor" + i.ToString();
pnlBooks.Controls.Add(tb);
pnlBooks.Controls.Add(tb2);
pnlBooks.Controls.Add(new LiteralControl("<br />"));
}
}
EDIT
I had forgotten that ViewState is not available during Page_Init. I've now modified the answer to use Session instead.
When somebody says that "You need to keep track of the controls you create or recreate them" it means that you need to store them between postbacks.
In ASP.NET persistance can means Session variables, ViewStates and other means
See this link http://msdn.microsoft.com/en-us/magazine/cc300437.aspx
Create a list of the textboxes that you created and store it on a Session
private void CreateOrLoadTextBoxes(int numTextBoxes)
{
List<TextBox> lstControls ;
//if its the first time the controls need to be created
if(Session["lstTitleControls"] == null)
{
lstTbTitles = new List<TextBox>(numTextBoxes) ;
lstTbAuthors = new List<TextBox>(numTextBoxes) ;
//create the controls for Book Titles
for (int i = 1; i <= numTextBoxes; i++)
{
TextBox tb = new TextBox();
tb.Text = "Book " + i.ToString() + " Title";
tb.ID = "TextBoxTitle" + i.ToString();
lstTbTitles.Add(tb) ;
}
//Create the controls for Author
for (int i = 1; i <= numTextBoxes; i++)
{
TextBox tb2 = new TextBox();
tb2.Text = "Book " + i.ToString() + " Author";
tb2.ID = "TextBoxAuthor" + i.ToString();
lstTbAuthors.Add(tb2) ;
}
//store the created controls on ViewState asociated with the key "lstTitleControls" and "lstAuthorControls"
// each time you store or access a ViewState you a serialization or deserialization happens which is expensive/heavy
Session["lstTitleControls"] = lstTbTitles ;
Session["lstAuthorControls"] = lstTbAuthors ;
}
else
{
//restore the list of controls from the ViewState using the same key
lstTbTitles = (List<TextBox>) Session["lstTitleControls"];
lstTbAuthors = (List<TextBox>) Session["lstAuthorControls"];
numTextBoxes = lstTbTitles.Count() ;
}
//at this moment lstTbTitles and lstTbAuthors has a list of the controls that were just created or recovered from the ViewState
//now add the controls to the page
for (int i = 1; i <= numTextBoxes; i++)
{
pnlBooks.Controls.Add(lstTbTitles[i]);
pnlBooks.Controls.Add(lstTbAuthors[i]);
pnlBooks.Controls.Add(new LiteralControl("<br />"));
}
}
protected void Page_Load(object sender, EventArgs e)
{
CreateOrLoadTextBoxes(10) ;
}
As you have noticed I am calling the CreateOrLoadTextBoxes with a fixed value of 10
Is up to you to chane this code to take the value from the text box and call this as needed
Related
so i have an HTML table with dynamically added rows and ASP.NET text boxes. I have the rows and controls re-instantiated on page_load if the viewstate[dataonpage] = true, and I'm declaring it as true in the method that adds the rows and controls. (I need them to persist on other postbacks)
The problem is that I'm now I've added a CLEAR button that removes all of the html rows (excluding the headers) when it's clicked, and for some reason on button click it gets an index error, or if using Try/Catch it only removes half of the rows (every other row). I believe the problem is something to do with that the viewstate[dataonpage] is still "true", and the data is being re-added on page load. If i add viewstate["dataonpage"] = "false" into the clear button method, the same happens but at least this way on the second click it removes the second half of the rows.
I understand this happens because the button event handler isn't fired until after the page_load which is why it doesn't work on the first click. But what I don't fully understand is why even without this my clear button code doesn't clear all of the rows in the first place.
Any help on understanding why it doesn't work, and a work around will be greatly appreciated!
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["DataOnPage"]) == "true")
{
Getmarketdata();
}
}
protected void Getdatabtn_Click(object sender, EventArgs e)
{
ViewState["DataOnPage"] = "true";
Getmarketdata();
}
Below is method that creates adds table rows and controls:
public void Getmarketdata()
{
String url = "https://api.rightmove.co.uk/api/rent/find?index=0&sortType=1&maxDaysSinceAdded=" + Dayssinceuploadtext.Text + "&locationIdentifier=OUTCODE%5e" + Outcodetext.Text + "&apiApplication=IPAD";
Response.Write(url);
using (var webclient = new WebClient())
{
String Rawjson = webclient.DownloadString(url);
ViewState["VSMarketDataJSONString"] = Rawjson;
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(Rawjson);
int NoOfHouses = dobj["properties"].Count;
Response.Write("<br />" + NoOfHouses);
for (int i = 0; i < NoOfHouses; i++)
{
System.Web.UI.HtmlControls.HtmlTableRow tRow = new System.Web.UI.HtmlControls.HtmlTableRow();
GeneratorTable.Rows.Add(tRow);
String RMlink = String.Format("https://www.rightmove.co.uk/property-to-rent/property-" + dobj["properties"][i]["identifier"].ToString()) + ".html";
HyperLink hypLink = new HyperLink();
hypLink.Text = dobj["properties"][i]["identifier"].ToString();
hypLink.Target = "_blank";
hypLink.NavigateUrl = RMlink;
using (System.Web.UI.HtmlControls.HtmlTableCell tb1 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
tRow.Cells.Add(tb1);
tb1.Controls.Add(hypLink);
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb2 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbEPCe = new TextBox();
tRow.Cells.Add(tb2);
tb2.Controls.Add(tbEPCe);
String txtboxID = (("EPCETxtBox") + i);
tbEPCe.ID = txtboxID;
tbEPCe.Style.Add("background", "none"); tbEPCe.Style.Add("border", "1px solid black"); tbEPCe.Style.Add("border-radius", "2px");
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb3 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbEPCp = new TextBox();
tRow.Cells.Add(tb3);
tb3.Controls.Add(tbEPCp);
String txtboxID = (("EPCPTxtBox") + i);
tbEPCp.ID = txtboxID;
tbEPCp.Style.Add("background", "none"); tbEPCp.Style.Add("border", "1px solid black"); tbEPCp.Style.Add("border-radius", "2px");
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb4 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbBbl = new TextBox();
tRow.Cells.Add(tb4);
tb4.Controls.Add(tbBbl);
String txtboxID = (("BblTxtBox") + i);
tbBbl.ID = txtboxID;
tbBbl.Style.Add("background", "none"); tbBbl.Style.Add("border", "1px solid black"); tbBbl.Style.Add("border-radius", "2px");
}
}
}
}
Below is clear table rows method: (this is the one that isn't working)
public void ClearTableRows()
{
System.Web.UI.HtmlControls.HtmlTable Htmlgeneratortable = ((System.Web.UI.HtmlControls.HtmlTable)GeneratorTable);
int NoOfRows = Htmlgeneratortable.Rows.Count;
for (int j = 1; j < NoOfRows; j++)
{
try
{
Htmlgeneratortable.Rows.RemoveAt(j);
}
catch
{ }
}
}
I'm going to explain what's going on as you have the code written now; I don't have faith in my ability to provide an answer including the exact code changes to be made, so here is what is wrong with your current approach:
Your table, GeneratorTable exists for all clients. That doesn't mean every time someone navigates to your website a table is generated, it means that there is one table, and every client that logs in is getting that one table.
So if you add rows to it for one client, then send the table to another client, both clients will see the same table (with the rows added).
The problem is that emptying out a table is logic that has nothing to do with your back-end server. There's no reason for your server to be handling emptying a table, your server should only handle page navigations and AJAX calls pretty much, it shouldn't be changing how the webpage looks, because the server can only respond to each client one time.
What's the point in responding to a client with GeneratorTable and then updating GeneratorTable on the server? The client will never see the updates made to the table unless they're resent from the server.
You stated that you are new to this and need to learn about JS and client-side, this exercise should serve as an example of why you need to put certain code on the front-end and some code on the back-end, as there isn't really an elegeant way to do what you're looking to do with just the server.
I have created a panel in my page view (tour.aspx file).
Now I want to access it in my class file (add_tour.cs file).
This is my panel:
<asp:Panel ID="itinerary_panel" runat="server"></asp:Panel>
This is my code behind tour.aspx file:
add_tour tour_obj = new add_tour();
int days_count = 2;
tour_obj.textbox_generator(days_count);
And this code is in add_tour.cs file:
public void textbox_generator(int days_count)
{
}
Now how to access the panel from aspx file?
Please help.
There's no need to actually add the text boxes to the panel from this class.
public List<TextBox> textbox_generator(int days_count)
{
var textBoxes = new List<TextBox>();
for(int i = 0; i < days_count; i++)
{
txt_desc = new TextBox();
txt_desc.ID = "txt_desc" + i.ToString();
txt_desc.CssClass = "form-control";
txt_desc.Attributes.Add("placeholder", "Enter day " + i + " description");
txt_desc.TextMode = TextBoxMode.MultiLine;
textBoxes.Add(txt_desc);
}
return textBoxes;
}
Then change your code behind to:
add_tour tour_obj = new add_tour();
int days_count = 2;
var textBoxes = tour_obj.textbox_generator(days_count);
foreach(var textBox in textBoxes)
{
itinerary_panel.Controls.Add(textBox);
}
Note that you need to be careful where you add these controls in the page lifecycle. See Microsoft documentation.
This keeps your textbox_generator from needing to know anything about the specific page using it.
Also, you should really align your naming conventions with C# standards. Use PascalCasing. textbox_generator should be TextBoxGenerator etc. And you can probably make textbox_generator into a static method if it doesn't need to access any fields or properties of its class.
If you really wanted your other class to itself add the controls directly to the panel, then you would just pass a reference to the panel from the code behind to the class.
public void textbox_generator(int days_count, Panel panel)
{
for(int i = 0; i < days_count; i++)
{
txt_desc = new TextBox();
txt_desc.ID = "txt_desc" + i.ToString();
txt_desc.CssClass = "form-control";
txt_desc.Attributes.Add("placeholder", "Enter day " + i + " description");
txt_desc.TextMode = TextBoxMode.MultiLine;
panel.Controls.Add(txt_desc);
}
}
and call this this way from your code behind:
add_tour tour_obj = new add_tour();
int days_count = 2;
var textBoxes = tour_obj.textbox_generator(days_count, itinerary_panel);
This works because itinerary_panel actually is a reference to the panel. See Passing Objects By Reference or Value in C#. However, it's often a bad idea to have a method modify the state in that manner.
I created a range validator and would like to trigger it once the submit button was clicked.
RangeValidator rv_tbAbsenceDay = new RangeValidator();
rv_tbAbsenceDay.ID = "rv_tbAbsenceDay" + tbAbsenceDay.ID;
rv_tbAbsenceDay.ControlToValidate = tbAbsenceDay.ID;
rv_tbAbsenceDay.EnableClientScript = true;
rv_tbAbsenceDay.Display = ValidatorDisplay.Dynamic;
rv_tbAbsenceDay.MinimumValue = DateTime.Now.AddMonths(-6).ToString("d");
rv_tbAbsenceDay.MaximumValue = DateTime.Now.ToString("d");
rv_tbAbsenceDay.ErrorMessage = "Date cannot be older than 6 months and not in the future.";
rv_tbAbsenceDay.SetFocusOnError = true;
plcMyStaff.Controls.Add(rv_tbAbsenceDay);
plcMyStaff is a placeholder.
<asp:PlaceHolder ID="plcMyStaff" runat="server"></asp:PlaceHolder>
How do I get hold of the created range validator to trigger it i.e. rv.validate(); ?
I have tried this:
protected void MarkAsSick_Command(Object sender, CommandEventArgs e)
{
DropDownList tempddlReason = (DropDownList)plcMyStaff.FindControl("ddlReason" + e.CommandArgument.ToString());
TextBox temptbAbsenceDay = (TextBox)plcMyStaff.FindControl("tbAbsenceDay" + e.CommandArgument.ToString());
TextBox temptbLastDayWorked = (TextBox)plcMyStaff.FindControl("tbLastDayWorked" + e.CommandArgument.ToString());
RangeValidator temprv_tbAbsenceDay = (RangeValidator)plcMyStaff.FindControl("rv_tbAbsenceDay" + e.CommandArgument.ToString());
temprv_tbAbsenceDay.validate();
...
Hope you can help me.
thanks,
Andy
First off to debug this I would suggest examining the plcMyStaff object in which you are adding the control to see if it does in fact contain the control you wish to access.
You should be able to retrieve it from the Page object that your webform inherits.
Page.FindControl();
// Or you can Iterate through each control to see what the control is called and test for the name you want
foreach (var control in Page.Controls)
{
}
i'm having issues retreiving the values out of a dynamically created dropdownlist. all controls are created in the Page_Init section. the listitems are added at that time as well from an array of listitems. (the controls are named the same so should be accessable to the viewstate for appropriate setting.)
here is the function that attempts to retrieve the values:
protected void Eng98AssignmentComplete_Click(object sender, EventArgs e)
{
String myID = "0";
Page page = Page;
Control postbackControlInstance = null;
// handle the Button control postbacks
for (int i = 0; i < page.Request.Form.Keys.Count; i++)
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
//Response.Write(page.Request.Form.Keys[i].ToString());
if (postbackControlInstance is System.Web.UI.WebControls.Button)
{
myID = Convert.ToString(
postbackControlInstance.ID.Replace("button_", ""));
}
}
String txtholder = "ctl00$ContentPlaceHolder$Eng098Instructors_" + myID;
Response.Write("MYID: " + myID + "<br/>");
DropDownList ddInstructorCheck = (DropDownList)Page.FindControl(txtholder);
Response.Write("Instructor Selected: "
+ ddInstructorCheck.SelectedValue + "<br/>");
}
here is the output I get, no matter which instructor was selected.....
MYID: 1_1
Instructor Selected: 0
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
the name of the control is correct (verified via view source)....
ideas?
You're going to a lot of work to build this fancy string:
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
That is the client ID of your control, not the server id. This code is running on the server side, and so you need the server id. To get that control using the server id, you need to do this:
ContentPlaceHolder.FindControl("Eng08Instructors_1_1");
Notice I didn't look in the page, because your content place holder created a new naming container.
Also, the way your loop is set up the myID variable will always end up holding the last button in the Keys collection. Why even bother with the loop?
Based on your comments, a better way to find the id of the dropdownlist is like this:
string id = ((Control)sender).ID.Replace("button_", "Eng098Instructors_");
why not just save the control in an instance in your class so that you don't have to use FindControl?
Do you also re-create the controls during the postback? Dynamically generated/added controls must be re-created with every request, they are not automatically re-created.
Why don't you cast the sender? This should be the button that caused the postback:
string myId = "0";
Button btn = sender as Button;
if (btn != null)
myId = btn.ID
...
You need to perform something like this because the UniqueID property is the key in Request.Form.
List<Button> buttons = new List<Button>();
List<DropDownList> dropdowns = new List<DropDownList>();
foreach (Control c in Controls)
{
Button b = (c as Button);
if (b != null)
{
buttons.Add(b);
}
DropDownList d = (c as DropDownList);
if (d != null)
{
dropdowns.Add(d);
}
}
foreach (String key in Request.Form.Keys)
{
foreach (Button b in buttons)
{
if (b.UniqueID == key)
{
String id = b.ID.Replace("button_", "");
String unique_id = "ctl00$ContentPlaceHolder$Eng098Instructors_" + id;
Response.Write("MYID: " + id + "<br/>");
foreach (DropDownList d in dropdowns)
{
if (d.UniqueID == unique_id)
{
Response.Write("Instructor Selected: " + d.SelectedValue + "<br/>");
break;
}
}
}
}
}
I'm not sure why you are generating the control in code (you can still add items dynamically if you do), but the code that generates the controls would probably be a huge help here. I'm guessing you are not setting the list item value, and instead just setting the list item text. Try seeing what you get from the SelectedText field and post your control creation function.
EDIT:
In response to your comment on #Martin's post, you said "yes I recreate the controls in the Page_Init function each time the page is created (initial or postback)". Are you also setting the selected value when you create them?
You can also use controls on the page even if your data comes from a database, the controls themselves don't have to be dynamically generated.
How about this?
((Button)sender).Parent.FindControl(myid)
Edit:I misunderstood your question. But i think you should follow page lifecycle. it is common issue for dynamically created controls.
I did some research and here is some info about Dynamically Created Controls may help you...
I had 2 catches.... here's what they were.
1. I didn't clear the table I was adding to before re-creating the controls.
apparently my attention to detail was off yesterday, i'm pretty sure the ctlXX frontrunner of the control was some different number upon postback due to how I was recreating the controls.
2. I was assigning the same list to all the dropdownlist controls.
once I called the lookup upon each creation a dropdownlist control, all works well.
anyway for what it's worth....
I have an input field on my page where the user will type in the number of text inputs they want to create. The action for the button is:
int num_flds = int.Parse(a_fld.Text);
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
}
Now, I have another button that the user would click after they have filled in all their dynamically-created text boxes. Questions, first of all, am I creating the text boxes dynamically in the correct place? How would I get the values out of the dynamically-created text boxes? (The dynamically-created text boxes are being added to the Panel "answer_inputs".
I recommend reading this and a few other articles about the topic of dynamically created controls. It is not quite as straightforward as you might think. There are some important page lifecycle issues to consider.
When creating web controls dynamically, I find it best to have the controls themselves report in the answers. You can achieve it like this:
Create something in your Page class to store the values:
private readonly Dictionary<TextBox, string> values=new Dictionary<TextBox, string>();
Make a method to act as a callback for the textboxes when their value changes:
void tmp_TextChanged(object sender, EventArgs e)
{
TextBox txt = sender as TextBox;
if(txt!=null)
{
values.Add(txt,txt.Text);
}
}
And then add this method to each textbox as they are added:
int num_flds;
if(!int.TryParse(a_fld.Text,out num_flds))
{
num_flds = 0;
}
for (int i = 0; i < num_flds; i++)
{
TextBox tmp = new TextBox();
tmp.ID = "answer_box" + i;
tmp.Width = Unit.Pixel(300);
answer_inputs.Controls.Add(tmp);
tmp.TextChanged += tmp_TextChanged;
}
Finally, you iterate through the dictionary on callback to see if it holds any values. Do this in the OnPreRender method for instance.
Edit: There is a problem with this, if the number of text fields are decreased on postback. Some safe way to recreate the previous textfields on postback should be employed.