Check if a List Column Exists using SharePoint Client Object Model?
Asked Answered
A

9

8

Using the Client Object Model (C#) in SharePoint 2010, how can I determine if a specified column (field) name exists in a given List?

Thanks, MagicAndi.

Anatomical answered 9/12, 2010 at 17:30 Comment(0)
T
12

Just found this while searching for the same thing, but it looks like Sharepoint 2010 has something built in for this, at least for the Server model: list.Fields.ContainsField("fieldName");

Not sure if it exists for Client side though. Figured it would be a good place to store this information however.

Thorner answered 9/12, 2010 at 17:30 Comment(0)
A
7

Server Object Model

string siteUrl = "http://mysite";
using (SPSite site = new SPSite(siteUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["my forum"];
        for (int i = 0; i < list.Fields.Count; i++)
        {
            if (list.Fields[i].Title == "xyz")
            {
                -
                -
            }
        }
    }
}

Client Object Model

string siteUrl = "http://MyServer/sites/MySiteCollection";
ClientContext clientContext = new ClientContext(siteUrl);
SP.List List = clientContext.Web.Lists.GetByTitle("my forum");
for (int i = 0; i < list.Fields.Count; i++)
{
    if (list.Fields[i].Title == "xyz")
    {
        -
        -
    }
}
Alumna answered 9/12, 2010 at 18:32 Comment(5)
It is server object model in your exampleNekton
their is no much difference in both codes except the client contextAlumna
Ashutosh, you could remove a lot of the boilerplate code above by using a lambda operator to query the fields collection.Anatomical
That client object model code won't work as written as nothing is loaded by context.load() and context.executequery() before its used.Campground
I added a suggested edit in the Server Object Model example to follow MSDN best practices by using / disposing of SPSite and SPWeb objects.Motorcade
S
5

The following method demonstrates how to determine whether a specified column exists in a List using CSOM:

static class FieldCollectionExtensions
{
    public static bool ContainsField(this List list,string fieldName)
    {
        var ctx = list.Context;
        var result = ctx.LoadQuery(list.Fields.Where(f => f.InternalName == fieldName));
        ctx.ExecuteQuery();
        return result.Any();
    }
}

Usage

using(var ctx = new ClientContext(webUrl))
{
    var list = ctx.Web.Lists.GetByTitle(listTitle);
    if(list.ContainsField("Title")){
       //...
    }
}
Shf answered 2/10, 2014 at 21:1 Comment(0)
L
4

Here's an extension code (CSOM) for sharepoint list

    public static bool DoesFieldExist(this List list, ClientContext clientContext, string internalFieldname)
    {
        bool exists = false;

        clientContext.Load(list.Fields, fCol => fCol.Include(
                f => f.InternalName
            ).Where(field => field.InternalName == internalFieldname));
        clientContext.ExecuteQuery();

        if (list.Fields != null && list.Fields.Count > 0)
        {
            exists = true;
        }

        return exists;
    }

usage

List targetList = this.Context.Web.Lists.GetById(<ListID>);
targetList.DoesFieldExist(<ClientContext>, <Field internal Name>)

enjoy :)

Lance answered 29/12, 2015 at 10:10 Comment(0)
A
2

I ended up retrieving the details of the list's fields prior to my operation, and saving them in a generic list of structs (containing details of each field). I then query this (generic) list to see if the current field actually exists in the given (SharePoint) list.

// Retrieve detail sof all fields in specified list
using (ClientContext clientContext = new ClientContext(SharePointSiteUrl))
{
    List list = clientContext.Web.Lists.GetByTitle(listName);
    _listFieldDetails = new List<SPFieldDetails>();

    // get fields name and their types
    ClientObjectPrototype allFields = list.Fields.RetrieveItems();
    allFields.Retrieve( FieldPropertyNames.Title, 
                        FieldPropertyNames.InternalName,
                        FieldPropertyNames.FieldTypeKind,
                        FieldPropertyNames.Id,
                        FieldPropertyNames.ReadOnlyField);
    clientContext.ExecuteQuery();

    foreach (Field field in list.Fields)
    {
        SPFieldDetails fieldDetails = new SPFieldDetails();
        fieldDetails.Title = field.Title;
        fieldDetails.InternalName = field.InternalName;
        fieldDetails.Type = field.FieldTypeKind;
        fieldDetails.ID = field.Id;
        fieldDetails.ReadOnly = field.ReadOnlyField;
        listFieldDetails.Add(fieldDetails);
    }
}

// Check if field name exists
_listFieldDetails.Exists(field => field.Title == fieldName);

 // Struct to hold details of the field
public struct SPFieldDetails
{
    public string Title { get; set; }
    public string InternalName { get; set; }
    public Guid ID { get; set; }
    public FieldType Type { get; set; }
    public bool ReadOnly { get; set; }
}
Anatomical answered 10/12, 2010 at 16:33 Comment(0)
M
2

Some good answers above. I personally used this one:

            List list = ctx.Web.Lists.GetByTitle("Some list");
            FieldCollection fields = list.Fields;
            IEnumerable<Field> fieldsColl = ctx.LoadQuery(fields.Include(f => f.InternalName));
            ctx.ExecuteQuery();

            bool fieldMissing = fieldsColl.Any(f => f.InternalName != "Internal_Name");

You can also use 'Where' after Include method and check if returned collection/field is null. It's about personal preference, because both options are querying on client side.

Most answered 22/7, 2016 at 12:35 Comment(0)
R
0

I prefer the SharePoint Plus Library as it is really clean: http://aymkdn.github.io/SharepointPlus/symbols/%24SP%28%29.list.html

$SP().list("My List").get({
  fields:"Title",
  where:"Author = '[Me]'"
},function getData(row) {
  console.log(row[0].getAttribute("Title"));
});

You could setup a for loop to loop through the row and check if the column you're looking for exists.

Rebbecarebbecca answered 19/11, 2015 at 5:4 Comment(0)
L
0

A cut down and simplified version of Mitya's extension method:

 public static bool FieldExists(this List list, string internalFieldname)
    {
        using (ClientContext clientContext = list.Context as ClientContext)
        {
            clientContext.Load(list.Fields, fCol => fCol.Include(
                    f => f.InternalName
                ).Where(field => field.InternalName == internalFieldname));
            clientContext.ExecuteQuery();

            return (list.Fields != null) && (list.Fields.Count > 0);
        }
    }

There's no need to pass in a separate client context parameter when you can already use the context that comes in with the list.

Lexis answered 10/3, 2019 at 0:8 Comment(0)
C
-2

to much code use this

load Fields first then

 bool exists= clientContext2.Site.RootWeb.Fields.Any(o => o.Id.ToString() == a.Id.ToString());
Curtsey answered 12/10, 2017 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.