in

Corey Roth and Friends Blogs

Group site for developer blogs dealing with (usually) Ionic, .NET, SharePoint, Office 365, Mobile Development, and other Microsoft products, as well as some discussion of general programming related concepts.

Kyle Kelin on .Net

Wrapping a SharePoint Choice Column with a C# Enum

 

One thing I like to do in my SharePoint code is wrap the SharePoint Object Model code when I access a particular value in a Sharepoint list item. I do this so I can pretend like I'm not working with the SharePoint Object Model. :) I had a couple of choice columns that were represented as Enums in my code base this week. I wanted to share what that code looks like in case someone else might find it useful.

 

The first method GetEnumValue is the method I am calling from my Data Access Layer (could be from the user control if you have fewer layers. The method takes the SharePoint listitem and the name of the column. I used generics in this method to make it more flexible so that it would take any Enum type so I wouldn't have to write a method for each Enum.

 

 

public static T GetEnumValue<T>(SPListItem result, string columnName)

{

string value = (GetItemValue(result, columnName));

return (T)Enum.Parse(typeof(T), value);

}

 

In the above method I used the method called GetItem. I use this little utility method to retrieve the value from the list item column

 

public static String GetItemValue(SPListItem listItem, string columnName)

{

string value = string.Empty;

 

try

{

var itemValue = listItem[columnName];

if (itemValue != null)

value = itemValue.ToString();

}

// catch ommitted for this examples

return value;

}

 

 

Here is how you would use the above GetEnumValue method. The Enum type is DocumentType and the column in SharePoint is also named DocumentType. Now you will need to wrap this line in your code that will access the list item. I will let you google that. There are plenty of posts on that.

documentType = Utilities.GetEnumValue<DocumentType>(listItem,"DocumentType");

 

Nothing earth shattering here but I found it useful and cleans up my code a litle bit.

Published Mar 11 2009, 10:17 PM by KyleKelin
Filed under:

Comments

No Comments

Leave a Comment

(required)
(optional)
(required)
Add

About KyleKelin

Kyle Kelin has been implementing software in the Microsoft space for the past 6 years mainly as a consultant. His interests are SharePoint, .NET, JQuery, and Silverlight.
2019.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems