Programmatically setting field value for sharepoint listitem
Asked Answered
F

4

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

Fledgling answered 11/10, 2010 at 6:44 Comment(1)
Are ContentTypes enabled in the list?Frere
E
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.

Elnaelnar answered 11/10, 2010 at 14:11 Comment(2)
Why on earth would they mess up the indexers so bad? :/Fledgling
@Fledgling 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.Nath
C
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();
Castillo answered 11/10, 2010 at 7:28 Comment(0)
E
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

Egide answered 11/10, 2010 at 18:26 Comment(0)
I
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!

Ilse answered 14/10, 2010 at 16:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.