Question

I am from PHP, and I don't think I am understanding how to walk through data structures properly. The documentation for SPFieldCollection.Add is pretty clear what kind of arguments it takes, so I wrote a class that does:

namespace SPAPI.Lists.Add
{
    class AddParams
    {
        public SPFieldType type { get; set; }
        public bool required { get; set; }
    }
}

From there I created a list that does:

public Create(SPFeatureReceiverProperties properties, Dictionary<string, List<AddParams>> columns, string name, string description, SPListTemplateType type)
{
    SPSite siteCollection = properties.Feature.Parent as SPSite;
    if (siteCollection != null)
    {
        SPWeb web = siteCollection.RootWeb;
        web.Lists.Add(name, description, type);
        web.Update();

        // Add the new list and the new content.
        SPList spList = web.Lists[name];
        foreach(KeyValuePair<string, List<AddParams>> col in columns){
            spList.Fields.Add(col.Key, col.Value[0], col.Value[1]);
        }

        // More Code ...
    }
}

The problem is, it doesn't like col.Value[0], col.Value[1] because one is not a SPFieldType and the other isn't a boolean by strict definition. I think I have the right Idea, but I am looking for guidance on how to make this work.

Because C# has type hinting I assumed that it would use the AddParams class to see the types.

The idea is to pass in a series of params and create a new list based on those params.

This is more of a C# question and data structure iteration question then a SP development question.

Was it helpful?

Solution 2

Change

spList.Fields.Add(col.Key, col.Value[0], col.Value[1]);

to

spList.Fields.Add(col.Key, col.Value[0].type, col.Value[0].required);

OTHER TIPS

Both col.Value[0] and col.Value[1] are of AddParams type. This will probably compile:

spList.Fields.Add(col.Key, col.Value[0].type, col.Value[0].required);

but you likely need another foreach inside your foreach:

foreach(AddParams item in col.Value)
{
}

Why do you have list of AddParams? Are you expecting more than 1 FieldType for the same field?

I think you should implement it this way:

public Create(SPFeatureReceiverProperties properties, Dictionary<string, AddParams> columns, string name, string description, SPListTemplateType type)
{
    SPSite siteCollection = properties.Feature.Parent as SPSite;
    if (siteCollection != null)
    {
        SPWeb web = siteCollection.RootWeb;
        web.Lists.Add(name, description, type);
        web.Update();

        // Add the new list and the new content.
        SPList spList = web.Lists[name];
        foreach(string key in columns.Keys){
            spList.Fields.Add(key, columns[key].type, columns[key].required);
        }

        // More Code ...
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top