public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack) {
            //动态创建的控件只存在与下次回发前
            Label l = new Label();
            l.Text = "动态创建的控件";
            this.PlaceHolder1.Controls.Add(l);
        }

        //如果是多次创建的话,动态控件也有视图状态,但是必须在此事件或之前
        TextBox tb = new TextBox();       
        tb.ID = "tb";
        tb.EnableViewState = true;
        this.PlaceHolder2.Controls.Add(tb);

   

   //此时就找不到动态创建控件的值

        //TextBox t = Page.FindControl("tb") as TextBox;
        //this.Button1.Text = t.Text;

 

        #region  request
        //将HTTP信息写入文件对调试很有用
        Request.SaveAs("E:\\201012\\20101222\\ControlTree\\TextFile.txt", true);

        //相当于Server的MapPath
        string path = Request.MapPath("~/TextFile.txt");

        //request用的更多的是它的属性
        #endregion

}

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        //在此事件中动态创建的控件就没有视图状态
        TextBox tb = new TextBox();      
        tb.EnableViewState = true;
        this.PlaceHolder2.Controls.Add(tb);

        //编程方式可以找到动态创建的控件的值,动态创建的值只能在创建控件所在事件的下一个事件中找到
        TextBox t = Page.FindControl("tb") as TextBox;
        this.Button1.Text = t.Text;
    }

   
    protected void Button1_Click(object sender, EventArgs e)
    {
        //可以找到动态创建的控件的值
        TextBox t = Page.FindControl("tb") as TextBox;
        this.Button1.Text = t.Text;
    }
}

posted on 2010-12-23 13:34  王长委  阅读(388)  评论(1编辑  收藏  举报