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 sharepoint list 'Events' with field Location.

I am trying to add from web existing field with same internal name from other package.

    var fields = contentType.ParentWeb.Fields;

 SPField fieldToAdd = null;
                foreach (SPField field in fields)
                {
                    if (field.Id == fieldId)
                    {
                        fieldToAdd = field;
                        break;
                    }
                }

 contentType.FieldLinks.Add(new SPFieldLink(fieldToAdd));

And i got exception:

A duplicate field name "Location" was found.

When i am adding this fields in sharepoint UI it will be changed to Location0 and will be successfully added!

How to do actually the same in code? I want to add them both and its acceptable to change one internal name to Location0.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

Did not get your code clearly, what is fieldId and how are you getting this fieldId? my guess is location is already there in the content type you can not add the same field again, create a new field if you wish, in that case your code will be (after foreach) -

string fldName = fields.Add(fieldToAdd.Title, fieldToAdd.Type, fieldToAdd.Required);
SPField newField = fields.GetField(fldName);
contentType.FieldLinks.Add(new SPFieldLink(newField));

In this case a new field is created with same display name and same type as fieldToAdd, but with different internal name (you dont have to worry about what the internal name is, system will determine) and add that field to your content type

P.S. - you should consider using break; after fieldToAdd = field;

:)

share|improve this answer
    
This field is stored in web.Fields collection. And i think that i cannot use fields.Add() because field that already added to web.Fields has complex initialization.So it will be better to use exisiting one. –  Evgeny Nov 20 '12 at 7:53
1  
then in that case, i think the field is already added to your content type, that's why you can not add it in the content type again –  Diptarag Nov 20 '12 at 7:59
    
No. I dont have this field. I have default field "Location" (Sharepoint events content type) and my field also has "Location" internal name. So the issue to change it somehow like sharepoint does this when you adding field from UI. –  Evgeny Nov 20 '12 at 8:05
1  
You can not change the internal name of a column, please find the msdn documentation msdn.microsoft.com/en-us/library/… , see it's a get only property no setter is defined, you have to create a new column for your case –  Diptarag Nov 20 '12 at 8:17
add comment

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.