Pages

Search This Blog

Friday, February 18, 2011

Adding WebPart Dynamically - Part-II


In a scenario we have created a CustomWebPart whose .dll is kept in the application Bin folder as per the requirement, now we have to add that webpart at runtime on the activation of a Feature,(so we cannot place that webpart dll in GAC), for this i have followed the following steps:


1.       Open the webPart gallery and click edit on your webpart.
2.      Now Click on "View Xml" .
3.  Copy that XML which looks something like:

@"<?xml version=""1.0"" encoding=""utf-8""?>
<webParts>
<webPart xmlns=""http://schemas.microsoft.com/WebPart/v3"">
<metaData>
<type name=""CustomWebPart, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name=""Title"" type=""string"">CustomWebPart</property>
<property name=""ControlName"" type=""string"">ucSiteSearch.ascx</property>
</properties>
</data>
</webPart>
</webParts>
You can also add your property values as I have added my custom propety value "ControlName" in the XML.
Now the Code snippet:
SPWebPartCollection objWebPartsCollection = objWeb.GetWebPartCollection(URLPage, Microsoft.SharePoint.WebPartPages.Storage.Shared);
string dwp = @"<?xml version=""1.0"" encoding=""utf-8""?>
<webParts>
<webPart xmlns=""http://schemas.microsoft.com/WebPart/v3"">
<metaData>
<type name=""CustomWebPart, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"" />
<importErrorMessage>Cannot import this Web Part.</importErrorMessage>
</metaData>
<data>
<properties>
<property name=""Title"" type=""string"">CustomWebPart</property>
<property name=""ControlName"" type=""string"">ucSiteSearch.ascx</property>
</properties>
</data>
</webPart>
</webParts>";

objWebPartsCollection.Add(dwp);


No comments:

Post a Comment