3

How might I create a SharePoint 2010 content query web part programatically and add it to a SharePoint page?

1
  • There's a lot of articles and blog post describing this task - I posted one of them as an answer below. Can you make your question more specific? Are you facing any particular problem? Jun 16, 2011 at 6:23

1 Answer 1

0

The post Adding/Removing web part in SharePoint website programmatically using C# code contains a detailed description of adding and removing Web Parts.

Here's a snippet taken from the above post adding a Web Part to a page (replace the WebPartToBeAdded pseudoclass with ContentByQueryWebPart):

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();    
   } 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.