我曾经发过一个帖子问这样的问题: 在下面的代码中,我想实现的是: (1) 第一次打开网页,TextBox中的文本为"Good Morning." (2) 单击Button,形成Postback,然后更改TextBox的文本为"Good Afternoon" 可是不管怎样,TextBox的文本总是 "Good Morning.", 请各位帮我看看是什么原因。 (我不想捕捉Button的Onclick事件) C# code public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button button1 = new Button(); button1.Text = "Click"; button1.ID = "button1"; TextBox textBox1 = new TextBox(); textBox1.Text = "Good Morning."; textBox1.ID = "textBox1"; if (IsPostBack) { textBox1.Text = "Good Afternoon."; } Form.Controls.Add(button1); Form.Controls.Add(textBox1); } } 在学习了《Pro ASP.NET 3.5 in C# 2008》之后,找到了答案。 虽然ViewState通常是在Page.Load事件之前恢复,但是如果你是在Page.Load事件委托之中创建的控件,ASP.NET 将会在Page.Load事件委托结束之后恢复ViewState. 所以如果将上述代码作一下修改,把改变TextBox的Text 部分的代码放到Page_PreRender中,就可以了。 public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button button1 = new Button(); button1.Text = "Click"; button1.ID = "button1"; TextBox textBox1 = new TextBox(); textBox1.Text = "Good Morning."; textBox1.ID = "textBox1"; Form.Controls.Add(button1); Form.Controls.Add(textBox1); } protected void Page_PreRender(object sender, EventArgs e) { if (IsPostBack) { TextBox textBox1 = (TextBox)Page.FindControl("textBox1"); textBox1.Text = "Good Afternoon."; } } }

评论