1

This is my .aspx.cs code:

public partial class Bus : System.Web.UI.Page
{    
    protected void btnSearchBus_Click(object sender, EventArgs e)
    {      
        foreach (Panel p in buses.Controls.OfType<Panel>())
        {   
            Button busSelectBtn = new Button();
            busSelectBtn.Click += btn_Click;
        }       
    }

    void btn_Click(object sender, EventArgs e)
    {
        //This part doesn't execute when the button is clicked
    }

}

The foreach loop executes when a button "btnSearchBus" is clicked. The foreach loop loops through every Panel inside another Panel "buses" and creates a button for each Panel.

What I want to do is add a click (or onclick) event to each of those buttons created. I checked a number of posts on how to achieve this but wasn't lucky. I am not sure what to do.

1 Answers1

0

Maybe you can proceed as usual linking the click event with the desired function:

busSelectBtn.Click += new System.EventHandler(this.btn_Click);

And inside said function, act depending the specific button that raised the event.

void btn_Click(object sender, EventArgs e)
{
    Button clickedButton;
    clickedButton = (Button) sender;

    //whatever you need depending which button it is the one clicked
}
Arzeik
  • 89
  • 5
  • What do you mean depending on which button is clicked?? I just want a function (btn_Click) to execute when either of the buttons created is clicked. – Clement Stanley Feb 07 '16 at 15:36
  • Then that's already what you've got. I thought you wanted some particular action depending on which of them was clicked. But then you just have to add whatever you want to happen when one of them is clicked inside void btn_Click (s,e){...}. – Arzeik Feb 07 '16 at 15:57
  • This does not work for dynamically generated buttons. – Shadrack Orina May 25 '18 at 12:19