46

I am creating one button on a page dynamically. Now I want to use the button click event on that button.

How can I do this in C# ASP.NET?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AB Vyas
  • 2,349
  • 6
  • 26
  • 43

6 Answers6

62
Button button = new Button();
button.Click += (s,e) => { your code; };
//button.Click += new EventHandler(button_Click);
container.Controls.Add(button);

//protected void button_Click (object sender, EventArgs e) { }
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 3
    You have to create button in OnInit method, otherwise event handler won't work – Egor4eg May 31 '11 at 13:27
  • 2
    First of all thnx IN this u write button.Click += (s,e) => { your code; }; s= object sender and e = event argument ri8? but then also button click event not fire ... can u explain me that how it can work.. – AB Vyas Jun 01 '11 at 04:04
  • 1
    @amitvyas: This is shorter, but more complex version of the same code. Instead of explicit event handler declaration - implicit using lambda expression and anonymous method: `{ this is anon method with 2 arguments declared }` – abatishchev Jun 01 '11 at 06:20
  • This also didn't work for me; the event handler never fired. It might be because a new event handler is created for the button each time a request is received. – Sam Sep 13 '13 at 02:28
  • @Sam: I think this happens due another reason. Because of page life-cycle even it's created on every request, handler should be fired. If creation occurs on postback too, it maybe an issue. – abatishchev Sep 13 '13 at 04:14
  • @abatishchev, in my case the event handler was being assigned to a control in a `DataListItem` during the `ItemDataBound` event of the `DataList`. I'm not really sure what causes the problem. – Sam Sep 13 '13 at 04:41
  • 2
    dynamic generated event must be register in Page_Load/Page_Init event outside of !IsPostBack. – nativegrip May 16 '18 at 10:24
43

The easier one for newbies:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}
A9S6
  • 6,575
  • 10
  • 50
  • 82
  • 8
    What is the non-newbie version? – Mike May 31 '11 at 13:22
  • @MichaelMello: Non-newbie one could have been the lambda one. "button.click += (sender, e) => { // do something here }" :) – A9S6 Sep 09 '15 at 07:29
  • Can I pass other arguments along with this? ie `button.Click += new EventHandler(button_Click("Test"));`? –  Sep 08 '16 at 18:14
  • 1
    Nevermind, this worked: `button.Click += (se, ev) => button_Click(se, ev, qo);` –  Sep 08 '16 at 18:22
13

Simply add the eventhandler to the button when creating it.

 button.Click += new EventHandler(this.button_Click);

void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
2GDev
  • 2,478
  • 1
  • 20
  • 32
11

It is much easier to do:

Button button = new Button();
button.Click += delegate
{
   // Your code
};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

You can create button in a simple way, such as:

Button button = new Button();
button.Click += new EventHandler(button_Click);

protected void button_Click (object sender, EventArgs e)
{
    Button button = sender as Button;
    // identify which button was clicked and perform necessary actions
}

But event probably will not fire, because the element/elements must be recreated at every postback or you will lose the event handler.

I tried this solution that verify that ViewState is already Generated and recreate elements at every postback,

for example, imagine you create your button on an event click:

    protected void Button_Click(object sender, EventArgs e)
    {
       if (Convert.ToString(ViewState["Generated"]) != "true")
        {
            CreateDynamicElements();
        }
    
    }

on postback, for example on page load, you should do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(ViewState["Generated"]) == "true") {
            CreateDynamicElements();
        }
    }

In CreateDynamicElements() you can put all the elements you need, such as your button.

This worked very well for me.

public void CreateDynamicElements(){

    Button button = new Button();
    button.Click += new EventHandler(button_Click);

}
giorgio calarco
  • 136
  • 1
  • 7
0

Let's say you have 25 objects and want one process to handle any one objects click event. You could write 25 delegates or use a loop to handle the click event.

public form1()
{
    foreach (Panel pl  in Container.Components)
    {
        pl.Click += Panel_Click;
    }
}

private void Panel_Click(object sender, EventArgs e)
{
    // Process the panel clicks here
    int index = Panels.FindIndex(a => a == sender);
    ...
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131