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

时间:2013-04-12 15:31:42

标签: c# asp.net

我在webform上的按钮点击事件中定义了以下代码。第一次单击按钮时代码正确执行。额外的点击应该为我的数据库添加更多的值,但在这种情况下,在第一次回发后,点击事件不会触发。

当我离开页面并返回时,我可以在列表中再添加一个名称,但后续点击仍无效。我对这一个感到难过......没有在页面上抛出任何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();
   }
}

2 个答案:

答案 0 :(得分:4)

如果正在动态创建有问题的Button,请确保在每个回发上重新附加Click事件处理程序。听起来这可能就是问题所在。

最好的方法是在你的页面PreInit event中创建Button控件,并在那里附加事件处理程序。这样它就是你的ViewState的一部分,并且页面生命周期中的后续事件将知道它。

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);
}

答案 1 :(得分:3)

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