eventhandlers for dynamically added controls

  • Thread starter Kasper Birch Olsen
  • Start date
K

Kasper Birch Olsen

Hi NG

Im adding a bunch of linkbuttons to a page, in a for loop, but I cant get
the eventhandlers to work.

A simplyfied version of the code looks like this:

for (int i = 0; i<10; i++)
{
Button b = new Button();

b.Text = "button_"+i;

b.Click +=new EventHandler(b_Click);

buttons = b;

i++;

TableCell tc = new TableCell();

tc.Controls.Add(b);

TableRow tr = new TableRow();

tr.Cells.Add(tc);

this.Table1.Rows.Add(tr);

}

And the b_Click method is defined like:
protected void b_Click(object sender, EventArgs e)

{

throw new Exception("Someone clicked one of the buttons");

}


The code is by memory, never mind syntax issues.

The code looks fine to me, but when the buttons are clicked the page just
reloads, the exception is never thrown, thus i figure the eventhandler
doesnt work.

Any surgestions?
- Kasper
 
K

Karl Seguin [MVP]

The controls and their event handler need to be created and hooked on
postback - no later than the page_load event.

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top