简体   繁体   中英

Retrieve a list of web parts on a page

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?

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);
        }
      }
    }
  }
}

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM