Wednesday, December 29, 2004

Dynamic Controls (ASP.NET)

The other day, I was discussing with someone regarding the creation of dynamic controls. Here is one simple scenario ( I hope to include this in my article which is in the writing) :

Suppose you have to create a particular textbox with a particular value depending on the value that is in the db.

Now, the textbox is 'needed' only when the user selects a particular button. So logically it would seem to create the textbox in the event of that button click.

Now here is the problem :

If the text box were to be created in a button click event. That textbox is not included in the control tree of the page. Hence, the control's value will not be able to squeeze itself into the viewstate. So when you try to get hold of that textbox on some event, you wont be able to...

1)During the page load a query is made to the db to get what value is in there

2)The particular textbox is created(during pageload) according to the value retrived from the db, with its visible property set to false.

3)This value from the db is also put in the viewstate, or cookie (as your situation calls)

4)Now when the button is clicked, the value that was store in the viewstate/cookie is retrieved, knowning that the particular textbox is already created with its visible property set to false, all we need to do at this point is to set the visible property of that textbox to true.