Wednesday, February 18, 2009

Hiding webpart in SharePoint webpart gallery

How to hide webpart in Sharepoint Webpart gallery


To hide the webpart in webpart gallery programmatically, you have to write a feature class which drives from SPFeatureReceiver. This Feature receiver class will be called during feature activation/deactivation.


Steps
----
1) Get the instace of SPweb
2) Get the list from parent as "Web Part Gallery"
3) Find webpart ID
4) Delete from List
5) Update the list


Sample code snippet


public void OnActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = (SPWeb)properties.Feature.Parent;
SPList list = web.Lists["Web Part Gallery"];
int itemID = 0;
bool flag = false;
foreach (SPListItem item in list.Items)
{
if (item.Name.ToLower() == "test.webpart")
{
itemID = item.ID;
flag = true;
break;
}
}


if (flag)
{
list.Items.DeleteItemById(itemID);
list.Update();
}
}


Enjoy programming