ASP.NET Calling a Method in (ASPX) From a UserCont

2019-07-16 10:58发布

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条回答
来,给爷笑一个
2楼-- · 2019-07-16 11:12

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();
查看更多
登录 后发表回答