Programmatically set field value for sharepoint listitem

I am trying to simply add plain text or a hyperlink to a list item in sharepoint 2007.

I can add the field without problems:

list.Fields.Add("MyField",SPFieldType.Text, false); 

And it shows up on my lists. However, no matter how I try, I cannot programmatically set the value for the field. I tried:

 list.items[0]["MyField"] = "text"; 

and I tried loading in the field:

 SPField field = list.items[0].Fields["MyField"]; 

and setting it there, and setting the default and updating, but nothing like that happens.

I always end my code blocks with list.update (); or if I myself work on the item.update () element; so I at least miss this one. Can someone tell me what I am doing wrong?

thanks

+7
c # sharepoint sharepoint-2007
source share
4 answers

Try:

 SPListItem item = list.items[0]; item["MyField"] = "text"; item.Update(); 

Although this seems equivalent, the code above does not match:

 list.items[0]["MyField"] = "text"; list.items[0].Update(); 

For more information, see here and here for people who have documented the same behavior.

+10
source share

Could you try this to add a new field and set a default? Unused code. let me know how this happens.

 SPFieldText fldName = (SPFieldText)list.Fields.CreateNewField(SPFieldType.Text.ToString(), "mycolumn"); fldName.DefaultValue = "default"; list.Fields.Add(fldName); list.Update(); 
+3
source share

I always found that the best route is to get a link to the list item directly and specifically update, as opposed to using the indexer route. Just as the rich first example is mentioned.

http://www.sharepointdevwiki.com/display/public/Updating+a+List+Item+programmatically+using+the+object+model

+1
source share

From the whole discussion above, it seems that you are trying to set the value of a field in a list event handler, and you are setting a value in the event of adding an item or update item. If so, you need to consider AfterProperties. Remember that we have * ing and * ed events, and in the case of events, we must work with BeforeProperties and AfterProperties.

Hope this helps!

0
source share

All Articles