Programmatically add a button

protected void btn_Click(object sender, EventArgs e) { form1.Controls.Add(tt); } protected void create_Click(object sender, EventArgs e) { int k = -1; int l = -1; if ((int.TryParse(row.Text, out k)) && (int.TryParse(cell.Text, out l))) { if ((k > 0) && (l > 0)) { HtmlTable table = new HtmlTable(); table.Border = 1; table.CellPadding = 3; table.CellSpacing = 3; table.BorderColor = "red"; HtmlTableRow new_row; HtmlTableCell new_cell; for (int i = 1; i <= k; i++) { new_row = new HtmlTableRow(); new_row.BgColor = (i % 2 == 0 ? "lightyellow" : "lightcyan"); for (int j = 1; j <= l; j++) { new_cell = new HtmlTableCell(); if (i == k) { Button btn = new Button(); btn.ID = "" + j + i; btn.Click += new EventHandler(this.btn_Click); btn.Text = "Автор"; new_cell.Controls.Add(btn); } else { new_cell.InnerHtml = "" + i + j; } new_row.Cells.Add(new_cell); } table.Rows.Add(new_row); } form1.Controls.Add(table); } } } <form id="form1" runat="server"> <div> <p> <a>Введіть кількість рядків</a> <asp:TextBox runat="server" ID="row"></asp:TextBox> <a>&nbsp &nbsp &nbsp Введіть кількість стовпців</a> <asp:TextBox runat="server" ID="cell"></asp:TextBox> </p> <p> <asp:Button ID="create" runat="server" Text="Побудувати таблицю" OnClick="create_Click"/> </p> </div> </form> 

But the event handler does not work.

  • need more code - where you create, how you check, etc. - Grundy
  • @Grundy added the code - Lada

1 answer 1

Dynamic components in ASP.NET need to be created for every page load after they have been created for the first time. For each request, a new class object of your page is created, which does not know / does not remember what happened to it during the processing of previous requests (there are nuances). Save the flag showing that the button is created (in Session , ViewState , hidden field, base), and check it no later than in Page_Load .

You, during PostBack a, occurring due to clicking on the "Author" button, this "Author" button on the server does not exist. There is no object that says: "They clicked on me; I need to call an event handler."

Update

 <asp:Panel ID="pnlTable" runat="server"></asp:Panel> protected void Page_Load(object sender, EventArgs e) { if (Session["RowCount"] != null && Session["ColumnCount"] != null) { int rows = (int)Session["RowCount"]; int columns = (int)Session["ColumnCount"]; CreateTable(rows, columns); } } protected void create_Click(object sender, EventArgs e) { int rows; int columns; if (int.TryParse(row.Text, out rows) && int.TryParse(cell.Text, out columns)) { Session["RowCount"] = rows; Session["ColumnCount"] = columns; CreateTable(rows, columns); } } private void CreateTable(int aRowCount, int aColumnCount) { pnlTable.Controls.Clear(); if (aRowCount > 0 && aColumnCount > 0) { HtmlTable table = new HtmlTable(); // код заполнения таблицы ... pnlTable.Controls.Add(table); } }