asp.net dynamically button with event handler

I have here a small problem with a dynamically generated buttons and their event handler in asp.net. I generate a flexible table with additional Buttons for special users. The buttons will generate dynamically, which works fine. But I can’t get the event handler to work.

Here are some pieces from my code: Build the button (In an own function).

…
Button ButtonChange = new Button();

ButtonChange.Text = "Change";
ButtonChange.ID = "change_" + i.ToString();
ButtonChange.Font.Size = FontUnit.Point(7);
ButtonChange.ControlStyle.CssClass = "button";
ButtonChange.Click += new EventHandler(test);
…

And

void test(object sender, EventArgs e)
{ 
   // Do some stuff       
}

My Page_Load is empty.

But the program won’t jump to test, if I click the button. What’s going wrong?

Edit!!! The problem is that I don’t know at start how many rows I get from my sql query back. For every row I will add a delete and a change button. I call in my program a method which builds the result as a table. In this method, I check if the current user is an AdminUser and if he is, I will call buildAdminButtons function. Here, I create the buttons in a new column, for every row. How could I get this in OnLoad?

private void buildAdminButtons(TableRow tempRow, int i)
{
    Button ButtonDelete = new Button();
    Button ButtonChange = new Button();

    TableCell change = new TableCell();
    TableCell delete = new TableCell();

    ButtonChange.Text = "Change";
    ButtonChange.ID = "change_" + i.ToString();
    ButtonChange.Font.Size = FontUnit.Point(7);
    ButtonChange.ControlStyle.CssClass = "button";


    ButtonDelete.Text = "Delete";
    ButtonDelete.ID = "delete_" + i.ToString();
    ButtonDelete.Font.Size = FontUnit.Point(7);
    ButtonDelete.ControlStyle.CssClass = "button";

    change.Controls.Add(ButtonChange);
    delete.Controls.Add(ButtonDelete);

    tempRow.Cells.Add(change);
    tempRow.Cells.Add(delete);
}

I add to every button a unique id, which I don't know at the start. How could I handle this?


Solution 1:

You must have to place that code in page_load or page_init event.

protected void Page_Load()
{
  Button ButtonChange = new Button();

  ButtonChange.Text = "Change";
  ButtonChange.ID = "change_" + i.ToString();
  ButtonChange.Font.Size = FontUnit.Point(7);
  ButtonChange.ControlStyle.CssClass = "button";
  ButtonChange.Click += new EventHandler(test);
}

Read MSDN article - How to: Add Controls to an ASP.NET Web Page Programmatically?