从代码隐藏创建aspx文本框 [英] Creating aspx textbox from codebehind
问题描述
如何在C#中从后面的代码创建aspx文本框,以及如何在后面的代码中访问其值?我按如下操作,但是在每个帖子背面的文本框都被清除了.我需要将其值保留在回发上.
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();
推荐答案
您可以从创建TextBox控件开始.必须在 Init()
( Page_Init()
)或 PreInit()
( Page_PreInit()
)方法,则无论 Page.IsPostBack
是什么,您都必须这样做.这样会将元素放在 ViewState
加载之前的页面上,并允许您在回发时检索值.
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();
然后,您应该在其上设置一些属性,包括ID,以便以后查找:
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...
然后,您需要将其添加到页面上的适当容器中( Page
,或者您希望其出现在其中的任何控件):
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);
然后在回发时,可以使用父级的 FindControl()
函数:
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;
注意:内置的 FindControl()
仅迭代直接子级.如果要搜索嵌套服务器控件的整个树,则可能需要实现自己的递归 FindControl()
函数.虽然[so]上有一百万个递归 FindControl()
函数的示例,所以我将由您自己决定.
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.
这篇关于从代码隐藏创建aspx文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!