Introduction
In SharePoint, We have multiple option to add a webpart in sitepages using programmatically. By,
- Using Elements.xml
- Referring Webpart Assembly
- Using SPLimitedWebaprtManager
Lets see one after one.
Using Element.xml
First Create a SharePoint Empty Project using Visual studio. Then, Add Module with name of SitePages. Add a aspx page in SitePages module. After added a visual webpart in the project. We may get three files.
Follow the below steps to add webpart property in sitepages property:
- Copy the properties from <webParts> to </webParts> in .webpart file.
- Then, Go to Element.xml file of SitePages module.
- Create <AllUsersWebPart> between particular page's file tag
- Paste the <Webparts> within <AllUsersWebPart>.
- Deploy the project to SharePoint site
Referring Webpart Assembly
We have an option to register the webpart in SitePage and use it as normal control. Steps are,
- Go to particular sitepage
- Add Register tag at top of the page. Like this
<%@ Register TagPrefix="TestWB" Namespace="Test.TestWebpart" Assembly="Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=59ae411e05487fd3" %>
- Use the webpart as normal control in aspx page.
<TestWB:TestWebPart ID="obj1" runat="server" />. Then, deploy and check in your page.
Using SPLimitedWebaprtManager
Here, We are going to add a webpart in the page using SPLimitedWebaprtManager. Steps are,
- Create Event Receiver for Feature
- Paste the below code on FeatureActivated event
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);
}
}
}
Then, Deploy solution and activate the feature. The webpart will display in the page. Happy Coding... !!!!!
No comments:
Post a Comment