如何为动态生成的按钮添加事件处理程序

4
这与以下问题非常相似,但它们似乎并没有帮助到我(下面会解释原因): 我正在创建一个C# aspx页面。该页面获取一堆数据,然后将其构建成表格。表格中的一列包含一个按钮,随着数据构建而动态创建(因为按钮的操作依赖于表中的数据)。
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
    }

我卡住的地方在这里。 我明白我的EventHandler没有被触发是因为它需要移到Page_Load方法中。 但是,如果我将btn1的创建和EventHandler移动到Page_Load中,我就无法在Build_Table中访问它们了!

我看到的所有代码示例都要么在ASPX页面中静态添加btn1,要么在Page_Load中动态创建它。 最好的方法是什么,可以实现我想要完成的功能?


我运行了你的代码,它可以正常工作,事件处理程序也能够正常触发。你确定你的处理程序正在被触发,但是在执行“惊人的操作”时出现了一些问题吗? - Karl Anderson
1个回答

5
在绑定事件之前,先使用一个ID创建你的按钮:
Button btn1 = new Button();
btn1.ID = "btnMyButton";
btn1.Click += new EventHandler(this.btn1_Click);

确保每个按钮都有唯一的ID。此外,我个人建议将代码移动到Page_Init而不是Page_Load中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接