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

前端 未结 5 1402
予麋鹿
予麋鹿 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:01

    This should do the trick:

    protected void Page_Load(object sender, EventArgs e)
    {
        Button b = new Button() { ID = "btnEdit", Text = "Edit Member" };
        b.Click += (sd, ev) => {
            // Do whatever you want to be done on click here.
            Button me = (Button)sd; // This creates a self-reference to this button, so you can get info like button ID, caption... and use, like this:
            me.Text = "Yay! You clicked me!";
        };
        form1.Controls.Add(b);
    }
    

提交回复
热议问题