SPFieldLinkCollection.Add Method

Adds an SPFieldLink object to the collection.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online

Syntax

'Declaration
Public Sub Add ( _
    fieldLink As SPFieldLink _
)
'Usage
Dim instance As SPFieldLinkCollection
Dim fieldLink As SPFieldLink

instance.Add(fieldLink)
public void Add(
    SPFieldLink fieldLink
)

Parameters

Exceptions

Exception Condition
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.

Remarks

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.

Examples

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.

Function LinkToField(ByRef field As SPField, ByRef contentType As SPContentType) As SPFieldLink
    ' Is the FieldLink in the collection?
    Dim fieldLink As SPFieldLink = contentType.FieldLinks(field.Id)
    If fieldLink Is Nothing Then ' No, so add it.
        fieldLink = New SPFieldLink(field)
        contentType.FieldLinks.Add(fieldLink)
    End If
    Return fieldLink
End Function
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;
}

See Also

Reference

SPFieldLinkCollection Class

SPFieldLinkCollection Members

Microsoft.SharePoint Namespace

SPFieldLink

SPContentType

Other Resources

Fields and Field References

Introduction to Columns