5

Files:

Website\Controls\map.ascx

Website\App_Code\map.cs

I'd like to create a strongly typed instance of map.ascx in map.cs

Normally, in an aspx, you would add a <%Register... tag to be able to instantiate in codebehind. Is this possible in an app_code class? I'm using .NET 3.5/Visual Studio 2008

Thanks!

2 Answers 2

4

Normally, I'd do something like this (assuming your type is "Map" and that you have the appropriate "Inherits" declaration in your .ascx file):

Map map = (Map)LoadControl("~/Controls/map.ascx");
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't work. The "Map" type is not available in App_Code. Something to do with how asp.net compiles the controls. That's what I meant by requiring the <%Register tag in the aspx to get the type available.
In cases like that I've usually moved the code-behind file (like Map.ascx.cs) into the App_Code folder.
ryan - thanks. Although the site doesn't compile as the codebehind is referring to a control from the ascx code. e.g.: icon.ImageUrl = imageUrl; Error: The name 'icon' does not exist in the current context
You can create a protected member variable in your class: "protected Image icon", for example (where "Image" is your other type...).
Doh! If I put the CodeFile="~\App_Code\map.ascx.cs" it gives a compile error: ... is in the special directory 'App_Code', which is not allowed. But trying to do a partial class also doesn't seem to work
1

Is there a map.ascx.cs file in Website\Controls? If so, move it to App_Code. Note you may have to update the CodeFile attribute in the .ascx file to ~\App_Code\map.ascx.cs. Alternatively, since the control is a partial class, you could just create the code in ~\App_Code\map.cs as:

public partial class controls_Map : UserControl
{
    protected void Page_Load( object sender, EventArgs e )
    {
         ...code here....
    }
}

And remove all the methods from the map.ascx.cs file in the controls directory.

2 Comments

Agreed. I neglected to mention moving the .ascx.cs file to App_Code as well.
Close-I've had to move methods like page_load into the ascx file but now I have a problem accessing Viewstate in methods/public properties inline: public Guid placeID { get { return (Guid)ViewState["placeID"]; } set { ViewState["placeID"] = value; } } Viewstate is not recognized.

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.