Webpart引用UserControl有两种方法:
1. 引用QuickPart
2. 自己开发出一个WebPart暴露一个引用地址属性。代码如下:
View Code
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
namespace WebPartCollection
{
[Guid("1c7e7f5f-c4d6-4628-8785-3804bc0f5c85")]
public class UserControlWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
public UserControlWebPart()
{
}
private string _ControlPath;
[Personalizable]
[WebBrowsable]
[WebDisplayName("Control File Path")]
public string ControlPath
{
get { return _ControlPath; }
set { _ControlPath = value; }
}
protected override void CreateChildControls()
{
base.CreateChildControls();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (string.IsNullOrEmpty(_ControlPath))
return ;
try
{
Control calendar = Page.LoadControl(_ControlPath);
if (calendar!=null)
{
this.Controls.Add(calendar);
}
}
catch (Exception ex)
{
this.Controls.Add(new LiteralControl(ex.Message));
}
}
}
}
ControlPath的地址格式如下:~/_CONTROLTEMPLATES/Calendar.ascx,从以上的地址格式可以看出Calendar.ascx文件是放在12\TEMPLATE\CONTROLTEMPLATES文件夹里面。