簡體   English   中英

如何為動態生成的Button添加EventHandler

[英]How do add an EventHandler for a dynamically generated Button

這與這些問題非常相似,但它們似乎對我沒有幫助(將在下面解釋原因):

我正在創建一個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中動態創建它。 做我想要完成的事情的最佳方法是什么?

在綁定事件之前使用ID創建按鈕:

Button btn1 = new Button();
btn1.ID = "btnMyButton";
btn1.Click += new EventHandler(this.btn1_Click);

確保每個按鈕都有唯一的ID。 另外,我個人會將代碼移到Page_Init而不是Page_Load

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM