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
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.
Could you try this for adding a new field and setting a default value? Untested code. let me know how it goes.
SPFieldText fldName = (SPFieldText)list.Fields.CreateNewField(SPFieldType.Text.ToString(), "mycolumn");
fldName.DefaultValue = "default";
list.Fields.Add(fldName);
list.Update();
I've always found the best route is to get a reference to the list item directly and update specifically, as opposed to using the indexer route. Just like rich's first example mentions.
http://www.sharepointdevwiki.com/display/public/Updating+a+List+Item+programmatically+using+the+object+model
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With