1 out of 1 rated this helpful - Rate this topic

SPFieldCollection.Add Method (String, SPFieldType, Boolean)

Creates a field in the collection based on the specified display name, field type, and Boolean value.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online
public string Add(
	string strDisplayName,
	SPFieldType type,
	bool bRequired
)

Parameters

strDisplayName
Type: System.String
A string that specifies the display name of the field.
type
Type: Microsoft.SharePoint.SPFieldType
A SPFieldType value that specifies the type of field to create.
bRequired
Type: System.Boolean
true if the field is required to contain a value; otherwise, false.

Return Value

Type: System.String
A string that contains the internal name of the new field.

The Add method cannot be used to create a field of type Lookup, because this causes an SPException to be thrown. Instead use the AddLookup method to add a field of this type.

The following code example adds a required text field to the specified list.

using (SPWeb oWebsite = SPContext.Current.Site.AllWebs["MySite"])
{
    SPFieldCollection collFields = oWebsite.Lists["MyList"].Fields;
    collFields.Add("MyField", Microsoft.SharePoint.SPFieldType.Text, 
        true);
}
NoteNote

Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Disposing Objects.

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Adding site columns to the site
In case of adding site column at site level use the following: $0$0 $0 $0web.Fields.Add(columnName, SPFieldType, true);$0 $0$0 $0 $0Where "web" is your SPWeb object.$0