UserControl's Event Handler not firing

UserControl's Event Handler not firing

静谧 发布于 2021-12-01 字数 853 浏览 757 回复 4 原文

I dynamically load a UserControl into a View that's in a MultiView control. Although the UserControl adds an event handler, the event never fires.

What am I missing here?

Containing ASPX page:

protected override void OnPreRender(EventArgs e)
    if (MultiView1.ActiveViewIndex == 2) //If the tab is selected, load control
        Control Presenter = LoadControl("Presenter.ascx");


override protected void OnInit(EventArgs e)
    Retry.Click += this.Retry_Click; //This is a .Net 2.0 project

protected void Retry_Click(object sender, EventArgs e)
    //This never fires

如果你对这篇文章有疑问,欢迎到本站 社区 发帖提问或使用手Q扫描下方二维码加群参与讨论,获取更多帮助。



需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。


悸初 2022-06-07 4 楼

It sounds like the control is not being added after each post back, i would take out the if statement in the containing aspx page to see if that fixes the assuming Retry is a button?

春夜浅 2022-06-07 3 楼

The control must be visible initially to be able to enter in OnPreRender event.
but maybe you want it to be unvisible.
the be sure to have EnableViewState = false;

原来分手还会想你 2022-06-07 2 楼

Postback event handling is done before rendering so the control is not present in the page in your case.

The life cycle events are fired in this order (skipped a few):

  1. Init
  2. Load
  3. PreRender
  4. Unload

And event handling is done between Load and PreRender (in case some events change the way the page should be rendered, it makes sense).

So just move your code that loads the Retry control to Load or Init.

Reference: Asp.Net Page Life Cycle Overview

愛上了 2022-06-07 1 楼

I am thinking it is not firing because you are loading the control in your page's prerender event. Upon postback, the control is being lost because there is no view state for it. Therefore there is no control to fire its event. Try to load the control in the page's init event. Let us know what happens!