I am trying to get a list of webparts deployed on a web page in sharepoint 3.0. Is there way I can retrieve it from sharepoint content database or can I do it programmatically?
A:
This isn't how you described. However, I have gotten a list of the parts of a webpage using JavaScript code using the GreaseMonkey addin for Firefox.
Steven
2009-10-05 19:56:30
+3
A:
You can use the SPWebPartManager to iterate thru a list of web part in a page.
See this MSDN example.
EDIT: This is maybe a better example:
private static void GetWebParts()
{
using (SPSite site = new SPSite("<YOUR SITE URL>"))
{
using (SPWeb web = site.OpenWeb())
{
SPFile file = web.GetFile("default.aspx"); // or what ever page you are interested in
using (SPLimitedWebPartManager wpm = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
foreach (WebPart wp in wpm.WebParts)
{
Console.WriteLine("Web part: {0}", wp.Title);
}
}
}
}
}
Magnus Johansson
2009-10-05 20:31:50
A:
Adding web parts programmatically is simple:
SPWeb site = SPContext.Current.Web;
SPFile page = web.GetFile("Pages/somepage.aspx");
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
// logic to get web parts here.
ContentEditorWebPart webPart = new ContentEditorWebPart();
webPart.Title = "Test Web Part";
webPartManager.AddWebPart(webPart, "Zone 1", 0);
}
finally
{
// SPLimitedWebPartManager has known memory leak where it does not dispose SPRequest object in its SPWeb, so dispose it
webPartManager.Web.Dispose();
}
}
Anders Rask
2009-10-06 22:49:54