[英]Button click event not firing after postback
我在Web表單的按鈕單擊事件中定義了以下代碼。 第一次單擊按鈕時,代碼將正確執行。 額外的點擊應該為我的數據庫添加更多值,但是在這種情況下,第一次回發后,click事件不會觸發。
當我離開頁面並返回時,我可以在列表中再添加一個名稱,但是隨后的點擊仍然不起作用。 我為此感到困惑...沒有在頁面上拋出任何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();
}
}
如果正在動態創建有問題的Button,請確保您在每個回發上都重新附加了Click事件處理程序。 聽起來可能是問題所在。
最好的方法是在Page的PreInit事件中創建Button控件,然后在其中附加事件處理程序。 這樣,它便成為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.