Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have the code below and up the fld.Update() line, it crashes saying

This functionality is unavailable for field collections not associated with a list

The string values I provided are fine.

             SPContentType ctype = list.ContentTypes["x"];
                    SPField fld = ctype.Fields.GetField("x");

                    if (!list.Fields.ContainsField("x"))
                    {

                        list.Fields.Add(fld);
                    }

                    fld.ShowInDisplayForm = true;
                    fld.ShowInEditForm = true;
                    fld.ShowInNewForm = true;
                    fld.Update();

                    ctype.Update();

How should this code be written?

EDIT: What I am trying to do is add a field from a content type (All the doc libs use the content type), display that field in the document library's view form (recursively, so within folders etc), and then copy text from one field to another.

share|improve this question

2 Answers 2

You actually being mixing retrieving a field from a Content Type and trying to add it to the List. As Bjorn said above, if you plan to add it to a Content Type you use Field Links, such as (excerpt from a function)

if (((contentType != null) && (field != null)) && (contentType.FieldLinks[field.Id] == null)) { contentType.FieldLinks.Add(new SPFieldLink(field)); contentType.Update(pushToChildren, false); }

If you use it on the list, you need first to retrieve the Field from the collection of the Site and than add it to your LIST using List.Fields.Add

share|improve this answer
    
See my edit above. :) –  gss11 Apr 22 '12 at 21:29
    
Ok, than it seems your target is other! You need not to add to the list, because it is already there (belonging to the CT)!. You need either to Update fields definition at the CT level (and push down to children) or get update simply the view, see here devcow.com/blogs/jdattis/archive/2007/03/28/… –  C. Marius - MVP Apr 22 '12 at 23:07

gss,

I'm extremely interested in understanding what you think you are doing here, but I'll answer your question first: Content types have field links, not fields, so try working with the field links collection instead.

.b

EDIT: Based on your refined question, what you want to do is something along the lines of (pseudo-code):

foreach (SPView view in list.Views) { view.ViewFields.Add(fieldname); }

You do not need to add the field to the list if the content type is already attached to the list.

.b

share|improve this answer
    
See my edit above. :) –  gss11 Apr 22 '12 at 21:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.