Adding/Removing a web part by Code

Tags: SharePoint 2010, WebPart

Adding a web part

using (SPSite spSiteTest = new SPSite(“SiteURL”) 
 {   
   using (SPWeb spWebTest = spSiteTest.OpenWeb())   
   {     
     SPWebPartCollection webparts = spWebTest.GetWebPartCollection("WebPageURL",Storage.Shared);      
   
     //create new webpart object            
     WebPartToBeAdded wpNew = new WebPartToBeAdded();      

     //set properties of new webpart object     
     wpNew.ZoneID = "WebPartZoneIDWhereWebPartIsToBeAdded";     
     wpNew.Title = "Web Part Title";     
     wpNew.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;     
     wpNew.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;      

     //add new webpart object to webparts collection     
     webparts.Add(wpNew);      

     //update spWeb object     
     spWebTest.Update();     
   } 
 }          

Removing a web part

using (SPSite spSiteTest = new SPSite(“SiteURL”) 
 {
   using (SPWeb spWebTest = spSiteTest.OpenWeb())
   {
     SPWebPartCollection webparts = spWebTest.GetWebPartCollection("WebPageURL", Storage.Shared);
     for (int k = 0; k < webparts.Count; k++)
     {
       //get reference to webpart
       Microsoft.SharePoint.WebPartPages.WebPart wp = webparts[k];

       //check webpart Title to find webpart which is to be removed
       if (wp.Title == "TitleOfWebPartWhichIsToBeRemoved")
       {
         //delete webpart
         webparts.Delete(wp.StorageKey);

         //update spWeb object
         spWebTest.Update();  
       }                                                                                                                                                             }
   }
 }