Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

SPFieldCollection class

Represents a collection of SPField objects.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
[SubsetCallableTypeAttribute]
[ClientCallableTypeAttribute(Name = "FieldCollection", CollectionChildItemType = typeof(SPField), 
	CollectionIndexerMethodClientName = "GetById", CollectionCreateEntityMethodClientName = "Create", 
	ServerTypeId = "{D449D756-E113-4d27-A5E7-609CBC3EBA7E}", SampleUrl = "{apiroot}/web/lists({listid})/fields")]
public class SPFieldCollection : SPBaseCollection

Use the Fields property of either the SPList class or the SPListItem class to return the collection of fields for a list or list item. Use the Fields property of the SPWeb class to return the fields in the website, and use the Fields property of the SPContentType class to get the fields that are associated with the content type. To create a field, use the Add method.

Use an indexer to return a single field from the collection. For example, assuming the collection has been assigned to a variable named collFields, use collFields[index] in C#, or collFields(index) in Visual Basic, where index is either the index number of the field in the collection or the display name of the field.

The following code example adds a new text field to the Announcements list of a specified website that is displayed in the default view of the list.

using (SPWeb oWebsite = SPContext.Current.Site.AllWebs["MySite"])
{
    SPList oList = oWebsite.GetList("Lists/Announcements/AllItems.aspx");
    SPFieldCollection collFields = oList.Fields;

    string strNewFieldName = collFields.Add("MyNewField", SPFieldType.Text, false);
    SPField oField = collFields.GetField(strNewFieldName);

    SPView oView = oList.DefaultView;
    SPViewFieldCollection collViewFields = oView.ViewFields;
    collViewFields.Add(oField);
    oView.Update();
}
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.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.