.comment-link {margin-left:.6em;}

kHSw

Wednesday, October 11, 2006

MOSS 2007: Creating readonly colums in a list

I wanted to add a column to a list to store a date based on some heavy business-logic (the calculated column could not be used for this). The end user needs to be able to see the contents of this column, but should not be able to modify it.

Walking through the Sharepoint object model I discovered the CreateNewField Function on the SPFieldCollection in the desired list.
This (at the moment almost undocumented) function needs two parameters:
- typeName As String
- displayName As String
and is returning a SPField.

I had some trouble with the first parameter as it was not clear what exact it was expecting, most of the time the function just throwed a null reference exception (guessing because the errormessage still doesn't exist in the resource file). So I did some investigation with Reflector.
The typeName is expected to be one of the members of
Microsoft.SharePoint.SPFieldType enumeration ("DateTime" in my case).


Dim sps As New Microsoft.SharePoint.SPSite("http://www.vds-computing.com")
Dim spw As Microsoft.SharePoint.SPWeb = sps.OpenWeb("/kHSw")
Dim spl As Microsoft.SharePoint.SPList = spw.Lists("MyList")

Now I was able to create a new field for this list:

Dim spf As Microsoft.SharePoint.SPField = spl.Fields.CreateNewField("DateTime", "Test")

The only thing left is setting some parameters...

spf.ShowInDisplayForm = True
spf.ShowInEditForm = False
spf.ShowInNewForm = False
spf.ShowInVersionHistory = True
spf.ShowInViewForms = True
spf.AllowDeletion = False


(I just discovered that setting a column hidden will remove the ability to delete it via code)

...and to add the new column to the list

spl.Fields.Add(spf)


I created a Windows Service that calculates the date for new listitems, and a simple workflow is taking care of the rest...

3 Comments:

  • thank you soo much - awesome approach!!!!

    By Anonymous Anonymous, at 11:00 PM  

  • This newly created list will not show newly added fields in Site. To show the fields do following:
    SPView myView = list.DefaultView;
    myView.ViewFields.Add(fieldName);
    myView.Update();

    Thank You.

    By Blogger サンタ, at 3:07 AM  

  • Liked the blog. However, how do I create Site Columns for the the Site collection but with same properties you have identified in your blog...

    By Anonymous Mota Landh Chod, at 9:32 PM  

Post a Comment

Links to this post:

Create a Link

<< Home


 
Stefanie Worm is het liefste vrouwtje van de wereld.
Melina is de liefste schatsie van de wereld (Erik De Maeyer).