简体   繁体   中英

ASP.net event handlers are not attached when controls are created dynamically after pageload event

The issue I am having is exactly what it sounds like.

I have an event handler:

public void Handler(object sender, EventArgs e)
{
      TableRow newRow = new TableRow();
      TableCell newCell = new TableCell();
      Button newButton = new Button();
      newButton.Click += new EventHandler(anotherHandler);
      newCell.Controls.Add(newButton);
      newRow.Cells.Add(newCell);      
      SomeTable.Rows.Add(newRow);
}

The controls are showing up just fine. However, somehow these kinds of controls' event handlers do not fire. Its as if there is no way to subscribe to an event after page load. Is there any way around this or can I only subscribe to events during page load?

Thanks in advance.

Rather that dynamically creating the item when the user does some action, create the item unconditionally (ideally via the markup) and simply mark it as hidden until the user does whatever they need to do to make it show up.

Having the item unconditionally on the page allows you to ensure all events are wired up at the appropriate time in the page lifecycle, and conditionally showing/hiding them ensures that the user can only interact with them when they should.

By the time you're creating these items dynamically it is already too late in the page life cycle to be adding event handlers to them and having them fire.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM