When a list is created programmatically using a custom template, the custom fields do not get displayed in the UI. These fields do not become a part of the displayed fields of the default view.
The Problem - A common task like uploading a file to a list that was created programmatically using a custom template.
When you try creating the list using the Object Model, you would most likely get a “Exception Occurred’ error. But still the list would get created but without the custom fields.
On trouble shooting you would find that the while picking up the custom template the schemaXML for the template was not being populated. Theoretically, the schemaXML should have contained the definition for the custom fields. However the schemaXML property would throw a SPException.
This is why the code was throwing the error “Exception occurred”, and even though the list was being created the fields were not being created. The resolution in this case is to modify the schemaXML property to ensure that the fields are created.
The first line of attack is to modify the schemaXML property through string manipulations to get the property set and the list getting rendered properly. This is possible for the SPList object but not for the SPView object (schemaXML is readonly for SPView). By doing this, I was able to get the fields added, but they were still not being displayed.
Modifying the schemaXML to include “Hidden=’false’” or for that matter “Hidden=’FALSE’” did not help.
The solution that did work was as follows
- create a new list using a blank template
- programmatically add the custom fields to the new list
- Update the list to commit the addition of the new fields
- Create a new view based on the default “All Items” view
- Add the same custom fields to the new view
- Delete the original view
- Make the custom view as the new default view
SPSite site = new SPSite("http://localhost/sites/Sergey/default.aspx");
SPWeb web = site.OpenWeb();
SPListCollection coll = web.Lists;
SPListTemplateCollection tmplcoll = web.ListTemplates;
SPListTemplate temp = tmplcoll;
Guid gd = coll.Add("NewList9","NewList9",temp);
string defaultquery = coll[gd].Views.Query;
SPViewCollection viewcoll = coll[gd].Views;
Guid anothergd = coll[gd].Views.ID;
System.Collections.Specialized.StringCollection viewfields = new System.Collections.Specialized.StringCollection();