Friday, December 11, 2009

Working with SPFieldChoice type

This may come as a no-brainer for some, but I thought I'd share it in any case. So, there may be times in a developers life that they need to write some functionality that fiddles around with SPList objects. Within those SPList objects, you may have a field derived from SPFieldChoice type. I'm not going to make this a note about how to derive the current value since that is ultimately a trivial task, but what I will do is talk about defaulting values programmatically (again, probably something trivial for most, but then again, maybe something you don't think about).

Ok, so let's say that you wrote a webpart that has to apply default values to an SPListItem. And within that SPListItem, say you have an SPFieldChoice type. Of course, within SharePoint, you can declare you're own default values, but say you want to buck the trend and set one of the other choices as a defaulted value.

Now you have a few decisions to make: hard code the value (bad design), always take field default value, or loop through choices. I'll show you how to get the latter 2 choices (I'm not about to champion the hardcoding movement).

To get the default value for SPFieldChoice:
  • SPListItem.Fields[Guid, Index, or Name of Column].DefaultValue
To loop through the SPFieldChoice choices:

foreach (string oneChoice in ((SPFieldChoice)SPListItem.Fields[Guid, Index, or Name of Column].Choices)
{
switch (oneChoice)
{
case value1:
{some code}
break;
case value2:
{some code}
break;
default:
{some code}
break;
}
}

No comments:

Post a Comment