Programmatically setting field value for sharepoint listitem

Dynde picture Dynde · Oct 11, 2010 · Viewed 42.3k times · Source

I'm trying to simply add a simple text or hyperlink field to a list item in sharepoint 2007.

I can add the field no problem:

list.Fields.Add("MyField",SPFieldType.Text, false);

And it shows up fine on my list items. However no matter which way I try, I can't programmatically set a value for the field. I tried:

list.items[0]["MyField"] = "text";

and I tried loading into a field:

SPField field = list.items[0].Fields["MyField"];

and setting it there, and setting the default value and updating, but nothing what so ever happens.

I always finish my code blocks with list.update(); or if I'm operating on the item itself item.update(); so I'm not at least missing that. Can anyone tell me what I'm doing wrong?

Thanks

Answer

Rich Bennema picture Rich Bennema · Oct 11, 2010

Try:

SPListItem item = list.items[0];
item["MyField"] = "text";
item.Update();

Although it seems equivalent, the above code is not the same as:

list.items[0]["MyField"] = "text";
list.items[0].Update();

For more information, see here and here for people who have documented the same behavior.