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.

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.

  • 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 '11 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. – Wictor Wilen MCA MCM MVP Aug 22 '11 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 '12 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 '13 at 15:05
  • It's not working on sandbox solution. It's showing error on "SPLimitedWebPartManager". Is it possible for sandbox solution ? – Ronak Patel Jan 21 '15 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);
  • He wanted to add a webpart on a page, not open a close one! – Robert Lindgren May 23 '13 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, privacy policy and cookie policy

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