Tuesday 13 September 2011

SPContext.Current.FormContext ; Detecting if you are in Edit or Display mode programmatically.

In some scenarios you need to detect if you are working in Edit Mode or Display Mode, well if you want to do that programmatically there is only a way, and that is SPContext.Current.FormContext.

This class provides information about the context that is specific to a list item form. It contains four properties:

I am going in concentrate only in Form Mode. This property return an enumerator with four options:

  • Invalid: A placeholder value in the enumeration indicating that it has no valid display mode from one of the other enumeration values.
  • Display: Specifies that the control is in display mode.
  • Edit: Specifies that the control is in edit mode.
  • New: Specifies that the control is in New mode.

Let’s go to do a simple experiment, go to one of your Web Parts and copy and paste this code into the CreateChildControls() method.

if (SPContext.Current.FormContext.FormMode == SPControlMode.Display)
{
  this.Visible = false;
}
else 
{ 
  this.Visible = true; 
}

If you deploy your Web Part you will notice that it has disappear … but if you go to Site Action-> Edit Page you will see that your notice that the Web Part is display it!


image



Conclusion: SPContext.Current.FormContext is a really porwerfull tool to access to the page controls or check the status of our page.