Tuesday, May 27, 2008

Dynamic Control (textbox) Creation

One problem I had with the dynamic control creation is the controls are not saved in the viewstate after postback unless you put the code of creating the controls in the Page_Load or Page_Init event.

One of the recent project I worked with required the application to create multiple labels & textboxes on the page according to user's interaction(button-click). I didn't want to create all the controls in the Page_Load and put them to different panels and hide them. One interesting thing I found (tip from co-worker) is that all the information in the textbox are saved in the viewstate no matter is pre-defined or dynamic created. In order to retreive the dynamic created textbox value, Request.Form need to be used.

According to MSDN, "The Form collection retrieves the values of form elements posted to the HTTP request body, with a form using the POST method."

The solution I used is to save the textbox.uniqueid to a hashtable and call the Request.Form[textbox's uniqueid].tostring() to retrevie the value of the textbox.

here is the link to Bilal Haidar's blog of "Loading control dynamically in ASP.net"

No comments: