Navigation

Tuesday, 10 March 2015

Add Calendar List View WebPart to SharePoint page

My custom list have two views (default list view & calendar view) and I would like to display the Calendar view when added to SharePoint page. After spending sometime trying to figure out, I finally find the solution. Hopefully it save you a lot of time. 
Solution
Change XsltListViewWebPart into ListViewWebPart
private void AddCalendarViewWebPart(SPFile file, SPList list, string webPartZone, int webPartOrder, Guid viewId)
{
   SPLimitedWebPartManager limitedWebPartManager = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
   ListViewWebPart wp = null;
   list.ParentWeb.AllowUnsafeUpdates = true;
 
   try
   {
       // create an instance of the ListViewWebPart
       wp = new ListViewWebPart();
 
       // convert the list GUID to a string, must include braces (ToString("B")) and be in uppers (ToUpper())
       wp.ListName = list.ID.ToString("B").ToUpper();
 
       // optionally set the title of the web part
       wp.Title = list.Title;
       wp.ViewGuid = viewId.ToString("B").ToUpper();
       wp.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
 
       // add the web part to the limited web part manager. 
       limitedWebPartManager.AddWebPart(wp, webPartZone, webPartOrder);
 
       // you need to update the list because a view was just added to it
       list.Update();
   }
   finally
   {
       // do some fun cleanup of disposable items.  if you are wondering about the .Web.Dispose() bit look for my
       // blog article on the memory leaks in the SPLimitedWebPartManager.
       if (limitedWebPartManager != null)
       {
           if (limitedWebPartManager.Web != null)
           {
              limitedWebPartManager.Web.Dispose();
           }
 
           limitedWebPartManager.Dispose();
       }
 
       if (wp != null)
       {
           wp.Dispose();
       }
       list.ParentWeb.AllowUnsafeUpdates = true;
   }
}

No comments:

Post a Comment