If you want to modify the DefaultView of a programmatically created list you have to know a “bagatelle”.
First i tried it this way:
list.DefaultView.ViewFields.Add(list.fields.GetFieldByInternalName(“internalName”);
list.DefaultView.Update();
and nothing happened at all.
The reason lies in the property DefaultView which encapsulates a behavior in which in every call the View is instantiated again. So in the first line you would modifiy the first instance of the view. Than, you would update a new instance of the View, which is not modified or updated.
So, knowing this, what you have to do to make it working is the following:
Get the Instance, modifiy it, and safe it.
SPView view = list.DefaultView;
if(view.ViewFields.Exists("internalName")==false)
view.ViewFields.Add(list.Fields.GetFieldByInternalName("internalName"));
view.Update();
Get All ContentTypes of the List.
List<SPContentType> ctl = new List<SPContentType>();
SPContentTypeCollection collection = list.ContentTypes;
Iterate over all ContentTypes of the List and compare your CustomContentType with all existing ContentTypes of the List. Compare the Name, not the ID.
Your CustomContentType has to be added to the List programmatically first.
Add the found/calculated ContentType to the List<SPContentType> ctl.
This is necassary in this manner, because after adding the ContentType to the List it gets a ID Appendix which you have to calculate first.
So if you would add your Custom ContentType directly to the List<SPContentType> ctl, it wouldn`t work, because exactly that ContentType is not existent at the SPList. When you add the ContentType to the SPList, it derives and has it`s own ID. So you first have to calculate the exact existent ContenType.
The complete Method looks like this:
private static void SetDefaultContentType(SPContentType CustomContentType, SPList list)
{
try
{
List<SPContentType> ctl = new List<SPContentType>();
SPContentTypeCollection collection = list.ContentTypes;
foreach (SPContentType ct in collection)
{
if (ct.Name.Contains(CustomContentType.Name))
{
ctl.Add(ct);
}
}
list.RootFolder.UniqueContentTypeOrder = ctl;
list.RootFolder.Update();
}
catch { }
}