Programmatically setting field value for sharepoint listitem
I'm trying to simply add a simple text or hyperlink field to a list item in share开发者_Go百科point 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
From all the discussion above it appears that you are trying to set the field value in a list event handler and you are setting the value in item adding or item updating event. If this is the case then you need to consider AfterProperties. Remember we have *ing and *ed events and in case of *ing events we need to work with BeforeProperties and AfterProperties.
I hope this helps!
精彩评论