how to create an asp button dynamically and add event to it

前端 未结 5 1389
予麋鹿
予麋鹿 2021-01-21 07:06

I\'m trying to create a button dynamically on asp.net,but I can\'t add the event to it.What is wrong or missing below?

Thanks in advance

$

         


        
5条回答
  •  终归单人心
    2021-01-21 08:02

    I think your trying to mix server side and client side events here.

    The html attribute OnClick is a client side, when a user clicks on the button it fires a piece of JavaScript The server event OnClick happens when a user clicks a button and it posts back to the server, which allows you to hook functions (server side) into that event.

    Are you looking for server side or client side?

    To add a client side event you can do

    btn2.Attributes.Add("onclick","my_javascript_function");
    

    To add a server side event you can do

    btn2.Click += new System.EventHandler(this.MyMethod); 
    

    Where this.MyMethod is a method already seutp to handle the server side button click.

提交回复
热议问题