Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically setting field value for sharepoint listitem

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

like image 798
Dynde Avatar asked Oct 11 '10 06:10

Dynde


3 Answers

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.

like image 67
Rich Bennema Avatar answered Oct 31 '22 03:10

Rich Bennema


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();
like image 45
Shoban Avatar answered Oct 31 '22 04:10

Shoban


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

like image 1
brian brinley Avatar answered Oct 31 '22 05:10

brian brinley