4

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. 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

<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
    }

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. However, if I move the btn1 creation and EventHandler over to Page_Load, I can no longer access them in 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. What's the best way to do what I'm trying to accomplish?

4

1 回答 1

5

Create your buttons with an ID before you bind the event:

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

Make sure every button has an unique ID. Also, I would personally move the code to Page_Init instead of Page_Load.

于 2013-06-21T22:53:21.327 回答