I'm having some trouble with TextBox (dynamically).
My application have a textbox to enter number of answer (txtNum), a button (btnAdd) to show textboxes for enter answer (with number gived), a button(btnSubmit) to get value of textboxes that entered answer.
I decided put textboxes (dynamically) in PlaceHolder with
Follow is code of btnAdd:
protected void btnAdd_Click(object sender, EventArgs e)
{
int numAns= Convert.ToInt32(txtNum.Text.Trim());
for (int i = 1; i <= numAns; i++)
{
TextBoxesHere.Controls.Add(new TextBox());
}
}
and code of btnSubmit:
protected void btnSubmit_Click(object sender, EventArgs e)
{
String[] arr = new String[10];
int count=0;
foreach (Control c in TextBoxesHere.Controls)
{
if (c.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") && c.ID == null)
//c.ID = null means that textboxes were not entered
{
arr[count] = ((TextBox)c).Text;
Response.Write(arr[count].ToString());
count++;
}
}
}
After I entered 3 for number of answer, web page show 3 textboxes. Then, i entered data for them but when I click SUbmit button, web page didn't display anything...
Wha'ts wrong???? :(
Thanks for read and hope explained soon!
Shawn HolmanPosted Sep 26, 2008, 4:36 PM
When you are creating dynamic controls, you have readd the control to the page each time on postback on order to give the viewstate something to work with. This is the easiest way for me to explain this, also check out this article:
http://weblogs.asp.net/infinitiesloop/archive/2006/10/16/TRULY-Understanding-Dynamic-Controls-_2800_Part-3_2900_.aspx