开发者

ASP.NET 2.0 - Parent Page Class not accessible from custom control

1) I've page class public partial class MyDelivery : System.Web.UI.Page

2) ASCX is in different subfolder public part开发者_如何转开发ial class MyControls_Hello_Bye : System.Web.UI.UserControl

I am unable to access #1 parent page class from control


This problem annoyed me for quite a while. I don't think my solution is perfect, but it sure helps my junior developers in coding. We have a base user control that all user controls inherit and we (like you) we have a base page class that all pages must inherit (team rule). In the user control is a property called ParentForm which is strongly typed to the specific page type that will contain it (the page baseclass if that is variable or unknown at the time).

During the load event of the page, we manually set the Parentform Property of all user controls (we do this in our master page for all master page level controls as well).

protected Page_Load(object sender, System.EventArgs e) 
{
    this.myControl.ParentForm = this;
    this.myControl2.ParentForm = this;
}

This provides immediate access from any user control back to the page and any of its exposed methods. It also provides a standardized (within our team) method of allowing controls to communicate between themselves through an interface in the ParentForm.

Our standard is to perform this assignment manually. For me this was a personnel consideration to make sure developers are aware of the controls they are adding (not setting the ParentForm will cause null reference exceptions if you attempt to access it obviously). If you wanted to perform this setting automagically, you could use the base class's Page_InitComplete event to cycle through any user controls and set the ParentForm to "this" that way.


Being in a different directory would get visual studio to give them different namespaces by default, causing the parent page class not to visible to the control.

Make sure the namespace declarations of both classes are the same, or import the parent page class namespace to the contorl with the using statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜