Adding/ Deleting webpart using sharepoint features

Referred URL:

http://www.sharepointdevwiki.com/display/public/How+to+create+Web+Part+instances+on+pages+using+Features+-+FeatureReceiver+-+SPLimitedWebPartManager

This post helps you to add / delete webpart using sharepoint feature. 

Open VS 2008 -> WSP builder -> Feature with receiver ->

Adding Webpart

public override void FeatureActivated(SPFeatureReceiverProperties properties) {

using (SPWeb web = properties.Feature.Parent as SPWeb)

   {

    SPFile file = web.GetFile(web.Url + "/default.aspx");

    using (SPLimitedWebPartManager webpartsMng = file.GetLimitedWebPartManager(PersonalizationScope.User))

    {

    ContentEditorWebPart webPart = new ContentEditorWebPart();

     webPart.Title = "Test Web Part";

     webpartsMng.AddWebPart(webPart, "Right", 0);

    webpartsMng.Web.Dispose();

   }

  }

}

Deleting webpart add this code in deactivating

public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {

SPWeb web = properties.Feature.Parent as SPWeb;

SPFile file = web.GetFile(web.Url + "/default.aspx");

using (SPLimitedWebPartManager webpartsMng = file.GetLimitedWebPartManager(PersonalizationScope.User))

{

try

{

for (int i=0; i< webpartsMng.WebParts.Count; i++)

webpartsMng.DeleteWebPart(webpartsMng.WebParts[i]);

}

finally

{

if(webpartsMng.Web != null)

webpartsMng.Web.Dispose();

}

}

}

You May Also Like

0 comments