tags:

views:

22

answers:

1

Hi I am currently trying to add a web part to a page. All i think is well however i am using a piece of code that i thought returned all existing webparts but really it only returns the web parts that are currently on a given page.

web.GetWebPartCollection(url,storage);

I was hoping to get the reference to my web part that already resides in the web part gallery from the collection returned by the above code but my web part hasn't been deployed to the page yet as thats what i am trying to do!!!!

Does anyone know how i can get access to the web part gallery via a piece of c# code?

Cheers in advanced

Truez

+2  A: 

Hi Truez,

This should do it:

SPSite site = new SPSite( siteCollectionUrl );
SPWeb web = site.OpenWeb();
SPList webPartGallery = web.GetCatalog( SPListTemplateType.WebPartCatalog );
...

siteCollectionUrl is the URL of the site collection for which you wish to load the web part gallery of.

the SPList webPartGallery will contain all of the web parts in the current site collection's gallery.

EDIT:

It's probably also worth mentioning the difference in naming conventions in Sharepoint:

  • A sharepoint Site Collection is represented within the object model by a SPSite object.
  • A sharepoint Site is represented by a SPWeb object
Rick
I was expecting it to return a collection of web parts as i now need to pass a web part in to the AddWebPart() method in order to add it to the page. Do you know how to get this from a SPList item to a web part ready to add. Sorry i am fairly new to sharepoint only been doing it for 3 months :S
Truezplaya
SOtty i was confused about it. I have used an XML reader in order to return a web part :). Your code was very useful thank you:)
Truezplaya