1

It's rather frustrating that a task such as ensuring a web part zone has a certain web part in it (on a page layout) is such a difficult or, at the very least, tricky task considering it's surely included in many specifications!?

  1. I've tried the xml approach to this: http://sharepointsearch.com/cs/blogs/sharepointblogs/archive/2007/11/23/adding-custom-webparts-in-a-sharepoint-site-definition.aspx
  2. And even used the following server control to try and achieve it: http://code.msdn.microsoft.com/Adding-default-web-parts-ab7aec72

The problem with solution 1 is that every time I switch between a new page layout - the web part's added again (as explained in the article link in solution number 2). Not to mention the fact that every time I deploy a page layout with this xml a duplicate web part is added (which then calls the need for a feature event receiver!!).

The problem with solution 2 is similar - in the fact that when I switch between page layouts - the web part is added to completely different web part zones on completely different pages!

I'd really appreciate any help anyone can offer on this.

1 Answer 1

3

The way I do this is similar to #2, but when I add the webpart, I store it's ID into the SPWeb property bag so I know whether I've added the webpart to the page or not:

if (web.AllProperties.ContainsKey("MY_WEBPART_ID")) return;

WebPart webPart = new MyWebPart();

using (SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager("Default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
    try
    {
        mgr.AddWebPart(webPart, "MiddleLeftZone", 2);
    }
    finally
    {
        if (mgr != null &&
            mgr.Web != null)
        {
            mgr.Web.Dispose();
        }
    }
}
web.AllProperties["MY_WEBPART_ID"] = webpart.ID;

You can always loop through the webparts on the page and make sure it's not currently on there before you add it:

Guid webPartId = new Guid(web.AllProperties["MY_WEBPART_ID"]);
using (SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager("Default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
    try
    {
        foreach (WebPart wp in mgr.WebParts)
        {
            if (wp.ID == webPartId)
            {
                return;
            }
        }

        WebPart webPart = new MyWebPart();
        mgr.AddWebPart(webPart, "MiddleLeftZone", 2);
        web.AllProperties["MY_WEBPART_ID"] = webpart.ID;
    }
    finally
    {
        if (mgr != null &&
            mgr.Web != null)
        {
            mgr.Web.Dispose();
        }
    }
}

P.S. Some of the code above is just from memory, make sure you debug it first to make sure it works as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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