If you’re like me and you do a fair bit of object model programming, you’ve likely seen this error before. More specifically, the error is as follows:
Unhandled Exception: Microsoft.SharePoint.SPException: Invalid data has been used to update the list item. The field you are trying to update may be read only.
There are probably more than one cause for this particular issue, but in my case, it always comes down to an error in the way I’ve assigned a field of type Lookup.
So to set up our scenario, let’s say we have a custom list called Types, and it contains 3 items:
Now let’s assume we’ve created a custom list called Users and it contains a column called User Type of type Lookup that points to the Types list using the Title column.
If we’re doing some updates to our list programmatically, we’ll need to be able to set the Type column. Your typical scenario is that you’re reading this from a form control and populating this field. In my case, I knew specifically what value I wanted to set. So let’s start with something like this:
1 2 3
SPListItem item = list.Items.Add(); item["Type"] = "Employee"; item.Update();
Unfortunately, the above bit of code will fail with the error outlined at the beginning of this post. The data we’re attempting to assign is not valid. What we need to do is create another object, an SPFieldLookupValue object to be more specific, and use one of the constructors to build the lookup that we’ll then assign to our field.
1 2 3 4
SPListItem item = list.Items.Add(); SPFieldLookupValue lookup = new SPFieldLookupValue(1, "Employee"); item["Type"] = lookup; item.Update();
I’m not satisfied with the above, because it’s forcing me to hard code the id and the value. I am interested in some feedback from my readers — does anyone have a better approach to this problem? I’ll be awarding a free Black Ninja TSHIRT to the reader who can provide me the most elegant workaround.