转:http://www.soaspx.com/dotnet/asp.net/tech/tech_20120814_9489.html
/// <summary>
/// 向页面添加Webpart
///
</summary>
/// <param name="web">站点</param>
/// <param name="pageUrl">页面地址</param>
/// <param name="webPartName">Webpart名称</param>
/// <param name="zoneID">WebPartZone的ID</param>
/// <param name="zoneIndex">ZoneIndex</param>
/// <param name="properties">字典类型的杂项名称和值</param>
/// <returns></returns>
public static
string AddWebPartToPage(SPWeb web,
string pageUrl, string webPartName,
string zoneID, int zoneIndex, Dictionary<string,
string> properties)
{
using (Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager(
pageUrl, PersonalizationScope.Shared))
{
using (WebPart webPart = CreateWebPart(web, webPartName, webPartManager))
{
Microsoft.SharePoint.WebPartPages.SPUserCodeWebPart codeWebPart
= webPart.WebBrowsableObject as Microsoft.SharePoint.WebPartPages.SPUserCodeWebPart;
if (properties !=
null)
{
foreach (string key
in properties.Keys)
{
foreach (Microsoft.SharePoint.WebPartPages.SPUserCodeProperty item
in codeWebPart.Properties)
{
if (item.Name == key)
{
item.Value = properties[key];
}
}
}
}
webPart.ChromeType = PartChromeType.None;//设置部件版式类型 设置 无
webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
return webPart.ID;
}
}
}
public
static WebPart CreateWebPart(SPWeb web, string webPartName, Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager webPartManager)
{
SPQuery qry = new SPQuery();
qry.Query = String.Format("<Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>{0}</Value></Eq></Where>",
webPartName);
SPList webPartGallery = null;
if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(
SPListTemplateType.WebPartCatalog);
}
SPListItemCollection webParts = webPartGallery.GetItems(qry);
XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMsg;
WebPart webPart = webPartManager.ImportWebPart(xmlReader,
out errorMsg);
return webPart;
}
调用
Dictionary<string,
string> properity = new Dictionary<string,
string>();
properity.Add("CalendarURL",
"/SystemSetting/Lists/EnterpriseCalendar/AllItems.aspx"); CommonUtil.AddWebPartToPage(systemWeb,
"/SystemSetting/SitePages/CalendarView.aspx",
"EnterpriseCalendarViewWebPart.webpart",
"Left",
0, properity);