I need to put the webpart calendar in a specific SharePoint 2010 site, but we need to do it by code.
The calendar must be shown on the main zone. How can I add the web-part with C# code?
You can use SPLimitedWebPartManager to do this. There is an example how to add Content Editor web part to the page, but in your case it should work too. If you works with published page you can use this code.
gWeb publishingWeb = PublishingWeb.GetPublishingWeb(webSite);
SPListItem item = publishingWeb.PagesList.GetItemByFileName(pageName);
if (item != null)
{
PublishingPage publishingPage = PublishingPage.GetPublishingPage(item);
try
{
if (item.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
{
publishingPage.CheckOut();
}
else
{
item.File.UndoCheckOut();
publishingPage.CheckOut();
}
webPartManger = item.File.GetLimitedWebPartManager(PersonalizationScope.Shared);
//code that adds web part
publishingPage.Update();
publishingPage.CheckIn(updateComment);
if (publishingWeb.PagesList.EnableModeration)
{
item.File.Publish(updateComment);
item.File.Approve(updateComment);
}
}
finally
{
if (webPartManager != null)
{
webPartManager.Dispose();
}
}
}