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
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.– StriderAug 22, 2011 at 8:59
-
4DISPOSAL 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– MedesSep 14, 2012 at 14:52
-
@Wictor Wilen MCA MCM MVP If you see a mistake in someone's post, you should fix the mistake.– MgSamJan 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
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.
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);
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.