[英]How do add an EventHandler for a dynamically generated Button
This is very similar to these questions, but they didn't seem to help me (will explain why below): 这与这些问题非常相似,但它们似乎对我没有帮助(将在下面解释原因):
I'm creating a C# aspx page. 我正在创建一个C#aspx页面。 That page grabs a bunch of data and then builds a table out of it.
该页面抓取了大量数据,然后构建了一个表格。 One of the columns in the table contains a button that gets dynamically created as it builds the data (since the button's action relies on the data in the table).
表中的一列包含一个在构建数据时动态创建的按钮(因为按钮的操作依赖于表中的数据)。
Default.aspx Default.aspx的
<body>
<form id="form1" runat="server">
<div>
<asp:Table ID="tblData" runat="server"></asp:Table>
</div>
</form>
</body>
Defafult.aspx.cs 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's where I'm tripping up. 这是我绊倒的地方。 I understand that my EventHandler isn't being fired because it needs to be moved over to the Page_Load method.
我知道我的EventHandler没有被触发,因为它需要转移到Page_Load方法。 However, if I move the btn1 creation and EventHandler over to Page_Load, I can no longer access them in Build_Table!
但是,如果我将btn1创建和EventHandler移动到Page_Load,我将无法再在Build_Table中访问它们!
All of the code examples I see either have btn1 statically added in the ASPX page, or have it dynamically created in Page_Load. 我看到的所有代码示例都在ASPX页面中静态添加了btn1,或者在Page_Load中动态创建它。 What's the best way to do what I'm trying to accomplish?
做我想要完成的事情的最佳方法是什么?
Create your buttons with an ID before you bind the event: 在绑定事件之前使用ID创建按钮:
Button btn1 = new Button();
btn1.ID = "btnMyButton";
btn1.Click += new EventHandler(this.btn1_Click);
Make sure every button has an unique ID. 确保每个按钮都有唯一的ID。 Also, I would personally move the code to
Page_Init
instead of Page_Load
. 另外,我个人会将代码移到
Page_Init
而不是Page_Load
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.