views:

488

answers:

1

In a SharePoint 2007 web part, I want to delete an existing property and replace it with a property using a different name. I want to get the value from the existing property and assign it to the new property.

How should I do this?

A: 

In summary:

  • Get a reference to the page containing the web part.
  • Get a reference to the web part itself.
  • Change the property value.
  • Save the change.

In code:

using (SPSite site = new SPSite("http://sharepoint"))
using (SPWeb web = site.OpenWeb("Web Title"))
using (SPLimitedWebPartManager webPartManager =
       web.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared))
{
    try
    {
     foreach (WebPart webPart in webPartManager.WebParts)
     {
      if ((webPart.Title == "Web Part Title") && (!webPart.IsClosed))
      {
       YourWebPart wp = (YourWebPart)webPart;
       wp.NewProperty = wp.OldProperty;
       webPartManager.SaveChanges(wp);
       web.Update();
       break;
      }
     }
    }
    finally
    {
     webPartManager.Web.Dispose();
    }
}

Replace the following in this code example:

  • "http://sharepoint" - the address of your SharePoint site
  • "Web Title" - the title of the SharePoint web containing the web part to be changed (or use one of the other OpenWeb overloads
  • "default.aspx" - filename of the page containing the web parts
  • "Web Part Title" - title given to the web part on the page
  • YourWebPart - class name of the web part to change
  • NewProperty/OldProperty - names of the properties to change
Alex Angas