LemmyLogic
LemmyLogic

Reputation: 1083

Create a usercontrol instance programmatically in ASP.NET

I have a UserControl that I need to add dynamically. I tried to follow this MSDN article, but I'm not having any success.... http://msdn.microsoft.com/en-us/library/c0az2h86.aspx

The UserControl is basically an image gallery, and it loads some pictures based on an ID. My idea was to make this ID available as a property. Then when I create an instance of the control, I could set this ID and add it to the form.

I added a reference to the control in the .aspx page that will use it, like this:

<%@ Reference Control="~/PictureGallery.ascx" %>

And in the UserControl I added a ClassName like this:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PictureGallery.ascx.cs"
Inherits="PictureGallery" ClassName="PictureGallery" %>

When I try to create an instance in the .aspx.cs like the article suggests, Dim gallery As ASP.PictureGallery, I get an "Type ASP.PictureGallery is not defined".

The article mentions a namespace, ASP, and I tried importing it to the .aspx.cs with no luck. So, I'm not able to get a reference to the UserControl.

How can it be fixed?

Upvotes: 2

Views: 9938

Answers (3)

davidsleeps
davidsleeps

Reputation: 9503

It sounds like you are confusing two separate ways of working with a UserControl.

One way is to register the control on your page so that you can put it into the page at Design Time e.g.

<div>
    <asp:PictureGallery id="myGallery" runat="server" MyProperty="SomeValue">  
    </asp:PictureGallery>
</div>

The second is programmatically (or dynamically) adding it into the page at runtime in your code behind. If so, then you need to use the LoadControl function which is mentioned in the sample. You do not need to register the control in the aspx file if you do this. e.g.

Dim gallery as PictureGallery = LoadControl("~/PathToControl/gallery.ascx")
gallery.MyProperty = "SomeValue"
placeHolder.controls.add(gallery)

edit
What is the class name of the control in the code behind...something like this:

Partial Public Class MyControlsClassName
    Inherits System.Web.UI.UserControl

That is the type you need to use when you declare it. Is it within a namespace perhaps?

Upvotes: 7

WiseGuyEh
WiseGuyEh

Reputation: 19080

The ASP namespace is generated at run time- user controls get "compiled" as they are used by .aspx pages so this is why you get the error message "Type ASP.PictureGallery is not defined".

When adding user controls dynamically you should use the Page.LoadControl method:

Page.LoadControl("~/PictureGallery.ascx")

Upvotes: 0

m.edmondson
m.edmondson

Reputation: 30872

I don't think you've placed the control in your code behind. You may well have created the reference, but do you have a tag such as <asp:PictureGalary id="gallary"></asp:PictureGalary> anywhere in your aspx?

Upvotes: 0

Related Questions