Creating aspx textbox from codebehind

asp.net, c#

Solution

You can start by creating the TextBox control. It must be done in the `Init()` (`Page_Init()`) or `PreInit()` (`Page_PreInit()`) method, and you have to do it regardless of `Page.IsPostBack`. This will put the element on the page before the `ViewState` is loaded, and will allow you to retrieve the value on postback.

var textBox = new TextBox();

Then you should set a few properties on it, including an ID so you can find it later:

textBox.ID = "uxTxtSomeName";
textBox.MaxLength = 10; // maximum input length
textBox.Columns = 20; // character width of the textbox
etc...

Then you need to add it to an appropriate container on the page (`Page`, or whichever control you want it to appear within):

parentControl.Controls.Add(textBox);

Then on post back, you can retrieve the value, probably in the `Load()` method (`Page_Load()`) using the parent's `FindControl()` function:

var input = (parentControl.FindControl("uxTxtSomeName") as TextBox).Text;

Note: The built-in `FindControl()` only iterates through immediate children. If you want to search through the entire tree of nested server controls, you may need to implement your own recursive `FindControl()` function. There are a million and one examples of recursive `FindControl()` functions on [so] though, so I'll leave that up to you.

Problem

how can I create aspx textbox from code behind in C# and how to access its value in code behind ? I do as follows but on every post backs text box is getting cleared. I need to keep its values on post backs. ``` TextBox txt = new TextBox(); txt.ID = "strtxtbox"; txt.CssClass = "CSS1"; StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); HtmlTextWriter htmlWriter = new HtmlTextWriter(writer); txt.RenderControl(htmlWriter); //lbl is an aspx label lbl.text += @"<td style='width: 5%;'>" + sb.ToString() + "</td>"; ``` And I access text box value as follows ``` string tb = Request.Form["strtxtbox"].ToString(); ```

Original source