0

这段代码是为一个asp.net网站写的,v2005

System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
phFname.Controls.Add(txtEFName);
placeHolder1.Controls.Add(TextBox1);

此代码在执行时始终显示文本框“”的值,即使我输入了一些字符串。

请帮忙。

4

1 回答 1

3

Dynamic controls need to be re-created each time the page loads. So you need to have that code execute during the Page_Init event. Note: You need to assign a unique ID for this control that stays the same each time the page loads.

Why all this?

Because the control is not contained in the markup (the .aspx file), you need to add it again every time the page loads. So how does it retain its value? The value will be stored in the ViewState, and as long as the control has the same ID it will be repopulated with the correct value.

To keep things running smoothly, let's put the code for adding the control in a separate function.

Private void AddMyControl()
{
   System.Web.UI.WebControls.TextBox txtEFName = new System.Web.UI.WebControls.TextBox();
   txtEFName.ID = something unique;
   phFname.Controls.Add(txtEFName);
}

So we can call it from both the click handler and the Page_Init handler, but we only need to call it in the Page_Init if we have already clicked. So let's store that as a flag inside a Session variable (you can also store it in the ViewState if you like, but let's keep it that way for now). So our click handler will now look something like this:

void ButtonSomething_Click(Object Sender, EventArgs e)
{
   AddMyControl();
   Session["MyControlFlag"] == true;
}

Now we need our Page_Init handler:

Public void Page_Init(Object Sender, EventArgs e)
{
   if(Session["MyControlFlag"]!=null && (bool)Session["MyControlFlag"])
      AddMyControl();
}
于 2013-10-03T19:10:39.663 回答