Search code examples
c#sitecoreglass-mapper

How do I add an item to a TreelistEx using C#?


I can't seem to find any documentation on this. I have an item, that has a TreelistEx field:

enter image description here

I want to programatically add a new item to this field, preferably using glass mapper but vanilla sitecore will do if needs must.

Can anyone help me out here? How do I go about this?

You'll have to excuse the lack of details, I can't find a single thing to point me in the right direction here.


Solution

  • The TreeList and TreeListEx work the same way as the multilist.

    using (new Sitecore.SecurityModel.SecurityDisabler())
    {
    
        Item newItem = Sitecore.Context.Item;
    
        newItem.Editing.BeginEdit();
    
        MultilistField mlf = newItem.Fields["FieldName"];
    
        // adding an item
        mlf.Add(ItemToAdd.ID.ToString());
    
        // removing an item
        mlf.Remove(ItemToRemove.ID.ToString());
    
        newItem.Editing.EndEdit();
    }