Why Main Page Class is restricted in User Control Code behind? RRS feed

  • Question

  • User619554136 posted

    Best practice is to code usercontrols independent to pages where we embed them. So generally Usercontrols will not be page specific as those can be reused in any aspx pages.

    So we generally do not use Main page object in usercontrol. I mean we do not access the methods and members of main page from user control.

    for a while if we park best practice aside.

    What's the reason .NET and VS is not recognising the MainPage Class Name in Usercontrol.

    //WebUserControl is a Usercontrol //and this usercontrol will be embed in Default.aspx (code behind class name is _Default) public partial class WebUserControl : System.Web.UI.UserControl { protected void Page_Load(object sender, EventArgs e) { //Here _Default is aspx codebehind class name where we embed this webusercontrol. //_Default is not allowed here. _Default is not recognized and gives compilation error. //this.Page as _Default;

    //Workaround Inherit aspx page from BasePage class. //BaseContentPage class will inherit System.UI.Page. //This way you can access the methods and members of Main page from user control. Response.Write((this.Page as BasePage).MyPageName); } }

    Please read the comments I wrote in above code snippet.

    Just not allowing the public class is against to OOPs.


    Why Main Page Class is restricted in User Control Code behind?


    If C# restricts main page class names in usercontrols (just to enforce best practice) then why BasePage inherited from System.Web.UI.Page is allowed?

    Tuesday, April 19, 2011 9:05 PM

All replies

  • User560403387 posted

    This doesn't have anything to do with best practices. _Default is not recognized, simply because you're not importing the correct namespace/assembly.


    Wednesday, April 20, 2011 5:08 AM