Share via


How to: Work with Web Parts on a Page

Applies to: SharePoint Foundation 2010

Available in SharePoint Online

Use classes in the Microsoft.SharePoint.Client.WebParts namespace to work with Web Parts through the client object model. The LimitedWebPartManager class allows you to access the collection of Web Parts on a SharePoint page within a shared or personal scope through the WebParts property

Updating the title of a Web Part

The following example changes the title of the second Web Part in the collection of Web Parts on the Default.aspx page of the specified Web site. The example uses a LINQ query expression to return only the title of each Web Part, and calls the SaveWebPartChanges() method to save changes. The ExecuteQuery() or ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) method is called twice, first to return the collection of Web Parts so that the code can verify that Web Parts exist on the page, and second to effect changes in the database.

using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;

namespace SampleCode
{
    class UpdateWebPartTitle
    {
        static void Main()
        {
            ClientContext oClientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            File oFile = oClientContext.Web.GetFileByServerRelativeUrl("Default.aspx");
            LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            oClientContext.Load(limitedWebPartManager.WebParts,
                wps => wps.Include(
                wp => wp.WebPart.Title));

            oClientContext.ExecuteQuery();

            if (limitedWebPartManager.WebParts.Count == 0)
            {
                throw new Exception("No Web Parts on this page.");
            }

            WebPartDefinition oWebPartDefinition = limitedWebPartManager.WebParts[1];
            WebPart oWebPart = oWebPartDefinition.WebPart;
            oWebPart.Title = "My New Web Part Title";

            oWebPartDefinition.SaveWebPartChanges();

            oClientContext.ExecuteQuery();
         }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports Microsoft.SharePoint.Client.WebParts

Namespace Microsoft.SDK.SharePointServices.Samples
    Class UpdateWebPartTitle

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim serverRelativeUrl As String = "/sites/MySiteCollection/Default.aspx"

            Dim oClientContext As New ClientContext(siteUrl)
            Dim oFile As File = oClientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl)
            Dim limitedWebPartManager As LimitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared)

            oClientContext.Load(limitedWebPartManager.WebParts, _
                                Function(wps) wps.Include( _
                                    Function(wp) wp.WebPart.Title))

            oClientContext.ExecuteQuery()

            If limitedWebPartManager.WebParts.Count = 0 Then
                Throw New Exception("No Web Parts on this page.")
            End If

            Dim oWebPartDefinition As WebPartDefinition = limitedWebPartManager.WebParts(1)
            Dim oWebPart As WebPart = oWebPartDefinition.WebPart
            oWebPart.Title = "My New Web Part Title"

            oWebPartDefinition.SaveWebPartChanges()

            oClientContext.ExecuteQuery()

        End Sub
    End Class
End Namespace

Adding a Web Part to a page

The following example adds a custom content editor Web Part as the second Web Part, in order, within the left zone of the Default.aspx page for a specified Web site. The example defines the XML for the Web Part, passes this string to the ImportWebPart(String) method, and then calls the AddWebPart(WebPart, String, Int32) method to add the Web Part to the page.

using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;

namespace SampleCode
{
    class AddWebPart
    {
        static void Main()
        {
            ClientContext oClientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            File oFile = oClientContext.Web.GetFileByServerRelativeUrl("Default.aspx");
            LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            string xmlWebPart = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + 
                "<WebPart xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + 
                " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + 
                " xmlns=\"https://schemas.microsoft.com/WebPart/v2\">" + 
                "<Title>My Web Part</Title><FrameType>Default</FrameType>" + 
                "<Description>Use for formatted text, tables, and images.</Description>" +
                "<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>" +
                "<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>" +
                "<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>" +
                "<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>" +
                "<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />" +
                "<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />" +
                "<MissingAssembly>Cannot import this Web Part.</MissingAssembly>" +
                "<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />" +
                "<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, " + 
                "PublicKeyToken=94de0004b6e3fcc5</Assembly>" +
                "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" +
                "<ContentLink xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" />" +
                "<Content xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\">" +
                "<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>" + 
                "<PartStorage xmlns=\"https://schemas.microsoft.com/WebPart/v2/ContentEditor\" /></WebPart>";
            
            WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(xmlWebPart);

            limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "Left", 1);

            oClientContext.ExecuteQuery();            
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports Microsoft.SharePoint.Client.WebParts

Namespace Microsoft.SDK.SharePointServices.Samples
    Class AddWebPart

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim serverRelativeUrl As String = "/sites/MySiteCollection/Default.aspx"

            Dim oClientContext As New ClientContext(siteUrl)
            Dim oFile As File = oClientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl)

            Dim limitedWebPartManager As LimitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared)

            Dim xmlWebPart As String = "<?xml version='1.0' encoding='utf-8'?>" + _
            "<WebPart xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" + _
            " xmlns:xsd='http://www.w3.org/2001/XMLSchema'" + _
            " xmlns='https://schemas.microsoft.com/WebPart/v2'>" + _
            "<Title>My Web Part</Title><FrameType>Default</FrameType>" + _
            "<Description>Use for formatted text, tables, and images.</Description>" + _
            "<IsIncluded>true</IsIncluded><ZoneID></ZoneID><PartOrder>0</PartOrder>" + _
            "<FrameState>Normal</FrameState><Height /><Width /><AllowRemove>true</AllowRemove>" + _
            "<AllowZoneChange>true</AllowZoneChange><AllowMinimize>true</AllowMinimize>" + _
            "<AllowConnect>true</AllowConnect><AllowEdit>true</AllowEdit>" + _
            "<AllowHide>true</AllowHide><IsVisible>true</IsVisible><DetailLink /><HelpLink />" + _
            "<HelpMode>Modeless</HelpMode><Dir>Default</Dir><PartImageSmall />" + _
            "<MissingAssembly>Cannot import this Web Part.</MissingAssembly>" + _
            "<PartImageLarge>/_layouts/images/mscontl.gif</PartImageLarge><IsIncludedFilter />" + _
            "<Assembly>Microsoft.SharePoint, Version=13.0.0.0, Culture=neutral, " + _
            "PublicKeyToken=94de0004b6e3fcc5</Assembly>" + _
            "<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>" + _
            "<ContentLink xmlns='https://schemas.microsoft.com/WebPart/v2/ContentEditor' />" + _
            "<Content xmlns='https://schemas.microsoft.com/WebPart/v2/ContentEditor'>" + _
            "<![CDATA[This is a first paragraph!<DIV>&nbsp;</DIV>And this is a second paragraph.]]></Content>" + _
            "<PartStorage xmlns='https://schemas.microsoft.com/WebPart/v2/ContentEditor' /></WebPart>"


            Dim oWebPartDefinition As WebPartDefinition = limitedWebPartManager.ImportWebPart(webPartXml)

            limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, "Left", 1)

            oClientContext.ExecuteQuery()

        End Sub
    End Class
End Namespace

Deleting a Web Part from a page

The following example shows how to use the DeleteWebPart() method to delete the first Web Part from the Home.aspx page of a specified Web site.

using System;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.WebParts;

namespace SampleCode
{
    class DeleteWebPart
    {
         static void Main()
        {
            ClientContext oClientContext = new ClientContext("http://MyServer/sites/MySiteCollection");
            File oFile = oClientContext.Web.GetFileByServerRelativeUrl("/sites/MySiteCollection/SitePages/Home.aspx ");
            LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            oClientContext.Load(limitedWebPartManager.WebParts);
                        
            oClientContext.ExecuteQuery();

            if (limitedWebPartManager.WebParts.Count == 0)
            {
                throw new Exception("No Web Parts to delete.");
            }

            WebPartDefinition webPartDefinition = limitedWebPartManager.WebParts[0];

            webPartDefinition.DeleteWebPart();
            
            oClientContext.ExecuteQuery();            
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client
Imports Microsoft.SharePoint.Client.WebParts

Namespace Microsoft.SDK.SharePointServices.Samples
    Class DeleteWebPart

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim serverRelativeUrl As String = "/sites/MySiteCollection/SitePages/Home.aspx"

            Dim oClientContext As New ClientContext(siteUrl)
            Dim oFile As File = oClientContext.Web.GetFileByServerRelativeUrl(serverRelativeUrl)

            Dim limitedWebPartManager As LimitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared)

            oClientContext.Load(limitedWebPartManager.WebParts)

            oClientContext.ExecuteQuery()

            If limitedWebPartManager.WebParts.Count = 0 Then
                Throw New Exception("No Web Parts to delete.")
            End If

            Dim webPartDefinition As WebPartDefinition = limitedWebPartManager.WebParts(0)

            webPartDefinition.DeleteWebPart()

            oClientContext.ExecuteQuery()

        End Sub
    End Class
End Namespace

For information and examples about working with client objects within the context of the Microsoft SharePoint Foundation 2010 Silverlight object model, see Using the Silverlight Object Model.

See Also

Concepts

Data Retrieval Overview

SharePoint Client Object Creation

SharePoint 2010 Client Object Model Guidelines

Common Programming Tasks in the Managed Client Object Model

Web Parts in SharePoint Foundation

Other Resources

Client Class Library