C# 在 asp.net 中使用 OnInit 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/667734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:33:49  来源:igfitidea点击:

Using the OnInit event in asp.net

c#asp.net

提问by akosch

I have contentpage overriding the OnInit event of a masterpage. The override works fine, until I put a custom user control on the page: in this case the OnInit event does not fire for the contentpage (no overrides are used in the user control)

我有 contentpage 覆盖了母版页的 OnInit 事件。覆盖工作正常,直到我在页面上放置一个自定义用户控件:在这种情况下,OnInit 事件不会为内容页面触发(用户控件中没有使用覆盖)

What are the possible causes/solutions for this? (I use the OnInit event to create dynamic controls)

可能的原因/解决方案是什么?(我使用 OnInit 事件来创建动态控件)



Edit:

编辑:

now i tried this in the content page:

现在我在内容页面中尝试了这个:

(The OnPreInit part runs, but Masters_Init does not get called...)

( OnPreInit 部分运行,但 Masters_Init 没有被调用......)

    protected override void OnPreInit(EventArgs e)
    {
        base.Master.Init += new EventHandler(Masters_Init);
    }

    void Masters_Init(object sender, EventArgs e)
    { 
    //code 
    }

采纳答案by bendewey

Are you calling the base.OnInit?

你在调用 base.OnInit 吗?

public override void OnInit(EventArgs e)
{
  // code before base oninit
  base.OnInit(e);
  // code after base oninit
}

Update

更新

public class Page1 : Page
{
  public Page1 : base() {
    PreInit += Page_PreInit;
  }
  void Page_PreInit(object sender, EventArgs e)
  {
    Master.Init += Master_Init;
  }
  void Master_Init(object sender, EventArgs e)
  {
    //code
  }
}

Also as mentioned in the comments I would recommend not overriding the events if you don't have to, but if you must be sure to call the base. so in your edit above it should be

同样如评论中所述,如果您不需要,我建议不要覆盖事件,但如果您必须确保调用 base。所以在你上面的编辑中应该是

protected override void OnPreInit(EventArgs e)
{
  base.OnPreInit(e);
  base.Master.Init += new EventHandler(Masters_Init);
}