Reputation: 3864
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();
Upvotes: 4
Views: 11456
Reputation: 107536
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.
Upvotes: 6
Reputation: 5604
Check this out, it gives you complete example for adding controls at runtime http://www.codeproject.com/Articles/8114/Dynamically-Created-Controls-in-ASP-NET
Upvotes: 1
Reputation: 55449
The problem is that the control won't be available on postback unless you recreate it every time, which is problematic.
One solution I've used in the past is the DynamicControlsPlaceholder, you can check it out here.
Upvotes: 1
Reputation: 6636
Create the textbox as per the code in the comment
TextBox myTextBox=new TextBox();
however, you must set an ID/Name. Additionally, you must create the text box on every postback, in the pre-render or before, so that the value will be populated. If you delay creation of the textbox to later in the page lifecycle, the value will not be populated from the postback, and then you would have to retrieve it from the Request.Response[] collection manually.
Upvotes: 0