And that is totally wrong.
So here is simple code snippet for how to fetch user from SharePoint list.
To do this you have to use SPFieldUserValue object provided by SharePoint object model
Here is the start up
SPSite site = new SPSite("http://spvm");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["DemoList"];
SPListItem item = list.GetItemById[1];
SPFieldUserValue objUserFieldValue = new SPFieldUserValue(web, item["User"].ToString());
Once you get this object SPFieldUserValue ( objUserFieldValue) then you can retrieve each and every property of that user by following way.
objUserFieldValue.User.LoginName;
objUserFieldValue.User.Name;
objUserFieldValue.User.ID;
objUserFieldValue.User.Groups;
objUserFieldValue.User.Roles;
objUserFieldValue.User.Email;
objUserFieldValue.User.Sid;
objUserFieldValue.User.UserToken;
So all the properties of SPUser will be available and you can use that the same way you treat SPUser field.
For group you can like this way
If(objUserFieldValue.User==null)
//Then selected value is group.
Else
//Selected value is user.
For allowing multi selection we have to use collection
SPFieldUserValueCollection objUserFieldValueCol = new SPFieldUserValue(web, item["User"].ToString());
for (int i = 0; i < objUserFieldValueCol.Count; i++)
{
SPFieldUserValue singlevalue = objUserFieldValueCol[i];
if (singlevalue.User == null)
//then single value is group
else
//singlevalue is user and you can use all SPUser properties.
}
This is same concept as SPLookupFieldvalue and this is also good practice to imbibe.
4 comments:
In which .net application to write the code of getting username?????
pls tel in detail...
Pals,
you can write this code to any webpart, in event handler, in feature receiver or any where you want this detail.
I had a scenario in which I used this. Thanks a ton!!! :)
I had a scenario in which this explanation was extremely helpful!
Thanks a ton!!! :)
Post a Comment