How to add an EventHandler for a dynamically created button

This is very similar to these questions, but they didn't seem to help me (will explain why below):

I am creating an aspx page in C #. This page captures a bunch of data and then creates a table from it. One of the columns in the table contains a button that is dynamically created when it is created (since the action of the button depends on the data in the table).

Default.aspx

<body> <form id="form1" runat="server"> <div> <asp:Table ID="tblData" runat="server"></asp:Table> </div> </form> </body> 

Defafult.aspx.cs

 protected void Page_Load(object sender, EventArgs e) { Build_Table(); } protected void Build_Table() { //create table header row and cells TableHeaderRow hr_header = new TableHeaderRow(); TableHeaderCell hc_cell = new TableHeaderCell(); hc_cell.Text = "This column contains a button"; hr_header.Cells.Add(hc_cell); tblData.Rows.Add(hr_header); //create the cell to contain our button TableRow row = new TableRow(); TableCell cell_with_button = new TableCell(); //create the button Button btn1 = new Button(); btn1.Click += new EventHandler(this.btn1_Click); //add button to cell, cell to row, and row to table cell_with_button.Controls.Add(btn1); row.Cells.Add(cell_with_button); tblData.Rows.Add(row); } protected void btn1_Click(Object sender, EventArgs e) { //do amazing stuff } 

Here where I stumble. I understand that my EventHandler is not fired because it needs to be transferred to the Page_Load method. However, if I move the creation of btn1 and EventHandler to Page_Load, I can no longer access them in Build_Table!

All the code examples that I see are either btn1 statically added on an ASPX page or dynamically created in Page_Load. What is the best way to do what I'm trying to accomplish?

+4
source share
1 answer

Create your buttons with an identifier before binding the event:

 Button btn1 = new Button(); btn1.ID = "btnMyButton"; btn1.Click += new EventHandler(this.btn1_Click); 

Make sure each button has a unique identifier. Also, I would personally move the Page_Init code instead of Page_Load .

+5
source

Source: https://habr.com/ru/post/1487571/


All Articles