0

Well if i'm creating an event programmatically and run it outside the page_load or page_init then it's not working. Do you have to write the code inside the page_load or page_init?

the code below is just a little example that works inside the page load or init but not outside.

    protected void btnAddProduct_Click(object sender, EventArgs e)
    {
        Button b = new Button();
        b.Text = "Add product";
        b.ID = "btn_Back";
        b.Click += new EventHandler(Button_Click);
        form1.Controls.Add(b);
    }
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Where is this event handler registered? – Ant P Dec 29 '14 at 15:25
  • 1
    You should review the page life cycle in ASP.NET. This post may also help you. http://stackoverflow.com/questions/4216329/asp-net-dynamically-created-controls-and-postback – Rick S Dec 29 '14 at 16:04

1 Answers1

0

You can't add events outside the Init and Load events.

The Page object instance isn't persistent across calls, it is built every time you call that url, so every event handler added in another place than the Page_Load will be lost after the page content is sent.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • Well i have created a method outside the page init or load that adds table rows with cells to a table control. I have added buttons programmatically but the events aren't fired. The method is called each time i click to add a new row. – user3512855 Dec 29 '14 at 15:47
  • @user3512855: Because they aren't rebuilt when the page is created again and again on every postback. – Patrick Hofman Dec 29 '14 at 15:52