按钮单击事件未在ASP .Net中的使用控件内触发

我正在开发一个asp网页,其中我有一个下拉combobox和一个下方的占位符。 当用户从下拉combobox中选择项目时,对服务器端进行回发,并且服务器将asp用户控件加载到该父页面中的占位符。 到目前为止,一切都很好。

在用户控件中,我有一个按钮,后面的用户控制代码被实现来处理按钮点击事件。 问题是,当我单击此按钮时,我可以看到回发发送到服务器端(即在调试模式下调用父页面Page_Load()),但用户控件的Page_Load()或按钮单击事件处理程序都是没有被调用。

请帮忙..

一些额外的信息,

  1. 我的父页面不是asp母版页面。 只是一个简单的asp页面。
  2. 我正在使用VS2008和.Net 3.5 SP1和C#。

您需要确保UserControl存在,以便在重建viewstate时触发按钮单击事件。

在Page_Load中加载UserControl将首次运行。 单击按钮并发生post_back时,尚未发生Page_Load。 这意味着UserControl将不存在,这意味着要重新连接事件的按钮不存在。 因此,带有按钮的UserControl无法连接到click事件,并且click事件不会触发。

建议您在此事件中加载您的用户控件。

protected override void OnLoad(EventArgs e) { base.OnLoad(e); //-- Create your controls here } 

尝试沙盒测试 。 在page_load中,在Page_Load中动态创建一个带有单击事件的按钮。 您将看到click事件不会触发。 现在将按钮移动到OnLoad事件。 点击事件将触发。 另请注意,click事件将发生在Page_Load事件之前。 进一步certificate该按钮在正确的时间不存在。

另一个想法……

您正在按钮事件发生之前在页面上重新加载usercontrol。 确保LoadControl方法在If块内

 if (!IsPostBack) { //load usercontrol } 

Default.aspx的

   

Default.aspx.cs

  protected void Page_Load(object sender, EventArgs e) { var ctl = LoadControl("Controls/UserControl.ascx"); ph1.Controls.Add(ctl); } 

UserControl.ascx

 

User control

UserControl.ascx.cs

 protected void btn1_Click(object s, EventArgs e) { Response.Write("You clicked me, yay"); } 

一切都像魅力。 当我点击按钮时,我看到“你点击了我,yay”

关注点 。 如果您尝试在下拉控件的SelectedItemChanged事件的处理程序中动态加载控件,则它将失败,因为生命周期对ASP.Net页面起作用的方式。 相反,您应该在页面的PageLoad事件中处理此类控件创建,例如Default.aspx下面的示例

        

Default.aspx.cs

 protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { switch (ddl1.SelectedValue) { case "1": var ctl = LoadControl("Controls/UserControl.ascx"); ph1.Controls.Add(ctl); break; case "2": ctl = LoadControl("Controls/UserControl2.ascx"); ph1.Controls.Add(ctl); break; } } } 

在我的特定情况下,我发现问题是UserControl ID(或者更确切地说是缺少)。

首次实例化UserControl时,我的按钮ID为ctl00 $ ctl02 $ btnContinue,但在回发后它已更改为ctl00 $ ctl03 $ btnContinue,因此按钮事件处理程序未触发。

我改为使用固定ID添加我的UserControl,现在按钮总是加载ID为ctl00 $ myUserControl $ btnContinue。