Thursday, December 4, 2008

Retrieve the user name from a sharepoint's "Person or Group" field.

Previously, in VPC, to get a name from a "person or group" field from a sharepoint list I had to use this code (in C#):

string onBehalfOf = properties.AfterProperties["On_x0020_Behalf_x0020_Of"].ToString();
int startingIndex = onBehalfOf.IndexOf("#") + 1;
int endingIndex = onBehalfOf.Length - 4;
string onBehalfName = onBehalfOf.Substring(startingIndex, endingIndex);

and I got the name. "On_x0020_Behalf_x0020_Of" is the column (field) name of a sharepoint list

"OnBehalfof" string gets value like this: "11;#M. Andalibur Rahman". So, by doing a substring by "#" u can get the name portion. But in the virtual Server, the "OnBehalOf" string gets only the number, "11", and the program crashes when it wants to do the substring operation. So, I had to figure out the solution by spending almost 1 day. And the solution is:

string currentValue= properties.AfterProperties["On_x0020_Behalf_x0020_Of"].ToString();
SPFieldUser userField= (SPFieldUser)properties.OpenWeb().Lists[properties.ListTitle].Fields.GetField ("On_x0020_Behalf_x0020_Of");
SPFieldUserValue fieldValue= (SPFieldUserValue)userField.GetFieldValue(currentValue);
string onBehalfName = fieldValue.User.Name;

U got the user name.
fieldValue.User will give you SPUser object
fieldValue.User.Id will give you the user Id, 11

No comments: