How can I create a dynamic button click event on a dynamic button?
Asked Answered
D

6

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?

Detached answered 31/5, 2011 at 13:0 Comment(0)
H
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) { }
Hellenic answered 31/5, 2011 at 13:4 Comment(7)
You have to create button in OnInit method, otherwise event handler won't workMaccaboy
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..Detached
@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 }Hellenic
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.Yearling
@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.Hellenic
@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.Yearling
dynamic generated event must be register in Page_Load/Page_Init event outside of !IsPostBack.Antoneantonella
R
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
}
Repairer answered 31/5, 2011 at 13:11 Comment(4)
What is the non-newbie version?Selfpollination
@MichaelMello: Non-newbie one could have been the lambda one. "button.click += (sender, e) => { // do something here }" :)Repairer
Can I pass other arguments along with this? ie button.Click += new EventHandler(button_Click("Test"));?Doer
Nevermind, this worked: button.Click += (se, ev) => button_Click(se, ev, qo);Doer
C
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...
}
Champerty answered 31/5, 2011 at 13:11 Comment(0)
M
11

It is much easier to do:

Button button = new Button();
button.Click += delegate
{
   // Your code
};
Marybelle answered 19/1, 2015 at 12:23 Comment(0)
L
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);

}
Luncheon answered 3/2, 2021 at 13:51 Comment(0)
B
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);
    ...
}
Bedclothes answered 14/10, 2016 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.