因为TextBox是在Button1的事件中创建的。当你点了Button2以后,findContor找不到TexBox了。返回的当然是null如果你把创建TextBox的代码写到Page_Load中就没事了

解决方案 »

  1.   


    动态加载的控件取值前需要加载一次,并且给控件的ID赋值必须在this.form1.Controls.Add(txt)这种语句之前
    并且动态加载的控件应在Page_Load方法里,或者Page_Load运行更靠前的方法里才行。在Button1事件中加,Button2事件中取,我测试了一下,行不通。
    如下代码是通过的:
     protected void Page_Load(object sender, EventArgs e)
        {
            TextBox txt = new TextBox();
            txt.ID = "txt1";
            this.form1.Controls.Add(txt); 
        }    protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox tbox = new TextBox();
            tbox = (TextBox)this.form1.FindControl("txt1"); 
        }