Monday, January 23, 2012

Avoid “Cannot change Hidden attribute for this field” exception when remove field from Sharepoint list

When you remove field from the Sharepoint list either from UI or programmatically you may encounter with the following exception (I faced with this problem when removed managed metadata field, but it can be also any type of field):

Cannot change Hidden attribute for this field 
   Microsoft.SharePoint.SPField.set_Hidden(Boolean value)
   Microsoft.SharePoint.SPFieldCollection.Delete(String strName)
   Microsoft.SharePoint.ApplicationPages.FieldEditPage.BtnDelete_Click(Object sender, EventArgs e)
   System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

This problem is caused by CanToggleHidden property of the field which was set to false during field provisioning. It has no setter so once it was provisioned you can’t change it using regular object model. The good news is that it is possible to change it using reflection:

   1: private static void setCanToggleHidden(SPField field)
   2: {
   3:     Type type = field.GetType();
   4:     MethodInfo mi = type.GetMethod("SetFieldBoolValue", BindingFlags.NonPublic | BindingFlags.Instance);
   5:     mi.Invoke(field, new object[] {"CanToggleHidden", true});
   6: }

After you will call this method, exception won’t be thrown and it will be possible to remove the field from list.

1 comment: