Wednesday, 16 October 2013

Remove Webpart from gallery

This is how you would programmatically remove a webpart from a webpart gallery in the feature event receiver.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
    using (SPWeb currentWeb = ((SPSite)properties.Feature.Parent).RootWeb)
    {
        //remove Student lottery webpart from web part gallery
        SPList webPartList = currentWeb.Lists["Web Part Gallery"];

        foreach (SPListItem webpart in webPartList.Items)
        {
            if (webpart["Title"].ToString() == "WebpartTitle")
            {
                webPartList.Items.DeleteItemById(webpart.ID);
                break;
            }
        }

        webPartList.Update();
        currentWeb.Update();
    }

}

You can find the webpart title in the mywebpartRegistration.webpart file, look for an element property with an name attribute of title.