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 need a method where add various Fields in a Sharepoint List, but these Fields must be in the parameter of this method.

Show me this method and how should I use it.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Something like this to get you going perhaps?

 private static void AppendNewFieldToListIfNonExistsent(SPList list, string internalName,
    string displayName, SPFieldType fieldType, Guid? lookupListId = null)
{
    if (list.Fields.ContainsField(internalName)) return;
    if (fieldType == SPFieldType.Lookup)
    {
        list.Fields.AddLookup(internalName, lookupListId.Value, false);
    }
    else
    {
        list.Fields.Add(internalName, fieldType, false);
    }
    var field = list.Fields.GetFieldByInternalName(internalName);
    field.Title = displayName;
    field.Update();
    var view = list.DefaultView;
    if (view.ViewFields.Exists(field.InternalName)) return;
    view.ViewFields.Add(field.InternalName);
    view.Update();
}

MSDN SPFIeldCollection.Add(SPField)
MSDN SPFieldCollection.Add(String, SPFieldType, Boolean)
MSDN SPFieldCollection.AddLookup Method (String,Guid,Boolean)
MSDN SPFieldCollection.AddLookup Method (String,Guid,Guid,Boolean)

share|improve this answer
    
Tks Man!!! But if this method uses a dictionary as a parameter passing the SPFields. –  fbadaro Oct 3 '12 at 20:27
    
Your method? In that case just loop through them. You could add SPField directly, but it's a bit odd I think because of the SPField constructors –  eirikb Oct 3 '12 at 21:08
    
What is the defintion of EnsureLookupEntities? It appears to be a custom method –  vandre Jun 6 at 12:17
    
@vandre I think it was meant as a helper method which would create the field on the lookup list if non-existing, I didn't include the method (with body) as I didn't find it important. Removed for now. Note that lookupListId can be null here, so a Debug.Assert(lookupListId != null, "lookupListId != null"); could be smart to use. Also, one can do switch on fieldType if necessary. (Since I removed EnsureLookupEntities I also removed SPWeb and LookupField, although field could be used to point to specific field) –  eirikb Jun 9 at 17:25

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.