sharepoint代码添加WebPart

Adding a web part
 
Following code snippet can be used to add a web part in an existing SharePoint website:
 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
 
Following code snippet can be used to remove a web part from an existing SharePoint website:
 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();  
       }                                                                                                                                                             }
   }
 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。