6

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.

2 Answers 2

4

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

1
  • See my edit above. :)
    – GurdeepS
    Commented Apr 22, 2012 at 21:29
1

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

2
  • See my edit above. :)
    – GurdeepS
    Commented Apr 22, 2012 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/… Commented Apr 22, 2012 at 23:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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