如何从asp.net 2.0中的页面调用用户控件的方法?

发布于 2024-08-06 04:21:30 字数 80 浏览 3 评论 0原文

我有一个在母版页中使用的用户控件。 我添加了一个带有母版页的页面。

现在我需要从页面调用用户控件的方法。 如何做到这一点?请帮忙。

I have a usercontrol used in a masterpage.
I have added a page with the masterpage.

Now I need to call a method of the user control from the page.
How to do this? Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

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

评论(3

末骤雨初歇 2024-08-13 04:21:30

假设您的方法是公共的并且您的用户控件的类型是 YourUserControlsType,请尝试以下操作:

YourUserControlsType ctrlAtMasterPage = 
      (YourUserControlsType)Page.Master.FindControl("YouControlsID");
ctrlAtMasterPage.YourPublicMethod();

Assuming that your method is public and your user control's type is YourUserControlsType, try this :

YourUserControlsType ctrlAtMasterPage = 
      (YourUserControlsType)Page.Master.FindControl("YouControlsID");
ctrlAtMasterPage.YourPublicMethod();
绝不放开 2024-08-13 04:21:30

即使它是以编程方式添加的,这也应该让您获得控制权:

在您添加的页面的成员中:

TextBox FoundTextBox = (TextBox)this.Master.FindControl("RunAtServerTextBoxServerID");

This should get you your control even if it was added programatically:

In a member of the page you added:

TextBox FoundTextBox = (TextBox)this.Master.FindControl("RunAtServerTextBoxServerID");
说不完的你爱 2024-08-13 04:21:30

如果您没有对该控件的成员引用,则应考虑将页面与控件分离。在理想情况下,页面不一定知道它可能包含或可能不包含的控件。因此,您可能会考虑 MVP 模式的实现。

这里有一个简单的 MVP 实现,您可以此处查看解耦过程。如果您从解耦示例中反转通信(即页面触发控件拾取的事件),那么基本上,您已经将页面与控件解耦了。这样做的好处是,如果您的页面发生更改并且不再使用该控件,则任何事件都不会拾取该事件,并且您的页面将继续执行,不会出现任何问题。我发现这比 FindControl 找不到控件然后您尝试对其执行方法时潜在的空引用异常更合适。

虽然解耦可能需要额外几分钟的时间,但在许多情况下,这是值得付出的努力。

If you don't have a member reference to the control you should consider decoupling the page from the control. In an ideal world, the page should not necessarily know about a control it may or may not contain. Therefore, you might look into an implementation of the MVP pattern.

There's a simple implementation of MVP here, and you can see the decoupling in action here. If you reverse the communication from the decoupling example (i.e. page fires an event that the control picks up), then basically, you've decoupled your page from the control. This has a benefit in that if your page changes and the control is no longer in use, the event is not picked up by anything and your page continues to execute with no problems. I find this much more suitable than a potential null reference exception when FindControl doesn't find the control and then you try to execute a method on it.

While decoupling may take a few extra minutes, in many scenarios it turns out to be a worthwhile endeavor.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文