问题描述
我有一个用户控件,我需要动态地添加。我试图按照此MSDN文章,但我没有任何成功....
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
的用户控件基本上是一个图片库,并加载基于ID的一些照片。我的想法是让作为一个属性此ID。然后,当我创建控件的实例,我可以设置这个ID,并将其添加到窗体。
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.
我添加到.aspx页的控制将使用它,参考如下:
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" %>
当我尝试在.aspx.cs来创建一个实例类的文章指出,昏暗的长廊作为ASP.PictureGallery
,我得到一个类型ASP.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".
文中提到一个命名空间, ASP
,和我试了一下进口到没有运气的.aspx.cs。
所以,我不能够获取到用户控件的引用。
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.
怎样才可以解决吗?
推荐答案
这听起来像你混淆了用户控件工作两分开的方式。
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>
二是编程方式(或动态)在code将它添加到页面在运行时后面。如果是这样,那么你需要使用的是样本中提到的LoadControl功能。你不需要,如果你这样做是为了注册控件在aspx文件。
例如。
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)
修改结果
什么是在code后面的控件的类名称...是这样的:
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?
这篇关于在ASP.NET编程方式创建用户控件实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!