By: Arjun Chakraborty
Problem:
Often it is tempting to simply assign a column value to an SPFieldLookupValue, or an SPFIeldUserValue. However, there is a danger to this practice; the end user may at some point decide to change a SPUser column type into a multiple select SPUser column. Today’s article addresses this issue.
Solution:
(lookup columns and user columns):
My first approach was to see if there is a difference in:
Item.Fields[columnName].GetType().Name
However, both a lookup field and a multi-select lookup field return "SPFieldLookup". My next approach was to use Collections, such as:
· SPFieldLookupValueCollection
· SPFieldUserValueCollection
So, it comes out to something like this:
string result = string.Empty;
if (workflowProperties.Item.Fields[columnName].GetType().Name == "SPFieldLookup")
{
SPFieldLookupValueCollection mluv =
new SPFieldLookupValueCollection (workflowProperties.Item[columnName].ToString());
bool firstChoice = true;
foreach (SPFieldLookupValue v in mluv)
{
if (firstChoice)
{
result = result + v.LookupValue;
firstChoice = false;
}
else
result = result + ", " + v.LookupValue;
}
}
This will in effect, return each value selected by the user in this column. Even if the column is set back to single select lookup, this code will still function. This will also work for User/Group columns as well if you replace:
SPFieldLookupValueCollection mluv =
new SPFieldLookupValueCollection (workflowProperties.Item[columnName].ToString());
With:
SPFieldUserValueCollection muv =
new SPFieldUserValueCollection(workflowProperties.Web, workflowProperties.Item[columnName].ToString());
And replace:
if (workflowProperties.Item.Fields[columnName].GetType().Name == "SPFieldLookup")
With:
if (workflowProperties.Item.Fields[columnName].GetType().Name == "SPFieldUser")
(Multi-choice column):
What will be a little different is the multiple choice column. There is no catch-all value collection implementation for a multi-choice column.
Instead, we use SPFieldMultiChoiceValue, as an array.
Replace:
if (workflowProperties.Item.Fields[columnName].GetType().Name == "SPFieldLookup")
With:
if (workflowProperties.Item.Fields[columnName].GetType().Name == "SPFieldMultiChoice")
And replace the foreach loop with the following for loop:
SPFieldMultiChoiceValue mcv =
new SPFieldMultiChoiceValue(workflowProperties.Item[columnName].ToString());
bool firstChoice = true;
for (int i = 0; i < mcv.Count; i++)
{
if (firstChoice)
{
result = result + mcv[i].ToString();
firstChoice = false;
}
else
result = result + ", " + mcv[i].ToString();
}
I hope that helps! Also, make sure to check if the field has a non-null value, and if the field actually exists for the item as well…
By: Arjun Chakraborty