SPFieldLinkCollection.Add method

Adds an SPFieldLink object to the collection.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

public void Add(
	SPFieldLink fieldLink
)

Parameters

fieldLink
Type: Microsoft.SharePoint.SPFieldLink

The field reference to add to the collection. The argument should not be null .

ExceptionCondition
SPException

The value of the Name property of the object that you are adding to the collection duplicates the value of the Name property for an object that already exists in the collection.

-or-

The SPFieldLink object references a field that is out of scope for this content type.

Objects in the collection are indexed by internal name (the value of the SPFieldLink.Name property). If you try to add an object that has the same internal name as an object that already exists in the collection, the method throws an exception. Because the value of the SPFieldLink.Name property is the same as the InternalName property of the SPField object that it references, this restriction effectively ensures that a content type cannot reference the same field twice.

You cannot directly add a field of type SPFieldLookup if it is a secondary lookup (that is, if the IsDependentLookup property returns true). To add secondary lookup fields in a multiple-column lookup, add the primary lookup field (the IsDependentLookup property returns false). All secondary lookup fields that depend on the primary lookup field are added automatically.

The following example shows a method that verifies whether a content type already has a link to a field. If it does not, the method creates a link and adds it to the content type’s collection.

The application that includes this example imports the System and Microsoft.Sharepoint namespaces.

static SPFieldLink LinkToField(SPField field, SPContentType contentType)
{
    // Is the FieldLink in the collection?
    SPFieldLink fieldLink = contentType.FieldLinks[field.Id];
    if (fieldLink == null) // No, so add it.
    {
        fieldLink = new SPFieldLink(field);
        contentType.FieldLinks.Add(fieldLink);
    }
    return fieldLink;
}
Show: