Monday, April 23, 2012

Add ECB Menu to any field in SharePoint porgrammatically

After long research on this - came up with something like this , however there are lots of approaches already available on net which shows you to do the same using SharePoint designer or by creating new column.
Thanks to improved SharePoint 2010 APIs which gives the SPField.ListItemMenu property , but one thing to note here is setting this property to true does not reflect the changes , before setting this property - MSDN documentation says that you need to set the SPField.ListItemMenuAllowed to Required.


try
{
   SPContext.Current.Web.AllowUnsafeUpdates = true;

   SPList list = SPContext.Current.Web.Lists.TryGetList("Cities");
   SPField countryField = list.Fields.GetField("Country");
   if (countryField.ListItemMenuAllowed == SPField.ListItemMenuState.Prohibited || countryField.ListItemMenuAllowed == SPField.ListItemMenuState.Allowed)
   {
       countryField.ListItemMenuAllowed = SPField.ListItemMenuState.Required;
   }
    countryField.ListItemMenu = true;
    countryField.Update();
    list.Update();
    SPContext.Current.Web.Update();

    SPContext.Current.Web.AllowUnsafeUpdates = false;

 }
 catch (Exception ex)
 {
    this.Controls.Add(new LiteralControl("Error: " + ex.Message));
 }

Hope this helps someone.

3 comments: