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
Syntax
'Declaration
Public Function Add ( _
strDisplayName As String, _
type As SPFieldType, _
bRequired As Boolean _
) As String
'Usage
Dim instance As SPFieldCollection
Dim strDisplayName As String
Dim type As SPFieldType
Dim bRequired As Boolean
Dim returnValue As String
returnValue = instance.Add(strDisplayName, _
type, bRequired)
public string Add(
string strDisplayName,
SPFieldType type,
bool bRequired
)
Parameters
strDisplayName
Type: System.StringA string that specifies the display name of the field.
type
Type: Microsoft.SharePoint.SPFieldTypeA SPFieldType value that specifies the type of field to create.
bRequired
Type: System.Booleantrue 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.
Remarks
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.
Examples
The following code example adds a required text field to the specified list.
Dim webSite As SPWeb = SPContext.Current.Site.AllWebs("MySite")
Try
Dim fields As SPFieldCollection = webSite.Lists("MyList").Fields
fields.Add("MyField", Microsoft.SharePoint.SPFieldType.Text, True)
Finally
webSite.Dispose()
End Try
using (SPWeb oWebsite = SPContext.Current.Site.AllWebs["MySite"])
{
SPFieldCollection collFields = oWebsite.Lists["MyList"].Fields;
collFields.Add("MyField", Microsoft.SharePoint.SPFieldType.Text,
true);
}
Note
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.