How do I get properties (e.g. Text) with asp.net controls that were created programatically when page loading when IsPostBack parameter is true?
Schema:
- creating control (e.g.
TextBox box = new TextBox(); box.ID = "BoxID") - display control in page (e.g.
SomeControlInPageID.Controls.Add(box)) - user see this textbox (with id
"BoxID", but we don’t have a possibility to get text property useBoxID.Text, because it control was created programatically!) in page & puts in it some text - user click in button (asp:Button) in page and start page reloading process
- start Page_Load method & IsPostBack parameter takes the true value
-
i try to use this code to get
Textproperty in Page_Load method, but it’s not work…:void Page_Load() { if (Page.IsPostBack) { TextBox box = SomeControlInPageID.FindControl("BoxID") as TextBox; string result = box.Text; } else { // creating controls programatically and display them in page ... } }
box.Text in this code always takes null value.
The key here is you need to make sure you recreate the dynamic controls each time the page is loaded. Once the controls are created, ASP.NET will be able to fill the posted back values into those controls. I’ve included a full working example below. Notice I add the control in the
OnInitevent (which will fire beforePage_Load), and then I can read the value back out in thePage_Loadevent if a postback has occurred.