Provisioning a Web Part with a predefined ID in your onet.xml of element manifest.

From time to time you might want to provision your WebParts using the CAML markup and then modify them in a feature later on. Most examples on the web find the webpart based on it’s title. i.e.

foreach(Webpart webpart in webpartManager.WebParts)
{
   if(webpart.Title == "Title I'm expecting")
   {
       // Do something with the webpart
       webpart.AuthorizationFilter = "";
       webpartManager.SaveChanges(webpart);
   }
}

However you can specify the ID of a web part in your onet.xml / element manifest like so:

 <View List="Lists/MyList" BaseViewID="1" DisplayName="Counter Parties" Name="List Nmae" RecurrenceRowset="TRUE" WebPartZoneID="Header" WebPartOrder="1">
        <![CDATA[
               <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
                    <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
                    <TypeName>Microsoft.SharePoint.WebPartPages.ListViewWebPart</TypeName>
                    <Title>MyList - Workflow Users</Title>
                    <DetailLink>~Site/Lists/MyList/AllItems.aspx</DetailLink>
                    <Description>Use this list to store ... information.</Description>
                    <ID>g_45C819FD_FC4C_44e1_81DD_3AE4FCC34D37</ID>
               </WebPart>
            ]]>
      </View>

Create a new Guid replace the hyphens with underscores and add a “g_” to the beginning of the string g_45C819FD_FC4C_44e1_81DD_3AE4FCC34D37.

Now we can reference the web part in your feature receiver using the indexer property, which is I think you’ll agree much more elegant and less error prone:

Webpart = webpartManager["g_45C819FD_FC4C_44e1_81DD_3AE4FCC34D37"]
// Do something with the webpart
webpart.AuthorizationFilter = "";
webpartManager.SaveChanges(webpart);
Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: