asp.net page_load中自动生成控件,解决上下文不存在问题的示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace dynamicweb4_8
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        Panel plContent;
        Panel plTips;
        TextBox TextBox1;
        Button btnSubmit;


        protected void Page_Load(object sender, EventArgs e)
        {
            //自动生成控件的代码,从Init搬到Load中,也是可以执行的,不用
            //加IsPostBack。 如果把控件不声明在类中,在函数Load中声明控件
            //点击按钮btn时,提示控件textbox不存在,这个就是局部变量和全局
            //变量的区别。
            
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            
            plContent = new Panel();
            plContent.BorderStyle = BorderStyle.Solid;
            plContent.BorderWidth = Unit.Pixel(1);

            Label Label1 = new Label();
            Label1.Text = "反馈建议";
            plContent.Controls.Add(Label1);
            plContent.Controls.Add(new Literal() { Text = "<br>" });
         
            TextBox1 = new TextBox();
            TextBox1.Width = Unit.Pixel(350);
            TextBox1.Height = Unit.Pixel(150);
            TextBox1.TextMode = TextBoxMode.MultiLine;
            plContent.Controls.Add(TextBox1);
            plContent.Controls.Add(new Literal() { Text = "<br>" });

            btnSubmit = new Button();
            btnSubmit.Text = "提交";
            btnSubmit.Click += btnSubmit_Click;
            plContent.Controls.Add(btnSubmit);
            plContent.Controls.Add(new Literal() { Text = "<br>" });

            this.form1.Controls.Add(plContent);
            this.form1.Controls.Add(new Literal() { Text="<br>"});

            plTips = new Panel();
            plTips.BorderStyle = BorderStyle.Solid;
            plTips.BorderWidth = Unit.Pixel(1);
            plTips.Visible = false;

            this.form1.Controls.Add(plTips);            
        }

         protected void btnSubmit_Click(object sender, EventArgs e)
        {
             
            if (!string.IsNullOrEmpty(TextBox1.Text))
            {
                plContent.Visible = false;
               
                Literal litTips = new Literal();
                litTips.Text = "<div><h3>谢谢你的宝贵建议!</h3></div>";
                plTips.Controls.Add(litTips);
                plTips.Visible = true;
            }
            
        }
    }
}

猜你喜欢

转载自blog.csdn.net/modern358/article/details/115249633