Wednesday, 30 January 2013

Getting Column Names (List) from SharePoint 2010 using Client Object Model (C#)



Step 1: Create New Project. (Minimum .NET Framework 3.5)
Step 2: Add “Microsoft.SharePoint.Client” and “Microsoft.SharePoint.Client.Runtime” namespaces.
Step 3: Write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//SharePoint namespaces
using Microsoft.SharePoint.Client;

namespace GettingFields
{
    class Program
    {
        static void Main(string[] args)
        {
            string siteUrl = "http://sharepointserver.com";
            ClientContext clientContext = new ClientContext(siteUrl);
            clientContext.Credentials = new System.Net.NetworkCredential("admin", "password", "sharepointserver.com");
            Web site = clientContext.Web;

            //Getting List
            List list = site.Lists.GetByTitle("Students");
            clientContext.Load(list);
            clientContext.ExecuteQuery();

            //Getting Column Names
            FieldCollection fieldCollection = list.Fields;
            clientContext.Load(fieldCollection);
            clientContext.ExecuteQuery();

            //Printing Column Names
            foreach (Field field in fieldCollection)
            {
                Console.WriteLine("Name: " + field.InternalName.ToString());
            }
            Console.ReadLine();
        }
    }
}


4 comments:

  1. I have created two columns for custom list.
    eg: Internal , External.

    Add few items to above list.

    Now I want to get only the above two columns (Internal,External , with their ID's) so that I can display in a dropdownlist. Now when ever I select a item (eg:Internal) It should display all the items in those columns.

    Problem: Am getting lots of columns , so how to
    simplyfy it..



    ReplyDelete
    Replies
    1. By default SharePoint creates a lot of columns to a List.
      To get the only Internal, External columns and their Id's.
      Please try the below code. Hope this helps.

      foreach (Field field in fieldCollection)
      {
      if (field.InternalName.ToString() == "Internal" || field.InternalName.ToString() == "External")
      {
      Console.WriteLine("Id = "+field.Id.ToString()+"\nName = "+field.InternalName.ToString());
      }
      }

      Delete
    2. You can exclude using
      if (!field.Hidden)

      Delete
  2. How to get specific fileds name?

    ReplyDelete