The Add / Remove Web Part message on a SharePoint website programmatically using C # code provides a detailed description of adding and removing web parts.
Here is a snippet taken from the above post that adds the web part to the page (replace the alias WebPartToBeAddedwith ContentByQueryWebPart):
using (SPSite spSiteTest = new SPSite("SiteURL")
{
using (SPWeb spWebTest = spSiteTest.OpenWeb())
{
SPWebPartCollection webparts = spWebTest.GetWebPartCollection("WebPageURL",Storage.Shared);
WebPartToBeAdded wpNew = new WebPartToBeAdded();
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;
webparts.Add(wpNew);
spWebTest.Update();
}
}
source
share