Problem adding field to a custom list type in SharePoint

2.4k views Asked by At

I have defined a custom list template type for SharePoint. I install it using VSeWSS 1.3 and everything seems to behave correctly.

I have added a custom action which will add additional columns (SPFields) to the list. However, every time that code executes it throws and ArgumentException with a 'Value not in the expected range.' error message. This behavior seems to be specific to custom types as suggested in this blog post.

Here is the relevant code (thisList is an instance of my custom list template type created using the browser interace) that tries to add a field to the SPFieldCollection of thisList:

                SPFieldType fieldType = Format2SPFieldType(format);
                SPField field = new SPField(thisList.Fields, fieldType.ToString(), fieldName);
                thisList.Fields.Add(field);

The last statement (thisList.Fields.Add(field)) throws the following exception:

   Message  "Value does not fall within the expected range."

   at Microsoft.SharePoint.SPFieldCollection.GetFieldByInternalName(String strName, Boolean bThrowException)
   at Microsoft.SharePoint.SPFieldCollection.GetFieldByInternalName(String strName)
   at Microsoft.SharePoint.SPFieldCollection.AddFieldAsXmlInternal(String schemaXml, Boolean addToDefaultView, SPAddFieldOptions op)
   at Microsoft.SharePoint.SPFieldCollection.AddFieldAsXml(String schemaXml, Boolean addToDefaultView, SPAddFieldOptions op)
   at Microsoft.SharePoint.SPFieldCollection.Add(SPField field)

This same code executes just fine if the SPList item is the base list type (built-in custom list).

Are there any fields that need to be set explicitly in the CAML and using the AddFieldAsXml() method directly to make this code work with custom list template types?

Update: I should also mention that the fields are actually created in some instances even though the call throws an exception!

2

There are 2 answers

0
Philipp Schmid On BEST ANSWER

Turns out that this was caused because calling thisList.SchemaXML put the SPList object into a state that I wasn't able to recover from! Getting a new reference to the same SharePoint List, e.g., SPList newList=thisList.ParentWeb.Lists[thisList.ID] solved the issue!

1
Kusek On

What is the Type of Field you are trying to add? is that an Internal field or a Custom Field type, what does this Function Format2SPFieldType return? If it is a Inbuilt field can you try adding with the

thisList.Fields.Add("DisplayName", SPFieldType.Integer, false);