Sunday, March 17, 2013

List.GetItemById Will Return Item with All Fields


It is a little surprise to me when I saw the List.GetItemById will return a item with all fields populated with data.

using (ClientContext context = new ClientContext(tbUrl.Text))
{
try
{
if (isOffice365)
{
...
}

Web web = context.Site.OpenWebById(currListInfo.WebId);
List list = web.Lists.GetById(currListInfo.ListId);

// GetItemById return item with all fields
ListItem item = list.GetItemById(60);
context.Load(item);
context.ExecuteQuery();

foreach (string fieldName in item.FieldValues.Keys)
{
LogInfo("Field Name = " + fieldName + " Value = " + item.FieldValues[fieldName]);
}
}
catch (Exception expt)
{
LogInfo(expt.Message + expt.StackTrace);
}
On the other hand using GetItems as next code, you have to specify the fields to be returned in the LINQ.

try
{
Web web = context.Site.OpenWebById(currListInfo.WebId);
List list = web.Lists.GetById(currListInfo.ListId);
string queryTxt = "<View><Query><Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">Auto</Value></Contains></Where></Query></View>";
CamlQuery query = new CamlQuery();
query.ViewXml = queryTxt;
ListItemCollection listItems = list.GetItems(query);

context.Load(listItems, items => items.Include(item => item.Id,item => item["Title"], item => item["helloworld"], item => item["myField"]));
context.ExecuteQuery();

foreach (ListItem item in listItems)
{
LogInfo("Item ID = " + item.Id + " Title = " + item["Title"] + " helloworld= " + item["helloworld"] + " myField= " + item["myField"]);}
}
catch (Exception expt)
{
LogInfo(expt.Message + expt.StackTrace);

2 comments:

  1. I don't believe that GetItemById returns all the fields. It doesn't return the ContentType field for example.

    ReplyDelete
  2. From my tests, GetItemById doesn't return any fields. item.FieldValues is empty when calling this code on SharePoint Online.

    ReplyDelete