Skip to main content

Cloud

SharePoint developers be aware: setting SPListItem column to null reverts the column value

I wanted to share an unexpected Share Point behavior that could be dangerous if you don’t know about it. It could potentially be useful if you are aware of it (although one must be very careful using it).
When working with SPLIstItem, if you set a column it to null in SPLIstItem, the in-memory column value reverts to the last updated value for that column even if you already changed it in memory to something else multiple times. When you finally do the Update() on SPListItem it sets that column to null. Not what you would expect.
Check out the code below with comments:

SPList list = web.Lists["Test"];

SPListItem item = list.Items[0];

item["Title"] = "ABC";
//item["Title"] is set "ABC" as expected

item.Update();
//item["Title"] continues to be "ABC" as expected

item["Title"] = "CBS";
//item["Title"] is set " CBS" as expected

item["Title"] = null;
//item["Title"] reverts back to "ABC" while you would expect it to be null (!)

item["Title"] = "NBC";
//item["Title"] is set to "NBC" as expected

item["Title"] = null;
//item["Title"] reverts back to "ABC" again while you would expect it to be null (!)

item.Update();
//item["Title"] is finally set to null, data in the database is set to null as well (!)

//Go figure!!!

I have tested it on several different types of columns with them being Required or not Required, I consistently got this behavior.
This is certainly something to keep in mind when working with Lists in SharePoint.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

PointBridge Blogs

More from this Author

Follow Us