Next time I want my webpart to hide itself I won’t use:
this.hidden = true;
because that will result in:
System.InvalidOperationException: The Visible property cannot be set on Web Part XXXXXXX
Instead, I will do the following:
SPFile myPage= SPContext.Current.File; SPLimitedWebPartManager limitedWebPartManager; //Get the page's limited webpart manager using (limitedWebPartManager = myPage.GetLimitedWebPartManager(PersonalizationScope.Shared)) { System.Collections.Generic.List configuratorWebParts = limitedWebPartManager.WebParts.Cast().Where(webpart => webpart.Title == "TITLE OF MY WEBPART").ToList(); if (configuratorWebParts.Count > 0) { foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in configuratorWebParts) { webPart.Hidden = true; limitedWebPartManager.SaveChanges(webPart); } } }
and voila!