Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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();
        }
    }
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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