Saturday, January 9, 2010

Hide WebPart at run time

In one of my project we had a requirement to hide the WebPart based on the logged in user's department-id. We are not able to use Audiance Targeting to achieve this cuase we were getting user's department id using webservice from 3rd party system only.
What I did, I wrote my custom RSS Viwer WebPart with custom field. And Thanks to SharePoint Developer Center, I found a solution to hide the webpart at runtime very easily.
See the Code Snippet below.
protected override void OnPreRender(EventArgs e)
{
if(your condition)
HideWebParts();
}

private void HideWebParts()
{
if (this.WebPartManager.DisplayMode != System.Web.UI.WebControls.WebParts.WebPartManager.EditDisplayMode
&& this.WebPartManager.DisplayMode != System.Web.UI.WebControls.WebParts.WebPartManager.DesignDisplayMode)
{
for (int i = 0; i <>

{
if (WebPartManager.WebParts[i].Title == this.YourCustomWebPartName.Title)
{
WebPartManager.WebParts[i].AllowHide = true;
WebPartManager.WebParts[i].Hidden = true;
} } } }