在WSS的开发中有时需要通过程序操作页面上的Web Part,比较添加,删除Web Part.此时可以使用 SPLimitedWebPartManager这个类,代码如下:
//添加Web Part
string AbsolutePageUrl = "http://YourSite/Page.aspx";
using (SPSite site = new SPSite(AbsolutePageUrl))
{
using (SPWeb web = site.OpenWeb(AbsolutePageUrl))
{
SPLimitedWebPartManager SpWebPartManger = web.GetLimitedWebPartManager(AbsolutePageUrl,
System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
// if MyWebPart is already installed, leave!
foreach (var webpart in SpWebPartManger.WebParts)
{
if (webpart is MyWebPart)
return;
}
// else add it in the bottom!
SpWebPartManger.AddWebPart(new MyWebPart(), "Main", 10);
SpWebPartManger.Dispose();
}
}
//删除Web Part
string AbsolutePageUrl = "http://YourSite/Page.aspx";
using (SPSite site = new SPSite(AbsolutePageUrl))
{
using (SPWeb web = site.OpenWeb(AbsolutePageUrl))
{
SPLimitedWebPartManager SpWebPartManger = web.GetLimitedWebPartManager(AbsolutePageUrl,
System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
WebPart webPartToDelete = null;
// let's locate the webpart first....
foreach (WebPart webpart in SpWebPartMaanger.WebParts)
{
if (webpart is MyWebPart)
{
webPartToDelete = webpart;
break;
}
}
if (webPartToDelete != null)
SpWebPartManger.DeleteWebPart(webPartToDelete);
SpWebPartManger.Dispose();
}
}
可参考:Add or Remove WebParts into SharePoint 2007 on runtime using SPLimitedWebPartManager
How to create Web Part instances on pages using Features - FeatureReceiver - SPLimitedWebPartManager
Content Query Web Part的RSS Feed的URL格如下:
wp=guid中的这个guid是指Content Query Web Part的ID,但是它并非是WebPart.UniqueId而是要通过SPLimitedWebPartManager.GetStorageKey()这个方法获取