Tuesday, June 26, 2012

Elegant way of setting and getting values from SPListItem

As we already know setting and getting values from SPListItem usually involves checking if the field is available, if exist then checking if the value is not null and then only we can make sure that we can read a value from the SPListItem. the following code snippet explains how we usually do that;

1 using (SPSite spSite = new SPSite("http://sp2k10"))
2 {
3 using (SPWeb spWeb = spSite.OpenWeb())
4 {
5 try
6 {
7 SPList spList = spWeb.Lists.TryGetList("ListName");
8 SPListItem spListItem = spList.GetItemById(1);
9 //see if the field exists and the value is not null
10 string fieldName = "fieldName";
11 if (spListItem.Fields.ContainsField(fieldName) && spListItem[fieldName]!=null)
12 {
13 object fieldVal = spListItem[fieldName];
14 }
15 }
16 catch (Exception exception)
17 { }
18 }
19 }



as you can see we have to know the type of the column for us to type cast the returned value. it would be really easy for the programmer if there is a way to call a typed method and get the value back. to achieve this I have decided to write 2 extension methods to get and set SPListItem values.



first we will look at the setting of SPListItem value using extention method.









1 public static bool TrySetValue<T>(this SPListItem listItem, string fieldInternalName, T value)
2 {
3 try
4 {
5 if (!String.IsNullOrEmpty(fieldInternalName) &&
6 listItem != null &&
7 listItem.Fields.ContainsField(fieldInternalName))
8 {
9 listItem[fieldInternalName] = value;
10 }
11 return true;
12 }
13 catch (Exception exception)
14 {
15 return false;
16 }
17 }


as you can see there is no magic here and the value is assigned at line 9.



Now, let’s look at the set method. I have used generics in order to prevent calling method using type casting.



1 public static T TryGetValue<T>(this SPListItem listItem, string fieldInternalName)
2 {
3 if (!String.IsNullOrEmpty(fieldInternalName) &&
4 listItem != null &&
5 listItem.Fields.ContainsField(fieldInternalName))
6 {
7 object untypedValue = listItem[fieldInternalName];
8 if (untypedValue != null)
9 {
10 var value = (T)untypedValue;
11 return value;
12 }
13 }
14 return default(T);
15 }


Let’s look at the usage of these 2 methods.



1 SPListItem spListItem = spList.GetItemById(1);
2 //read values
3 string title = spListItem.TryGetValue<string>("Title");
4 DateTime modDate = spListItem.TryGetValue<DateTime>("dateTimeField");
5
6 //set value
7 spListItem.TrySetValue("dateTimeField", DateTime.Now);
8 spListItem.TrySetValue("Title", "test value");
9 spListItem.Update();


Hope this blog post would help you to streamline the SPListItem set and get value process.