Tom Gullen
Tom Gullen

Reputation: 61727

Can't case webusercontrol, namespace not found

I have this control:

public partial class controls_UploadedImageView : System.Web.UI.UserControl
{

And in a static function I have this code:

using (var ctl = (controls_UploadedImageView)tmp0.LoadControl("~/controls/UploadedImageView.ascx"))
{
    ctl.RenderControl(h);
}

However the cast to `` fails:

The type or namespace name 'controls_UploadedImageView' could not be found (are you missing a using directive or an assembly reference?)

I can't work out how to cast the control properly so I can set it's properties before rendering.

Update

Turns out that as my project is a website project and not a Web Application, it is causing this issue. A solution is to convert the entire project to a web application but this looks time consuming and fiddly. Does anyone have any solution that doesn't require me to convert the entire project?

Upvotes: 1

Views: 360

Answers (2)

Matt
Matt

Reputation: 1616

I think I have fixed this before by using an interface.

Create an interface in the app_code folder

public interface ICustomControl
{
    ... add any extra methods here
}

when you declare the class for your user control, include that interface

public partial class controls_UploadedImageView : System.Web.UI.UserControl, ICustomControl

then use that interface.

using (var ctl = (ICustomControl)tmp0.LoadControl("~/controls/UploadedImageView.ascx"))

This is all from memory, but hopefully it gets you close to the solution. I'll check my code later if its not helping.

Upvotes: 2

mason
mason

Reputation: 32694

Try simply adding a namespace to your .ascx.cs (may need to update the .ascx also). Then add a using <namespace>; statement to the class that needs to reference that control.

Ex:

namespace MyFancyNamespace
{
    public partial class controls_UploadedImageView : System.Web.UI.UserControl
    {
    }
}

and...

using MyFancyNamespace; //this goes at the top of your class.

using (var ctl = (controls_UploadedImageView)tmp0.LoadControl("~/controls/UploadedImageView.ascx"))
{
    ctl.RenderControl(h);
}

Upvotes: 0

Related Questions