ASP.NET Programmatically adding button with an eve

2020-04-11 05:08发布

问题:

I am making a dynamic table that will add rows whenever the add row button is clicked. I am creating the button programmatically and adding it to the table header. Below that button, and on the same column there will be delete row buttons too.

I am having a problem though, when I click the button, the event is not being called. Am I creating the button correctly? If not, then how do I do it? If I am, then do you know what the problem is?

region Add_Table_Header

    TableHeaderCell thcOne = new TableHeaderCell();
    TableHeaderCell thcTwo = new TableHeaderCell();
    TableHeaderCell thcThree = new TableHeaderCell();
    TableHeaderCell thcrFour = new TableHeaderCell();
    TableHeaderCell thcFive = new TableHeaderCell();
    TableCell thcRowAction = new TableCell(); //THIS IS THE COLUMN WITH THE 
                                              //ADD BUTTON

    thcOne.Text = "Who";
    thcTwo.Text = "Date Started";
    thcThree.Text = "Date Ended";
    thcrFour.Text = "Causes?";
    thcFive.Text = "Result";

            //HERE IS WHERE I CREATE AND ADD THE BUTTON

    Button addRowButton = new Button();
    addRowButton.Text = "Add Row";
    addRowButton.Click += new EventHandler(this.AddNewRow_Click);
    thcRowAction.Controls.Add(addRowButton);

    TableHeaderRow headerRow = new TableHeaderRow();
    headerRow.Cells.Add(thcOne);
    headerRow.Cells.Add(thcTwo);
    headerRow.Cells.Add(thcThree);
    headerRow.Cells.Add(thcrFour);
    headerRow.Cells.Add(thcFive);
    headerRow.Cells.Add(thcRowAction);

    table.Rows.Add(headerRow);

    #endregion


protected void AddNewRow_Click(object sender, EventArgs e)
    {
        if (ViewState["RowsCount"] != null)
        {
            numOfRows = Convert.ToInt32(ViewState["RowsCount"]);
            GenerateTable(numOfRows);
        }
    }

Once again, the button appears, but it does not enter the correct event method. Thanks for your help and time :)

By the way when I do it declaratively such as:

<asp:Button ID="BTNAdd" runat="server" Text="Add New Row" OnClick="AddNewRow_Click" />

the event will register and work completely fine.

NEW INFO: I have a delete button appearing too, I did not register any type of event with it, but when I click it, it does the exact same thing as the add row button, could this be because the master page or a different source is telling the buttons what to do first or by default?

THANKS :)

回答1:

You should add the dynamic controls in the Page's Init event handler so that the ViewState and Events are triggered appropriately.

Try doing this:

protected void Page_Init(object sender, EventArgs e)     
     {         
         Button btn = new Button();         
        btn.ID = "btnTest";         
         btn.Text = "I was dynamically created";         
         btn.Click += new EventHandler(btnTest_Click);         
        Panel1.Controls.Add(btn);     
     }