ASP.net dynamic Controls on Page

liunx

Guest
First off this is not an issue as I have resolved it. However you all might find it useful during your development in ASP.net.

First off it is possible to add controls to a page at runtime. So adding a text box or RSS feed control or news based on a database. If you haven't gotten this far into developing complex websites don't worry. Its cool how it works and gives a better insight into how the page events are fired and the way controls are also.

Issue is that I had to create a Page that would dynamically create the form on the page, to handle a complex image structure that has branching based on selection.

Sounds easy at first but ran into some issues. First off I used a data List. Created a custom class populated the class from the database at page run time. Added some labels in the ItemTemplate to allow me to add the controls to a specific location in a table. All went well. Until I posted the data to the server. No control nor did I know what the name of the controls where. Usually when binding data to a control you bind it only once, in this case it wasn't creating the controls because of the way runtime added controls are handled.

What happens is you must re-bind the data to the datalist and re-create the control. Once the data is binded and all page init and load events are fired your button event will be called where you can access the controls.

Next issue is you don't know what the name of the controls were. I then added a Recursive function to iterate the pages controls looking for HtmlInputFile and HtmlTextArea control. And boom it all worked. As I was able to get a reference to the control.

Underneathe in the page, when Items are added during design time. They are coded during compile time into the structure of the output file. The ASP.net engine compiles the code into its own version with all the controls that were added during design time being changed to runtime.

On flaw is that once a control is added, it has a property of TrackViewState is called unless the property is set. However runtime also calls this but the function that built the controls is not called... no -rebinding.... unless you do not use the standard

if(!Page.IsPostBack){
//bind data.
}

The next thing is that controls do not hold state the right way if not added in the correct order. IE Setting properties of item before adding the control to the page.
If you re-bind the data in the data list then the control has ablility to iterate controls that were placed during runtime.


Just hopefully you can understand the complexities or if you have questions go ahead ask.
 
Back
Top