Wednesday, April 21, 2010

Add data to Person or Group field type programatically

In Share point list Person or Group field is a read only field. when we trying to add logged in user to person or group field programatically, usally we capture the windows logged in user by using

txtusername.Text=System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

and give the captured logged in user to the person or group field. But, we get an error because person or group field is readonly field. we can add the logged in user to person or group field type using the following line

listitem["Name"] =web.Users[txtusername.Text];

using (SPSite site = new SPSite("yoursite",systoken))
{
using (SPWeb web = site.OpenWeb())
{

site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["yourlist"];
SPListItem listitem = list.Items.Add();
listitem["user Email"] = web.Users[txtusername.Text].Email;
listitem.Update();
list.Update();
web.AllowUnsafeUpdates = false;
site.AllowUnsafeUpdates = false;
}
}

No comments:

Post a Comment