views:

114

answers:

2

Can't find much information on how to do this at all - how can I add in a web part and then configure the settings for it?

+1  A: 
  1. Load the page you want to add the web part to via object model.
  2. Get the SPLimitedWebPartManager for this page.
  3. Add the web part you want via the AddWebPart() method.
  4. If your web part uses the normal web part configuration then you can access the settings via the web parts properties.
Flo
How do I obtain the name of the webpart? I am trying to use the Bamboo Data Viewer WP. Do I have to reference the DLL? Not sure how to do this and can't find any info on it at all.
Graeme
+1  A: 

Hi.

Here's a code snippet that will do that for you. In this example, I put a Content Editor Web Part on the page and set the content of it programmatically. If you want to find out what properties your web part has, you can manually put it on a page and export it. Examine the exported file for the property names. In your case, must must reference the 3rd party DLL, and use the name on the desired web part instead of the ContentEditorWebPart. You can find out the name by either using the Object Browser or Reflector.

SPFile spPageFile = web.GetFile(targetFilePath);
using (SPLimitedWebPartManager theMan = spPageFile.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
  ContentEditorWebPart cewp = new ContentEditorWebPart();
  cewp.ChromeType = PartChromeType.None;
  XmlDocument xmlDoc = new XmlDocument();
  XmlElement xmlEl = xmlDoc.CreateElement("NewCEWP");
  xmlEl.InnerText = string.Format(@"<h2>Blah blah blah...</h2>");

  cewp.Content = xmlEl;
  theMan.AddWebPart(cewp, "Main", 0);
  theMan.SaveChanges(wp);
}

Hope this helps.

Magnus Johansson
Thanks Magnus, that's a real help! I've tried looking for the Bamboo dll from the Add Reference dialog but can't find it. I managed to iterate through the WebPartCatalog and found the name of the web part to be Bamboo.SPGridView.dwp - not sure how much that helps me though! I'll persevere though and your code about the xml is a real help!Thanks
Graeme
@Graeme. The Bamboo assembly is probably not installed in the GAC, so you will have to select the browse tab in the Add Reference dialog and browse to the installation directory of the Bamboo DLL. Open the .dwp file in a text editor (it's in XML format) and find the property names you want to update/set.
Magnus Johansson
Brilliant, thanks so much - will need to do a search for where it installed to as it's not in the usual places.
Graeme