【问题标题】:Button click event not firing in user control, created dynamically in another user control按钮单击事件未在用户控件中触发,在另一个用户控件中动态创建
【发布时间】:2017-08-03 16:38:51
【问题描述】:

我有可视 Web 部件和两个用户控件。 在可视化 Web 部件的 Page_Load() 上,我动态创建 userControl1

protected void Page_Load(object sender, EventArgs e)
{
  UserControl1 userControl = Page.LoadControl(userControl1Path) as UserControl1;
  userControl.ID = "UserControl1";
  this.Controls.Clear();
  this.Controls.Add(userControl);
}

在 UserControl1 中,我有一个按钮,用于加载第二个用户控件 (UserControl2)(它可以工作!):

protected void GoToUserControl2_Click(object sender, EventArgs e)
{
  UserContol2 userControl = Page.LoadControl(userControl2Path) as UserContol2;
  userControl.ID = "UserContol2";
  this.Controls.Clear();
  this.Controls.Add(userControl);
}

UserControl2 也有一个按钮,但是当我单击它时 - 单击事件未触发。取而代之的是,单击按钮执行重定向到UserControl1。 即使按钮没有任何事件 - 它也会重定向到 UserControl1

请帮帮我!

【问题讨论】:

  • 在你的页面加载中设置一个断点,你会注意到 page_load 函数在每次回发时都会执行,我怀疑你的页面加载清除了控件 2 并使用了控件 1 的事件跨度>

标签: c# asp.net sharepoint user-controls web-parts


【解决方案1】:

必须在每次页面加载时重新创建动态生成的控件,其中包括 PostBack。因为第二个用户控件仅在单击按钮时加载,所以在执行另一个 PostBack 时它会消失。如果 UserContol2 已创建,您将必须跟踪,如果是,则在父级的 Page_Load 中重新加载它。在这个 sn-p 中,我使用 Session 来跟踪 UserContol2 的开放情况。

在按钮点击方法中设置会话

protected void GoToUserControl2_Click(object sender, EventArgs e)
{
    //rest of the code
    Session["uc2_open"] = true;
}

并检查 Page_load 是否存在 Session,如果存在,则创建第二个用户控件。

protected void Page_Load(object sender, EventArgs e)
{
    UserControl1 userControl = Page.LoadControl(userControl1Path) as UserControl1;
    userControl.ID = "UserControl1";
    this.Controls.Clear();
    this.Controls.Add(userControl);

    if (Session["uc2_open"] != null)
    {
        UserContol2 userControl = Page.LoadControl(userControl2Path) as UserContol2;
        userControl.ID = "UserContol2";
        this.Controls.Clear();
        this.Controls.Add(userControl);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2018-10-31
    相关资源
    最近更新 更多