简体   繁体   English

在Sharepoint 2010中以编程方式添加用户控件

[英]Programmatically adding a user control in Sharepoint 2010

I'm trying to add a custom user control to a Panel in a visual web part in Sharepoint 2010, with the following lines of code: 我正在尝试使用以下代码行将自定义用户控件添加到Sharepoint 2010中可视化Web部件的面板中:

MyUserControl userControl = new MyUserControl();

MainContentPanel.Controls.Add(userControl);

However, my user control fails to load/render. 但是,我的用户控件无法加载/渲染。 The above code is triggered by clicking a link button. 上面的代码是通过单击链接按钮触发的。

Am I missing something, or is it just not possible to do it this way? 我是否缺少某些东西,或者只是无法做到这一点?

Because the usercontrols are stored in the 12/14 hive you need a clear reference to the path of the user control. 由于用户控件存储在12/14配置单元中,因此需要清楚地引用用户控件的路径。 Thats why you always need to do: 因此,您始终需要这样做:

private const string _ascxPath = @"~/_CONTROLTEMPLATES/ProjectFolder/controlname.ascx"; 

MyControl MyUserControl = (MyControl)LoadControl(_ascxPath);

Controls.Add(MyUserControl);

However, you can also add it directly to the webpart/page/control by doing something like (determined by where you're placing it): 但是,您还可以通过执行类似操作(由放置位置决定)将其直接添加到webpart / page / control中:

<%@ Register TagPrefix="MyPrefix" Namespace="MyNameSpace.MyControl"
    Assembly="MyAssemby"%>

 <MyPrefix:MyControl ID="MyId" runat="server" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM