Dynamic asp.net button with event handler

I have a little problem with dynamically generated buttons and their event handler in asp.net. I am creating a flexible table with additional buttons for special users. Buttons will generate dynamically, which works great. But I can not get the event handler to work.

Here are some snippets from my code: Build a button (in its 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 empty.

But the program will not check if I press the button. What is going wrong?

Change !!! The problem is that I do not know how to start, how many rows I get from my sql query back. For each line, I will add a delete and change button. I call in my program a method that builds the result as a table. In this method, I check if the current user is AdminUser, and if there is one, I will call the buildAdminButtons function. Here I create buttons in a new column for each row. How can 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 a unique identifier to each button that I don’t know at the beginning. How can I handle this?

+7
source share
1 answer

You need to place this code in the page_load or page_init .

 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 the MSDN article - How to add controls to an ASP.NET web page?

+13
source

All Articles