这是非常相似的这些问题,但他们似乎并没有帮我(会解释为什么下面):
如何添加一个事件处理程序的动态生成按钮
- How to create an onClick eventHandler for a dynamically created button
- asp.net dynamically button with event handler
- asp:Button Click event not being fired
我创建一个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中访问它们!
我看到的所有代码示例都有btn1静态添加到ASPX页面中,或者在Page_Load中动态创建它。什么是我想要完成的最好的方法?
我跑你的代码,它的工作原理,事件处理程序没有问题。你有没有证实你的经纪人正在解雇,但是在做“惊人的事情”时发生了一些不好的事情? –