There was a small question in the SharePoint development newsgroups that alluded to whether it was possible to use the SharePoint WebPartPage and SPWebPartManager objects in order to construct a small iteration through all the WebParts that were placed within an arbitrary WebPart page in a SharePoint instance and search for a specific WebPart type. The objects that will be exposed in this code example are pretty straightforward, notably:
WebPartPage – Represents a SharePoint WebPart page
SPWebPartManager – Derived from the ASP.NET 2.0 WebPart manager, the SPWebPartManager object manages all the WebParts and WebPart zones on a page.
WebPart – Represents, well you know, a frickin WebPart on the page
In this example, I will show you how to use the aforementioned objects, and then show you to how to build the loop that was the main part of the persons query in the newsgroups.
Here is the code, in this I will test for the most standard WebPart type, a ListViewWebPart, since it is orthodox and out-of-the-box.
WebPartPage l_oPage = (WebPartPage) this.Page;
SPWebPartManager l_oManager = (SPWebPartManager) l_oPage.Master.FindControl(this.SPWebPartManager);
foreach (WebPart l_oPart in l_oManager.WebParts)
if (l_oPart.GetType() != typeof(ListViewWebPart))
// Perform some action after the type test is complete, depending on your type return