简体   繁体   中英

Button click event not firing after postback

I've got the following code defined in a button click event on my webform. The code executes properly the first time I click the button. Additional clicks should add more values to my database, but in this case after the first postback, the click event doesn't fire.

When I leave the page and come back, I can add one more name to the list, but subsequent clicks still don't work. I'm stumped on this one...not throwing any Javascript errors on the page (which is the first thing I thought of)

if (!String.IsNullOrEmpty(tbSuggestedSupplier_Add.Text))
{
   SqlCommand cmd = new SqlCommand("pSuggestedSupplier_AddNew", dbConnection);
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.Clear();
   cmd.Parameters.Add("@NewSupplierRequestID", SqlDbType.Int);
   cmd.Parameters.Add("@SupplierName", SqlDbType.VarChar, (500));
   //cmd.Parameters.Add("@SupplierTypeID");

   cmd.Parameters["@NewSupplierRequestID"].Value = Session["NewSupplierRequestID"];
   cmd.Parameters["@SupplierName"].Value = tbSuggestedSupplier_Add.Text;
   functions.NewSupplierRequest.Open();

   try
   {
      cmd.ExecuteNonQuery();
      gvSuggestedSuppliers.DataBind();
      tbSuggestedSupplier_Add.Text = string.Empty;
   }

   catch (Exception err)
   {
      this.lblError.Text = err.Message;
   }

   finally
   {
      functions.NewSupplierRequest.Close();
   }
}

If the Button in question is being dynamically created, make sure that you are re-attaching the Click event handler on each postback. It's sounds like that could be the problem.

The best way to go about it would be to just create the Button control within your Page's PreInit event , and attach the event handler there. That way it is part of your ViewState, and later events in the Page life cycle will know about it.

Page_PreInit(Object sender, EventArgs e)
{
    Button yourBtn = new Button();
    // Set your other properties
    yourBtn.Click += yourEventHandlerName;
    // Add the control to the controls collection of whatever container it belongs in
    yourContainer.Controls.Add(yourBtn);
}

通过将CausesValidation =“ False”添加到此特定按钮来解决该问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM