Saturday, 19 January 2013

"Invalid data has been used to update the list item. The field you are trying to update may be read only" error while updating list item.


When working with SharePoint object model  normally you encounter this error when you are trying to update a list item programmatically for a lookup or a people picker type field.
Below I have described how we should go ahead to update listitems for these two types so as to avoid the error.

Lookup Type Field Column

public static SPFieldLookupValue GetLookupFieldFromValue(string lookupValue,string lookupSourceColumn, SPList lookupSourceList)
       
            {

                    SPFieldLookupValue value = null;
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><Eq><FieldRef Name='" + lookupSourceColumn + "'/><Value Type='Text'>" + lookupValue +  "</Value></Eq></Where>";
                   
                    SPListItemCollection listItems = lookupSourceList.GetItems(query);
                    if(listItems.Count > 0 )
                        value = new SPFieldLookupValue(listItems[0].ID,lookupValue);
                    return value;
            }

lookupValue : Value you want to assign to your item.
lookupSourceColumn : Column name from the source list that you are using as a lookup
lookupSourceList : Name of the source list which is having the column that acts as a datasource for the lookup type column

Now simply refer to the above method and use it to assign it to your list item of lookup type.

item["LookupField"] = GetLookupFieldFromValue(lookupfieldValue, lookupSourceColumn, listName);


People/User Type Field Column

SPUser user = web.EnsureUser(loginName);
                 
item["UserTypeFieldName"] = user;

Updating in this manner will wipe out the fear of lookups and people picker fields. Enjoy Coding :)

Regards,
Geetanjali

2 comments:

  1. Very good article. I am almost reading all ur articles.

    http://www.enjoysharepoint.com

    ReplyDelete
  2. What about when the User is a group? EnsureUser doesn't work for a SharePoint group, it throws an exception. Any thoughts?

    ReplyDelete