When looking at the value that is stored, we can see it is a lookup field - and is stored using the format ID#useraccount. For example:listitem["User Name"]
will have "1#development\ishai"Click on the image below to see it in action in visual studio:
So how do we use this field in code?
Get a user from a list item:
using (SPSite site = new SPSite("http://portal"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Example For Users"];
SPListItem item = list.Items[0];
SPFieldUserValue userValue = new SPFieldUserValue(web, item["User Name"].ToString());
if (userValue.User.LoginName == web.CurrentUser.LoginName)
{
//do something!
}
}
}
Adding a value to a user field
This is the same, but in reverse. We use the same class (SPFieldUserValue ) and give it the values we want for the user.
{using (SPSite site = new SPSite("http://portal"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Example For Users"];
SPListItem item = list.Items[0];
SPFieldUserValue userValue = new SPFieldUserValue(web, web.CurrentUser.ID, web.CurrentUser.LoginName);
item["User Name"] = userValue;
item.Update();
}
}
0 comments:
Post a Comment