Introduction
Not having found any documentation on how to create a new listing in SharePoint Portal Server during runtime, I decided to publish my findings so that others might also benefit from it.
Background
During a recent redesign of the corporate intranet, we found it necessary to create new lists in SharePoint Portal Server areas that had a consistent structure. Just one problem: the code would fail when trying to submit the new list when calling the Update
.
Some assumptions
- You are familiar with creating webparts in VS.NET
- You have the webpart framework installed and running on your development PC
Using the code
Firstly get a reference to the current area that you want to work with. I assume that it is the current area that the webpart is running in and therefore referencing Context
.
Dim thisWeb As SPWeb = SPControl.GetContextWeb(Context)
Create a reference to the new list that you want to add to the area. The reference has to be a Guid
as SPList
accepts an identifier of this type.
I am assigning the GenericList
template to the list as I want to start with a clean list template. You can assign any of the SPListTemplateType
templates to the list if you want to use a generic list format.
Dim docLibName As String = "New List Name"
Dim guid As System.Guid = thisWeb.Lists.Add(docLibName, _
"A custom list created during runtime.", SPListTemplateType.GenericList)
Add the field that you want to have in the field. First apply the global settings and force an Update
before you add the fields to the list.
Dim newList As SPList = thisWeb.Lists(guid)
With newList
.AnonymousPermMask = SPRights.EmptyMask
.EnableVersioning = True
.OnQuickLaunch = True
.ReadSecurity = 1
.WriteSecurity = 2
.Update()
.Fields.Add("Text field one", SPFieldType.Text, True)
.Fields.Add("Text field two", SPFieldType.Text, False)
.Fields.Add("Boolean field", SPFieldType.Boolean, False)
End With
As far as I can tell, the only field that any template will "force" on the list is the Title
field.
Points of Interest
Do not call Update
again after adding the new fields! If you do call another Update
, then you will receive the following exception on the next Update
:
Save Conflict
Your changes conflict with those made concurrently by another user.
If you want your changes to be applied, click Back in your Web browser,
refresh the page, and resubmit your changes.