14

I have created a webpart, now I need to add that webpart programmatically into the EditForm.aspx page. Can anyone help me on this.

5 Answers 5

21

You can create a feature and on the activation of the feature you can add the webpart to the page.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPSite site = properties.Feature.Parent as SPSite;
    using(SPWeb web = site.OpenWeb())
    {
        using(SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(page url, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
        {
            YourWebPart webpart = new YourWebPart();
            webpart.ZoneID = "Top";
            webpart.Title = "My Webpart";
            wpManager.AddWebPart(webpart,"Top" , 0);
        }
    }
}

Also have a look at this link for reference.

Hope it helps.

7
  • If suppose my webpart is not in the same solution, How will I be able to create an object and add it to a page? - Padmaraj.
    – Strider
    Aug 22, 2011 at 8:59
  • 4
    DISPOSAL WARNING: You need to check the disposals here! OpenWeb() returns a SPWeb object that needs disposal. SPLimitedWebPartManager must be disposed properly as well. Aug 22, 2011 at 9:04
  • I would like to add web part to default.aspx automaticlly exact when the web is created by using a feature. but I don't know when I must do it. because when feature is activated (within onet.xml) default.aspx doesn't exist
    – Medes
    Sep 14, 2012 at 14:52
  • @Wictor Wilen MCA MCM MVP If you see a mistake in someone's post, you should fix the mistake.
    – MgSam
    Jan 24, 2013 at 15:05
  • It's not working on sandbox solution. It's showing error on "SPLimitedWebPartManager". Is it possible for sandbox solution ? Jan 21, 2015 at 13:35
2

Take a look at the SPLimitedWebPartManager.

Grab the SPFile object related to the EditForm.aspx page and then execute the GetLimitedWebPartManager method on the SPFile object. Use the limited web part manager to modify the web part page.

0

Here is the method of SPLimitedWebPartManager class which opens the closed web parts

    // Summary:
    //     Opens a dynamic Web Part that was previously closed by CloseWebPart so it
    //     renders on the WebPartPage.
    //
    // Parameters:
    //   webPart:
    public void OpenWebPart(System.Web.UI.WebControls.WebParts.WebPart webPart);
1
  • He wanted to add a webpart on a page, not open a close one! May 23, 2013 at 7:44
0

If you don't want to directly reference WebPart type in the code, you can use SPLimitedWebPartManager.ImportWebPart method.

You just need to provide content of the *.dwp or *.webpart description file for the webpart instance you want to import.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.