Tuesday, March 13, 2012

Create a list, columns and view programmatically


Create a list, columns and view programmatically

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 itsSPListCollection. You have to supply a template for the list, and this depends on the templates available on the site – hence getting the template from theSPListTemplateCollection.
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;
newList.Update();
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;
lkp.Update();
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 ***
newList.DefaultView.ViewFields.Add("NewText");
newList.DefaultView.ViewFields.Add("NewLookup");
newList.DefaultView.Update();
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;
view.ViewFields.Add("NewText");
view.ViewFields.Add("NewLookup");
view.Update();

No comments:

Post a Comment

Building Secure Azure AI Foundry Agents with Managed Identity

  The credential problem nobody wants to own Every team that connects an Azure AI Foundry agent to Microsoft Graph, SharePoint, Outlook, or...