Create a usercontrol instance programmatically in ASP.NET

后端 未结 3 795
不知归路
不知归路 2021-01-07 04:58

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/c0az2h8

相关标签:
3条回答
  • 2021-01-07 05:32

    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?

    0 讨论(0)
  • 2021-01-07 05:33

    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?

    0 讨论(0)
  • 2021-01-07 05:47

    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")
    
    0 讨论(0)
提交回复
热议问题