Link to home
Start Free TrialLog in
Avatar of SamDorling
SamDorling

asked on

ASP.NET 2.0 Reference User Control in Code

In ASP.NET 2.0, I have a User Control called MyUserControl.  How do I reference this in the code of a Class if I want to declare a variable of type MyUserControl or if I want to declare a method parameter of type MyUserControl .  For example -

MyUserControl opUserControl;

or

public void SetControlParameters(MyUserControl opControl)
{
...
}

We could do this fine in ASP.NET 1.1 but it doesn's seem possible in version 2.0.  Someone help please.
Avatar of SamDorling
SamDorling

ASKER

I believe I've found the answer but it's not the quickest/simplest solution so I would welcome any simpler solutions.

You need to build a base (abstract) class first with all public properties/methods defined.  You then create the User Control and your User Control must inherit from the base class.

You can then declare the User Control in your code as type [base class].

I find this annoying that I have to build 2 classes for every User Control I create & this wasn't necessary in version 1.1.
Unfortuately there is no easy way of doing this :( if you want to use the project model in VS 2005.
Actually MS discovered that this model is not so good especially for the projects that have to be migrated from VS 2003 to 2005.
That is why MS had created a web application project that uses the old project model and the references between classes is the easiest as it was in VS 2003

http://msdn2.microsoft.com/en-us/asp.net/aa336618.aspx

regards
Martin
If you add a reference on the .aspx to the usercontrol (The ones that start with <%@), you can then refer to that usercontrols class name in the codebeside file.  This is rather easy, but took me awhile to figure this out.  
raterus

Thanks for your response but the question was not how to reference a specific user control in code-behind but rather how to decare a variable of the type of the control eg -

MyUserControl opUserControl;

or

public void SetControlParameters(MyUserControl opControl)
{
...
}
There is no misunderstanding, as I know exactly what you are trying to do.  Please try what I have suggested, and you should be able to declare it like you have asked.
raterus

We are already using the User Control in various web forms with a Reference directive and we can access the instance of the user control fine in the code-behind fine.  This is not the issue.

What we are trying to do in this particular example is actually declare an object of type [UserControl] in a class which is not the code-behind file for a web form.

Response 1 and 2 to the original post are possible answers of acheiving this but we are just wondering if there is a less drastic method.
ASKER CERTIFIED SOLUTION
Avatar of raterus
raterus
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial