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?
source share