I am attempting to write an extension method for the SPListItem type to ease the pain of getting SPUserValues as strings. I am getting an "Object reference not set to an instance of an object" exception when I hit the line:
msg = "field.AllowMultipleValues == " + field.AllowMultipleValues;
because field is null. I know that at the item level item[fieldName] has a value and that the field does exist as I can see the field definition in item.Fields.
Any suggestions about where I am going wrong?
public static List<string> GetFieldValueUserLogin(this SPListItem item, string fieldName)
{
try
{
if (item != null)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("_PAR_", TraceSeverity.Unexpected, EventSeverity.Information), TraceSeverity.Unexpected, "Getting value of " + fieldName, null);
List<string> userNames = new List<string>();
SPFieldUser field = item[fieldName] as SPFieldUser;
string msg = field == null ? "field is null" : "field is not null";
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("_PAR_", TraceSeverity.Unexpected, EventSeverity.Information), TraceSeverity.Unexpected, msg, null);
msg = "field.AllowMultipleValues == " + field.AllowMultipleValues;
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("_PAR_", TraceSeverity.Unexpected, EventSeverity.Information), TraceSeverity.Unexpected, msg, null);
//Etc ...
}
}
Edit--- After a bit of caffeine I went back and realized I was kind of being an idiot. Appears to be my modus operandi. Here is my final method code.
public static List<string> GetFieldValueUserLogins(this SPListItem item, string fieldName)
{
try
{
if (item != null)
{
List<string> userNames = new List<string>();
SPFieldUserValueCollection uvc = new SPFieldUserValueCollection(item.Web, item[fieldName].ToString());
foreach (SPFieldUserValue userValue in uvc)
{
userNames.Add(userValue.User.LoginName);
}
return userNames;
}
else
{
return null;
}
}
catch (Exception ex)
{
SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("_PAR_", TraceSeverity.Unexpected, EventSeverity.Information), TraceSeverity.Unexpected, ex.Message + " - " + ex.StackTrace.ToString(), null);
return null;
}
}
