简体   繁体   English

回发后未触发按钮单击事件

[英]Button click event not firing after postback

I've got the following code defined in a button click event on my webform. 我在Web表单的按钮单击事件中定义了以下代码。 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. 额外的点击应该为我的数据库添加更多值,但是在这种情况下,第一次回发后,click事件不会触发。

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) 我为此感到困惑...没有在页面上抛出任何Javascript错误(这是我想到的第一件事)

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. 如果正在动态创建有问题的Button,请确保您在每个回发上都重新附加了Click事件处理程序。 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. 最好的方法是在Page的PreInit事件中创建Button控件,然后在其中附加事件处理程序。 That way it is part of your ViewState, and later events in the Page life cycle will know about it. 这样,它便成为ViewState的一部分,而Page生命周期中的后续事件将对此有所了解。

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”添加到此特定按钮来解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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