How to dynamicaly load a ASP.NET web control and add it to a ASPX page
Posted on 2003-11-26
I am having a problem loading controls dynamically at runtime.
To re-create my problem:
Create a ASPX page and add a placeholder and a button the the page.
In the code behind, in page_load, do the following:
TextBox txt = new TextBox();
txt.Text = "Hello";
txt.BackColor = Color.Yellow;
Run the page,
You will notice the textbox gets rendered correctly (text and color). Then press the button to post back...
The control never loads it's view state to set the backcolor. When the page get rendered out on postback, the backcolor is cleared.
I tested this by creating my own user control that inherits the TextBox. I overrided the SaveViewState and LoadViewState fucntions to add trace ouput so i can see when they are called. This is what i found...
When the page first loads, Save view state is called twice (not sure why?).
When the page posts back for the first time, the LoadViewState method of the control is not called.
When the page posts back again (postback 2 to infinity) the LoadViewState function is called as soon as the control is added to the placeholder controls collection.
Why is LoadviewState not called on the first postback?
Any comments would be appreciated...