tags:

views:

2133

answers:

2

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!

+3  A: 

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");
Ryan Duffield
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.
Mofoo
In cases like that I've usually moved the code-behind file (like Map.ascx.cs) into the App_Code folder.
Ryan Duffield
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
Mofoo
You can create a protected member variable in your class: "protected Image icon", for example (where "Image" is your other type...).
Ryan Duffield
Ryan - awesome this did the trick! Thank you!
Mofoo
No problem, glad I could help. :-)
Ryan Duffield
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
Mofoo
i removed the codefile. this worked... wack.
Mofoo
+1  A: 

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.

tvanfosson
Agreed. I neglected to mention moving the .ascx.cs file to App_Code as well.
Ryan Duffield
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.
Mofoo