WEB开发网
开发学院软件开发C语言 C#动态生成控件以及添加事件处理 阅读

C#动态生成控件以及添加事件处理

 2009-04-01 08:21:45 来源:WEB开发网   
核心提示: 动态添加控件并添加事件private void Page_Load(object sender, System.EventArgs e){ Button Button1 = new Button(); Button1.CommandArgument = "b1"; Bu

动态添加控件并添加事件

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 3 4  下一页

Tags:动态 生成 控件

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接