R – ASP.NET WebControl & Page – Adding controls (like TextBox) dynamically

asp.netdynamic-controlsweb-controls

I'm trying to create a custom server control (WebControl) with a text box.

I add asp.net textbox to the custom control in CreateChildControls override. In OnInit override I add event handler to TextBox.TextChanged.

Everything works, except that TextChanged never fires. I looked at viewstate and it looks like my textbox never saves its Text property in the viewstate. I've tried to set Text in various places, including constructor, but nothing works.

How can I get TextBox dynamically added to WebControl to save it's Text in viewstate and get TextChanged event to fire?

I would greatly appreciate an example of WebControl code behind with TextBox being added dynamically and TextChanged event being fired.

Best Answer

The dynamically created control must be created again in each post back, (the pageInit event is the better option) for the event to be fired.

BTW, if you want the TextChanged event to generate a postback you must also set the AutoPostback of the control to true.