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.

7 comments:

Anand Balasubramanian 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.

Thanks,
Anand.

Unknown said...

Excellent article. Thank you.
Selvi.

Unknown 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.

Thanks,
Selvi.

Zabiullah Sheik Ismail said...

Anand : Thanks Anand!

Selvi : Thanks for your comments!

Have you fixed the issue? Check this one for removing WebPart from SharePoint Page
http://zabistop.blogspot.com/2008/12/code-to-remove-web-part-from-page-in.html

Unknown 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
mgr.DeleteWebPart(mgr.WebParts[i]);
break;
}
}

Thanks again for very useful article and help,
Selvi.

AK said...

To add/remove web parts programmatically refer following post:

http://www.etechplanet.com/post/2009/03/18/AddingRemoving-web-part-programmatically-in-SharePoint-website-using-C-Code.aspx

Prajakta said...

Perfect !!!

Thank you,
Prajakta.