Friday, January 2, 2009

Programmatically adding web part to a SharePoint page from web part gallery

I had a requirement to add a web part to default.aspx page from Web part gallery. I have used a Feature to do the same. Please find the code below which is written in “Feature Activated” event.

Feature Activated

Add WebPart

Get WebPart XML

Hope the code is straightforward to understand.


Anand said...

Hi Zabi,

I have the same exact requirement to add a web part to several pages in a huge portal share point site. Your code sample will be very helpful as a starting point for me to code the same.

Thanks for posting the same.


SS said...

Excellent article. Thank you.

SS said...

Hi Zabi,

I used this same code to delete the web part. But the mgr.DeleteWebPart(wp) throws exception "The operation could not be completed because the Web Part is not on this page."

Any suggestions.


Zabi said...

Anand : Thanks Anand!

Selvi : Thanks for your comments!

Have you fixed the issue? Check this one for removing WebPart from SharePoint Page

SS said...

Thank you for your response.

Because my custom web part is not of type "Microsoft.SharePoint.WebPartPages.WebPart" the "foreach" threw exception as it was unable to cast the "Microsoft.SharePoint.WebPartPages.WebPart" to the custom web part type.

This worked for me. I was also concerned getting webpart by its title as the user may change the title.

SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager(rootWebUrl, PersonalizationScope.Shared);

for (int i = 0; i <= mgr.WebParts.Count - 1; i++)
if (mgr.WebParts[i].GetType().AssemblyQualifiedName == "custom web part qualified assembly name")
//Delete the web part from the page

Thanks again for very useful article and help,

AK said...

To add/remove web parts programmatically refer following post:

Prajakta said...

Perfect !!!

Thank you,