Add Web Part to Page Programmatically

4 Jan

I use the following code to programmatically add web parts to my pages.

I frequently see similar code, but no one is ever using the xml from the web part library to do the import, and as such the properties are not set to what was exported/defined in the web part xml.


XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());

WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);




public static string AddWebPartToPage(SPWeb web, string pageUrl, string webPartName, string zoneID, int zoneIndex) {
 using(SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared)) {
  using(System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(web, webPartName, manager)) {
   manager.AddWebPart(webPart, zoneID, zoneIndex);
   return webPart.ID;

public static WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager manager) {
 SPQuery query = new SPQuery();
 query.Query = String.Format(CultureInfo.CurrentCulture, "<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>", webPartName);
 SPList webPartGallery = null;
 if (null == web.ParentWeb) {
  webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
 } else {
  webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
 SPListItemCollection webParts = webPartGallery.GetItems(query);
 XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
 string errorMessage;
 WebPart webPart = manager.ImportWebPart(xmlReader, out errorMessage);
 return webPart;
Tweet about this on TwitterShare on Google+Share on FacebookShare on RedditEmail this to someoneShare on LinkedInShare on StumbleUpon

One thought on “Add Web Part to Page Programmatically

Leave a Reply

Your email address will not be published. Required fields are marked *