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