Edit Mode on a WebPart


It is sometimes interesting to know if the view of the current WebPart is the display view or the edit view.

I’ve done this little tutorial to show one difference which occur when you work with a Publishing site or not.

Working most of the time with publishing , I’m use to check the status with this test


if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit)

For example, the code below displays 2 lines. The first is always displayed and the second only on edit mode.


protected override void CreateChildControls()
{
string contenuPasSecret = "Je m'appelle Christopher.";
string contenuSecret = "J'ai 26 ans.";
Controls.Add(new LiteralControl(contenuPasSecret));
if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
Controls.Add(new LiteralControl(contenuSecret));
}

As you can see on the print screen below, only the first line is displayed.

When we edit the page, we see the second too.

Until there, all was ok!
Then I tried to use this WebPart on a “Team site” and I was surprised to see only one line on the edit mode!

So I’ve done some debug and I found that the error comes from the SPContext.Current.FormContext.FormMode , instead of sending me « Edit » , it send me « Invalid »!


So the tip to perform this check on a Team site is to use the current page’s WebPartManager . Let’s modify our code to have something like this.


protected override void CreateChildControls()
{
WebPartManager wpm = WebPartManager.GetCurrentWebPartManager(Page);
string contenuPasSecret = "Je m'appelle Christopher.";
string contenuSecret = "J'ai 26 ans.";
Controls.Add(new LiteralControl(contenuPasSecret));
if ((SPContext.Current.FormContext.FormMode == SPControlMode.Edit)|| (wpm.DisplayMode.Name.Equals("Design")))
Controls.Add(new LiteralControl(contenuSecret));
}

Now, all is ok! We have our 2 lines displaying in edit mode on both a team site and a publishing site

Christopher.

Article published for the first time the 2nd of June 2010 on Areaprog

Advertisements

2 thoughts on “Edit Mode on a WebPart

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s