Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Creating a new list in SharePoint Services at runtime

3.64/5 (6 votes)
17 May 20061 min read 1  
How to create a new list in a SharePoint Services area at runtime

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

  1. You are familiar with creating webparts in VS.NET
  2. 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.

VB.NET
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.

VB.NET
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.

VB.NET
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. 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here