Wednesday, May 13, 2009

Accessing Controls Dynamically Created During AJAX PartialPostBacks

I had an extremely annoying issue trying to be able to create textboxes dynamically within an AJAX UpdatePanel during on the PostBack.  Below is the code that I used to create a textbox, and added it to a TableCell.  It runs during an AJAX PartialPostback created on a DropDownList SelectedIndexChangedEvent.

TextBox answerText = new TextBox();
answerText.ID = "AnswerTextBox" + question.ServiceRequestQuestionId;
answerText.Attributes.Add("questionid", question.ServiceRequestQuestionId.ToString());
answerText.TextMode = TextBoxMode.MultiLine;
answerText.Style.Add(HtmlTextWriterStyle.Width, "100%");
answerText.Columns = 4;
answerText.Rows = 4;
answerText.Attributes.Add("runat", "server");
answerCell.Controls.Add(answerText);



My TextBox was showing up exactly how I wanted it to, but when I'd attempt to access the textbox after the user clicked the button submit, the textbox didn't exist anywhere on my page.  After googling for a bit, it made sense to me that I had to re-add my dynamic control to my page, but what I couldn't find was how to access the answerText.Text value from the ViewState.  I finally discovered that the TextBox had to be readded during the Page_Load or Page_Init events in order to be able to access their ViewState values, and it is only after the Page_Load event finishes that the values actually become accessible, and only if you add the objects in the some location within the heirarchy, and with the same id value.

I was thinking that somehow automagically I should be able to access this controls from the ViewState, and when I readded the control, it would override the value.  Boy was I wrong. 

No comments: