Disclaimer

The views expressed on this weblog are mine alone and do not necessarily reflect the views of my employer, Avanade.

Search
Recomends...
  • Code Complete, Second Edition
    Code Complete, Second Edition
    by Steve McConnell
Login
« Overcoming the limitations of the SharePoint Solution Generator | Main | Customizing the Quick Launch menu with SPNavigationNode, SPNavigationNodeCollection and Audiences »
Tuesday
09Oct2007

Maping from SPList Field Types to .Net Types

When I am working with the WSS Object model, I generally do not pass references to SharePoint objects around. I usually create business objects to represent the lists that I am accessing. I will then use an Adapter pattern to map from th SharePoint object model to the custom business objects.

In the adapter class, you will need to extract data from fields/columns of the SPListItem. Depending on the types of columns you have, extracting that data is not as straight forward as you may expect. I've begun to build up a nice utility library for converting some of these field types. I thought it may be helpful to share some of it's functions.

The simplest column type is a text field. Getting data from such a field is pretty straight forward, except for the fact that if you leave the column empty during data entry, it actually ends up being stored as null. Instead of checking for null every time you need to map this type of field (which is very often), consider abstracting the logic out like I have:

        public static string GetStringField(SPListItem item, string key)
        {
            if (item[key] != null)
            {
                return item[key].ToString();
            }
            return "";
        }

Another common field type is the multi line text fields. These fields can store rich text or even html. Here are a couple of functions that will get the contents of the filed as HTML and as plain text.

        public static string GetMultiLineTextAsHTML(SPListItem item, string key)
        {

            SPFieldMultiLineText field = item.Fields[key] as SPFieldMultiLineText;
            if (field != null)
            {
                return field.GetFieldValueAsHtml(item[key]);
            }

            return "";
        }

        public static string GetMultiLineTextAsPlainText(SPListItem item, string key)
        {

            SPFieldMultiLineText field = item.Fields[key] as SPFieldMultiLineText;
            if (field != null)
            {
                return field.GetFieldValueAsText(item[key]);
            }

            return "";
        }

One of the more powerful column types is People and Groups. Getting the underlying SPUser, SPGroup or collection of SPUsers and SPGroups can be challenging. Check out these functions that make it easier.

        public static SPUser GetSPUser(SPListItem item, string key)
        {
            SPFieldUser field = item.Fields[key] as SPFieldUser;

            if (field != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    return fieldValue.User;
                }
            }
            return null;
        }

        public static SPGroup GetSPGroup(SPListItem item, string key)
        {
            SPFieldUser field = item.Fields[key] as SPFieldUser;
            if (field != null)
            {
                SPFieldUserValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldUserValue;
                if (fieldValue != null)
                {
                    string groupName = fieldValue.LookupValue;
                    return item.Web.SiteGroups[groupName];
                }
            }
            return null;
        }


        public static List<SPUser> GetSPUserCollection(SPListItem item, string key)
        {
            SPFieldUserValueCollection fieldValues = item[key] as SPFieldUserValueCollection;
            if (fieldValues != null)
            {
                List<SPUser> users = new List<SPUser>();
                foreach (SPFieldUserValue value in fieldValues)
                {
                    users.Add(value.User);
                }
                return users;
            }

            return null;
        }

Here is another function that will return the url to a file that is attached to a List Item. This also works for getting the url to images in a image library/picture gallery.

public static string GetItemAttachmentUrl(SPListItem item)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(SPEncode.UrlEncodeAsUrl(item.Web.Url));
            sb.Append(@"/");
            sb.Append(SPEncode.UrlEncodeAsUrl(item.ParentList.RootFolder.Url));
            sb.Append(@"/");
            sb.Append(item.File.Name);
            return sb.ToString();
        }

Lastly I'll share a usefully little function that will return the value of a Lookup Column as a SPListItem object.

        public static SPListItem GetListItemFromLookup(SPListItem item, string lookupTableName, string key)
        {
            SPFieldLookup field = item.Fields[key] as SPFieldLookup;
            if (field != null)
            {
                SPFieldLookupValue fieldValue = field.GetFieldValue(item[key].ToString()) as SPFieldLookupValue;
                if (fieldValue != null)
                {
                    return item.Web.Lists[lookupTableName].GetItemById(fieldValue.LookupId);
                }
            }
            return null;
        }

I hope you find these useful. I do.

Happy Coding.

PrintView Printer Friendly Version

EmailEmail Article to Friend

References (1)

References allow you to track sources for this article, as well as articles that were written in response to this article.
  • Response
    If you are doing a fair amount of programmatic access to SharePoint lists, you will quickly find there

Reader Comments (9)

this was exactly what I was looking for, can't thank you enough!
February 7, 2008 | Unregistered Commentergabouy
Great work, thx a lot!
March 27, 2008 | Unregistered CommenterFred
What does key stands for????
October 8, 2008 | Unregistered CommenterReks
I am stuck in "How can I get the list of all the users having permission on SPfolder in a list?". If you can help me out... Please respond.

Thanks in advance
October 8, 2008 | Unregistered CommenterReks
key is the column name on the list you want to get the value for.
October 8, 2008 | Registered CommenterDavid San Filippo
Hi David,

Is there a way I can get the list of all the users/group for a subfolder inside a Spfolder which is created in a document library.

Thanks for help in advance.
Reks
October 9, 2008 | Unregistered CommenterReks
Many thanks for the great functions i was looking to find the users collection from the person or group type and couldn't get good examples the function you have mentioned above are great and helped me out from the loop. great work.
October 9, 2008 | Unregistered CommenterSK
Excellent !!!!!!!!!!!!!!!!!!!
May 13, 2009 | Unregistered CommenterMM
Great Post.. helped me a lot.. thank you
January 22, 2010 | Unregistered CommenterRavi

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
All HTML will be escaped. Hyperlinks will be created for URLs automatically.