7

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

Dynde
  • 2,592
  • 4
  • 33
  • 56

4 Answers4

10

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.

Rich Bennema
  • 10,295
  • 4
  • 37
  • 58
  • 1
    Why on earth would they mess up the indexers so bad? :/ – Dynde Oct 12 '10 at 05:49
  • @Dynde They don't. This is no different than if a value type was returned and modified. It's just that a *new* object is returned. –  Nov 29 '12 at 00:19
3

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();
Shoban
  • 22,920
  • 8
  • 63
  • 107
1

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

brian brinley
  • 2,364
  • 1
  • 13
  • 10
0

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!

Azher Iqbal
  • 547
  • 2
  • 4
  • 13