How can we add a webpart to sharepoint page programmatically?
1. First export the webpart to dwp file. Which is essentially an XML file.
2. Use below code to the load and add the webpart to your page.
SPSite site = new SPSite(SITEURL);
SPWeb web = site.RootWeb;
// Get the web part collection
SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager("default.aspx", .PersonalizationScope.Shared);
//Read Web Part dump
using (StreamReader sr = new StreamReader("WebPart.dwp"))
{
string errorMsg="";
//string webpartdwp=sr.ReadToEnd();
StringReader strR=new StringReader(sr.ReadToEnd());
XmlReader xmlR=XmlReader.Create(strR);
System.Web.UI.WebControls.WebParts.WebPart webPart=wpMgr.ImportWebPart(xmlR, out errorMsg);
wpMgr.AddWebPart(webPart, "Left", 0);
}
To Remove web parts:
using (SPSite site = new SPSite(siteUrl))
{
foreach (SPWeb web in site.AllWebs)
{
Application.DoEvents();
try
{
// Get the web part collection
SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
for (int i = 0; i < wpMgr.WebParts.Count; i++)
{
System.Web.UI.WebControls.WebParts.WebPart wp = wpMgr.WebParts[i];
if (wp.Title == "YOUR WEB PART TITLE")
{
wpMgr.DeleteWebPart(wp);
}
}
}
catch
{
//error handing codes here
}
finally
{
web.Dispose();
}
}
}
Enjoy!
No comments:
Post a Comment