ASP.NET Calling a Method in (ASPX) From a UserControl (ASCX)?

狂风中的少年 提交于 2020-01-04 06:15:32

问题


got an Default.aspx

its Codebehind has a Method: public void DoSomething(){}

The Default.aspx has got a UserControl.ascx

In the Codebehind of my UserControl.ascx I would like to call my DoSomething() from Default.aspx, but this doesn't works:

Default defaultPage = new Default();
defaultPage.DoSomething();

How can I achieve this? (Default.aspx is also the StartupPage of the Masterpage)


回答1:


Default defaultPage = new Default(); would create a new instance of your page, which isn't what you want.

From your usercontrol, you could do something like this:

((Default)Page).DoSomething();

Or to be safe and ensure that the Page is of type Default since a user control could exist on many different pages (which is why this may not be the best idea).

Default p = Page as Default;
if( p != null )
    p.DoSomething();


来源:https://stackoverflow.com/questions/7810548/asp-net-calling-a-method-in-aspx-from-a-usercontrol-ascx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!