Aerus
Aerus

Reputation: 4380

Event handler not firing after button removed C#

I have a table with data from an SQL database and the table exists of a few rows and columns. The user has to provide credentials first before the table with the data is shown so i create the table (and its contents) dynamically.

On each row in the table i add a cell with a "remove"-button in it:

   // more code to create the table above
   Button remove = new Button();
   remove.Text = "Remove";
   remove.Click += new EventHandler(remove_Click);

   TableCell last = new TableCell();
   last.Controls.Add(remove);

   row.Cells.Add(last);
   //...

When the user clicks the button i want the corresponding record in the database to be removed and the table updated after the postback.

The code for this is written in remove_Click but the event is never fired, just because the remove button doesn't exist anymore after the postback and thus the event of the button can't be fired. As explained here: Dynamically Added Event Handler Not Firing

The code works fine if i don't remove the button, but how would i go about firing the event and still wanting to remove the button ?

Upvotes: 2

Views: 746

Answers (2)

Robert
Robert

Reputation: 265

Call whatever function that builds your table AGAIN in the remove_Click event handler. Since the record doesn't exist in the database after the remove button fires, the 2nd time the BuildTable() is called, that record will not be included when the table is built.

Assuming your .aspx looks something like:

...
<asp:PlaceHolder id="phTable" runat="server">
...

Try something like this:

    PageLoad(...)
    {
        BuildTable();
    }
    BuildTable()
    {
        phTable.Controls.Clear();
        Table T = new Table();
         //do stuff
        phTable.Controls.Add(T);


    }
    protected void remove_Click(object sender, EventArgs e)
    {
        //remove record from database
        BuildTable();

    }

Upvotes: 1

code4life
code4life

Reputation: 15794

You have to assign a unique ID to your Button control.

Upvotes: 1

Related Questions