Search code examples
c#sharepointsharepoint-2010web-partssplist

How to know the name of the fields of a list that is empty?


In a Sharepoint there is a SPList that I should check if a name of field exist. (If exist I add content, if not exist I do something else)

Now I'm doing that:

SPListItemCollection listItems = spList.GetItems();
SPFieldCollection spFieldCollection =listItems.Fields;
foreach (SPField field in spFieldCollection)
 {
     String name = field.Title;

     if (name == "nameField") {
         return true; // Exist
     }
 }

that works ok, except if the list is empty. How can I check if a name of the field exist before add content to the list?


Solution

  • Just check on the Fields property on the SPList:

    SPFieldCollection fields = spList.Fields;
    

    Use the method ContainsField to check if a field exists:

    return spList.Fields.ContainsField(fieldName);
    

    fieldName Type: System.String A string that contains either the display name or the internal name of the field.

    SPFieldCollection.ContainsField Method