none
How can I declare and instantiate an object at the *same* time in an aspx page when the object requires the page context? RRS feed

  • Question

  • Example based on an aspx page 

    I need to instantiate an object that has a constructor that requires an instance of the System.Web.UI.Page, but this object cannot be instantiated at the point of its declaration because the 'this' context is not available.

    public class MyClass
    {
    public MyClass(System.Web.UI.Page page)
    //...
    }

    public class MyPage : System.Web.UI.Page { private MyClass myClassWorks; // Compiles but is not instantiated... private MyClass myClassFails = new MyClass(this); // Obviously fails because 'this' is not valid... protected void Page_Load(object sender, EventArgs e) { myClassWorks.DoSomething(); // Throws null exception because I have forgotten to instantiate it
    // This is the error I want to prevent } }

    A solution?  Is there any way that I can create a parameterless constructor for MyClass that can be used to 'register' the existence of the MyClass class in some way so that the System.Web.UI.Page can be assigned later, but before the MyClass instance is used? I thought about sub-classing the Page object (i.e. a MyExtendedPage object) that performs a Page_Load and then includes a virtual Instantiate_MyClasses function.  For a windows App a class static List<MyClass> would have worked just fine to keep a list of the instances, but aspx static variables are Application level and Session 'variables' involve a ViewState, neither would be acceptable.

    Any ideas?



    • Edited by Datamast Monday, March 19, 2018 12:57 PM
    • Moved by CoolDadTx Monday, March 19, 2018 1:57 PM ASP.NET related
    Monday, March 19, 2018 12:57 PM

All replies

  • Please post questions related to ASP.NET in the ASP.NET forums.

    Michael Taylor http://www.michaeltaylorp3.net

    Monday, March 19, 2018 1:57 PM
  • Thank you for your guidance, but I *did* select Visual C# when I created this thread (the page initially requested this) and I can only assume there is an error in the post code because my choice was ignored?  (I had to hunt for the relevant topic and chose it)  I thank you for your reply and I have reposted.
    Monday, March 19, 2018 5:41 PM