Add ECB to View Columns

Some code to add the ECB menu to the specified columns of a view:

public void SetEcbColumnOnView(SPView view, List<string> internalNames)
{
    if (view == null)
        throw new ArgumentNullException("view");
 
    const string ListItemMenu = "ListItemMenu";
    const string ViewFields = "ViewFields";
    const string AttributeName = "Name";
 
    XElement root = XElement.Parse(view.GetViewXml());
 
    // Get all columns that use the ECB menu
    IEnumerable<XElement> fields = from el in root.Elements(ViewFields).DescendantNodes().OfType<XElement>()
                                    where el.Attribute(ListItemMenu) != null
                                    select el;
 
    // Remove the ECB Menu from all columns that currently use it.
    foreach (XElement el in fields)
    {
        el.Attributes(ListItemMenu).Remove();
    }
 
    if (internalNames.Count > 0)
    {
        //Get the field specified in the parameters
        fields = from el in root.Elements(ViewFields).DescendantNodes().OfType<XElement>()
                    let nameAttribute = el.Attribute(AttributeName)
                    where nameAttribute != null && internalNames.Any(v => v.Equals(nameAttribute.Value))
                    select el;
 
        // Add the attribute to the columns to show the ECB menu
        foreach (XElement el in fields)
        {
            Console.WriteLine(el);
            var attribute = new XAttribute(ListItemMenu, bool.TrueString);
            el.Add(attribute);
        }
    }
 
    // Update the view
    string viewXml = root.ToString(SaveOptions.DisableFormatting);
    view.SetViewXml(viewXml);
    view.Update();
}

Code should be pretty self explanatory, happy coding! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the maths problem shown below before posting: *

Follow

Get every new post delivered to your Inbox

Join other followers: