当前位置: 代码迷 >> ASP.NET >> 动态创建的 Button, 如何动态添加 OnClick 事件
  详细解决方案

动态创建的 Button, 如何动态添加 OnClick 事件

热度:2267   发布时间:2013-02-26 00:00:00.0
动态创建的 Button, 怎么动态添加 OnClick 事件
这里无效,   怎么才能引用   CheckLogin   方法?
    //smtButton.OnClick=this.CheckLogin;

如下:
  public   void   CheckLogin(Object   s,   EventArgs   e)
  {
 
  }
 
  public   void   Login(PlaceHolder   LoginPh)
  {
    Literal   Br=new   Literal();
    Br.Text= " <br/> ";
   
    Literal   ltUsername=new   Literal();
    ltUsername.Text= "Username:   ";
   
    Literal   ltPassword=new   Literal();
    ltPassword.Text= " <br/> Password:   ";
   
    TextBox   Username=new   TextBox();
    Username.ID= "Username ";
   
    TextBox   Password=new   TextBox();
    Password.TextMode=TextBoxMode.Password;
    Password.ID= "Password ";
   
    Button   smtButton=new   Button();
    smtButton.Text= "login   now ";
    //smtButton.OnClick=this.CheckLogin;
   
    LoginPh.Controls.Add(ltUsername);
    LoginPh.Controls.Add(Username);
    LoginPh.Controls.Add(ltPassword);
    LoginPh.Controls.Add(Password);
    LoginPh.Controls.Add(Br);
    LoginPh.Controls.Add(smtButton);
  }

------解决方案--------------------------------------------------------
vb.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim btn As New Button
btn.ID = "btn1 "
btn.Text = "btn1 "
form1.Controls.Add(btn)
AddHandler btn.Click, AddressOf btn1_Click
End Sub

Public Sub btn1_click(ByVal sender As Object, ByVal e As EventArgs)
For Each ctl As Control In form1.Controls
If (ctl.GetType Is GetType(System.Web.UI.WebControls.Button)) Then
If CType(ctl, Button).ID = "btn1 " Then
Response.Write(CType(ctl, Button).ID)
End If
End If
Next
End Sub
------解决方案--------------------------------------------------------
this.smtButton.Click += new System.EventHandler(this.CheckLogin);
  相关解决方案