程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#動態生成控件以及添加事件處理(3)

C#動態生成控件以及添加事件處理(3)

編輯:關於C語言
體的代碼請看下面:

需要特別注意的是:

添加控件和給控件加事件時絕對不能放到 if(!IsPostback){}裡面,那樣的話,點擊一次後控件會消失,而且事件也不會執行。

protected void Page_Load(object sender, EventArgs e)
    {
       //將輸入字符串分析為System.Web.UI.Control對象,b為傳進去的值
        Control c = ParseControl("<ASP:Button Text = '按我' ID = 'myButton' commandargument = 'b' runat = 'server' />");

        //將控件添加大Panel中
        this.Panel1.Controls.Add(c);

        //查找頁面名為myButton的控件
        Button Button = (Button)Page.FindControl("myButton");

        //添加事件On_Button
        Button.Command += new CommandEventHandler(this.On_Button);

    }

    //CommandEventArgs為command事件提供數據
    protected void On_Button(Object sender,CommandEventArgs e)
    {
        Response.Write("<script language = 'Javascript' type = 'text/Javascript'>alert('" + e.CommandArgument.ToString() + "');</script>");
    }

動態添加控件並添加事件

private void Page_Load(object sender, System.EventArgs e)
{
   Button Button1 = new Button();
   Button1.CommandArgument = "b1";
   Button1.Text = "Btn1";
   Button1.Command += new CommandEventHandler(this.OnButton);
   PlaceHolder1.Controls.Add(Button1);
   Button Button2 = new Button();
   Button2.CommandArgument = "b2";
   Button2.Text = "Btn2";
   Button2.Command += new CommandEventHandler(this.OnButton);
   PlaceHolder1.Controls.Add(Button2);

   Control c3 = ParseControl("<ASP:Button id='Button3' text='Btn3' commandname='Btn' commandargument='b3' runat='server' />"); //將字符串轉換成web控件
   Control c4 = ParseControl("<ASP:Button id='Button4' text='Btn4' commandname='Btn' commandargument='b4' runat='server' />");
   PlaceHolder1.Controls.Add(c3);
   PlaceHolder1.Controls.Add(c4);
   Button myBut = (Button)Page.FindControl("Button3");
   myBut.Command += new CommandEventHandler(this.OnButton);
   Button myBut2 = (Button)Page.FindControl("Button4");
   myBut2.Command += new CommandEventHandler(this.OnButton);

}
public void OnButton(Object Sender, CommandEventArgs e)
{
   switch (e.CommandArgument.ToString().ToLower())
   {
    case "b1":
     Label1.Text = "Button 1";
     break;
    case "b2":
     Label1.Text = "Button 2";
     break;
    case "b3":
     Label1.Text = "Button 3";
     break;
    case "b4":
     Label1.Text = "Button 4";
     break;
   };
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved