SharePoint: Adding a webpart to a page through the object model

The code below illustrates adding a custom webpart to a webpart page (it doesn’t have to be a custom webpart, you can also following this approach with standard webparts). In this case I am going to add a custom redirector webpart to redirect to ./home/default.aspx to the left webpart zone on Default.aspx.

using System;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using MyWebParts.Redirector;
public static void AddTestWebPartToDefaultPage(string webUrl)
    using (SPSite site = new SPSite(webUrl))
        using (SPWeb web = site.OpenWeb())
            string webPartPageUrl = string.Format("{0}/home/default.aspx", web.Url);
            Redirector homePageRedirector = new Redirector();
            homePageRedirector.Destination = webPartPageUrl;
            SPLimitedWebPartManager webPartManager = web.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared);
            webPartManager.AddWebPart(homePageRedirector, "Left", 0);

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>