0

How do I access a page class from another class. For example I have:

public partial class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { }
}

Why can I not access it from another class in App_Code folder?

public class MyClass
{
    public MyClass() {}
    public void DoSomething(object o)
    {
         // The following line won't compile.
         MyPage page = o as MyPage;
    }
}

I just figured it out (thanks to Fujiy) that for some reason this is the case with website project, but is not a problem with web application project in VS. If anyone has any clues as to why, please share your thoughts. Thank you :)

2
  • @anna: post it as an answer - I think you're right. Commented Jun 1, 2009 at 15:41
  • yeah me too, I just dumped it to VS to check for anything non-obvious :) Commented Jun 1, 2009 at 15:43

2 Answers 2

4

I see nothing wrong with your code as posted, most likely you've got a namespace problem.

edit: gah, just noticed that you mentioned this was a website project. It's been a while since I deigned to start one of those :) but I believe this stems from the fact that App_Code is run-time compiled. It would take a better man than me to explain why that creates the problem, but long story short I'd just avoid website projects in general.

Sign up to request clarification or add additional context in comments.

4 Comments

Code as posted works, must be namespace or you've a typo in your actual code.
I get this error: The type or namespace name 'MyPage' could not be found (are you missing a using directive or an assembly reference?). Just created a new project to check if it will work - it doesn't. The namespaces are non-existent.
In a website project, the namespaces are implicit based on the site structure. You'd need to explicitly identify the full path to the class you want to access, using "." instead of "/"...
@niaher - one of them is definitely in another namespace somehow I think your clearest way through is to check the object browser and/or put them in a namespace. Namespaces are good and intellisense is very good about helping you with them.
2

You can do this, afaik:

System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;

Be careful where you call that though, because obviously at different points in your code the page won't be available. For example, Application_Start in global.asax.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.