Next task on my prep – create a list programmatically. Then I want to add some columns to it, and show these on the default view. Actually, it’s mostly pretty easy (apart from that last part).
Well, creating a list is pretty easy.
SPSite siteCol = new SPSite(@"http://vm-moss2007/test/");
SPWeb site = siteCol.OpenWeb();
site.Lists.Add("New Calendar", "This calendar was created programmatically", site.ListTemplates["Calendar"]);
Here you can see me getting an SPWeb object, and then adding to its SPListCollection. You have to supply a template for the list, and this depends on the templates available on the site – hence getting the template from the SPListTemplateCollection.
I wanted a custom list, and I wanted it to appear on the left navigation:
site.Lists.Add("My Custom List", "This list was created programmatically", site.ListTemplates["Custom List"]);
SPList newList = site.Lists["My Custom List"];
newList.OnQuickLaunch = true;
Great! And now I want to add some columns. First I added a text column:
newList.Fields.Add("NewText", SPFieldType.Text, true);
And then a lookup column (as I figured this would be a hard one):
SPList targetList = site.Lists["My Lookup Target"];
SPField targetField = targetList.Fields["My Target Lookup Column"];
newList.Fields.AddLookup("NewLookup", targetList.ID, false);
SPFieldLookup lkp = (SPFieldLookup)newList.Fields["NewLookup"];
lkp.LookupField = targetField.InternalName;
First I get the target list and the target field for the lookup. I add a new lookup column, but for some strange reason none of the SPFieldLookup class’s constructors allow me to create one supplying a target list and column. Also, none of the SPFieldCollection’s methods allow me to add a lookup supplying a target column.
Thus, I end up getting the column I’ve just created and assigning the column that I want use as the value of the lookup. Crazy. I’m sure that there must be a better way of doing this (i.e. in one call) but I don’t see how.
Anyway, it works; my columns are added. Now I want to show them in the default view:
//*** Doesn't work for some obscure reason ***
As the code subtly hints, this code didn’t work – my columns weren’t shown in the default view. However, the code below does work:
SPView view = newList.DefaultView;
The observant amongst you might notice that these pieces of code should be functionally equivalent. Well, they’re not! Daniel Pavelescu has investigated this – but it’s all a bit weird. Anyway, it works!
So there we have it – creating a list, adding new columns to it, and altering a view, all through the SharePoint API.
EDIT – Keith Dahlby has also investigated, and looked at why this is happening. Although he let’s the code talk for itself, the essence of it all is that each call to .DefaultView actually creates a new SPView object!
And he’s right, reflector is very useful.