Prgramatically add Custom WebPart to SharePoint Views or aspx page
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://RKU:777/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists.TryGetList("MyDocs");
SPView myview = list.Views["RKUVIewTest"];
using (SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(myview.Url, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
SPList list1 = web.Lists.TryGetList("Web Part Gallery");
SPListItemCollection Icoll = list1.Items;
foreach (SPListItem item in Icoll)
{
if (item.Title.Contains("SPGridTest"))
{
SPFile page = web.GetFile(myview.Url);
using (SPLimitedWebPartManager manager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
string errMsg = string.Empty;
SPFile myWebPart = web.GetFile(item.Url);
XmlTextReader read = new XmlTextReader(myWebPart.OpenBinaryStream());
var wp = manager.ImportWebPart(read, out errMsg);
manager.AddWebPart(wp, "Top", 1);
manager.SaveChanges(wp);
}
}
}
}
}
}
});
No comments:
Post a Comment