Search code examples
c#htmlasp.netwebforms

My C# button not doing anything when clicked on?


I have a table of venues for an asp.net webforms website I am creating. At the end of each row of the table I put a button labeled Book. When I click on the button it should send me to the page on the venue's own website.

However, when I try and click on the button nothing happens. I have tried putting a break point in the first line of the _click method, however it doesn't seem to get there.

Here is the code for the button. At the moment it is just meant to open the popup (This isn't the full code just the relevant parts):

Button btnbook = new Button
{
    ID = "Remove_" + VenuesTable.Rows.Count,
    Text = "Book",
    CommandArgument = reader["venueid"].ToString()
};
btnbook.Click += new EventHandler(btnbook_click);
joinCell.Controls.Add(btnbook);
socrow.Cells.Add(joinCell);

protected void btnbook_click(object sender, EventArgs e)
{
    Button button = (Button)sender; // This is where I put the brake point
    int venueid = int.Parse(button.CommandArgument);
    string buttonId = button.ID;
    ScriptManager.RegisterStartupScript(this, this.GetType(), "btnbook", "$('#bookingpopup').modal('show');", true);
}

I was expecting when the button was clicked that a popup would open, however the code doesn't even go into the _click method. There is no error message and the code doesn't break.

How can I resolve this?


Solution

  • This is related to the ASP.Net Page Lifecycle.

    The key thing to understand is ASP.Net does not keep an instance of your page class around between requests or user events. When the user first initially loads the page, as soon as that initial render is ready the server will throw away the page class instance used to create it, in order to reclaim the memory for handling HTTP requests from other users.

    When the user then clicks the button, that sends a brand new HTTP request to your web server. The web server processes this request just like any other request: with a brand new instance of the page class that must build the entire page from scratch. Any work from the prior instance to render the button has already concluded and was already thrown away.

    This means any code for your page that creates dynamic controls must run on every postback. And for event processing to work correctly, this must happen before the Page_Load event (Pre_Init is the common choice for this).


    But for this specific button, my recommendation is don't use the server click event at all. Handle it entirely in Javascript. Why use resources on your web server to recreate the entire page, and make the user wait on the round-trip latency, when the browser already has everything it needs to handle the click?