Showing posts with label SPList. Show all posts
Showing posts with label SPList. Show all posts

Get multiple users from PeopleEditor and update column of type “People and Group” in SharePoint List

Get multiple users from PeopleEditor and update column of type “People and Group”.

Aspx Page:
<%@ Register TagPrefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>

<wssawc:peopleeditor id="UserPickerRequestedFor" runat="server" allowempty="False"
height="20px" multiselect="true" selectionset="User" showcreatebuttoninactivedirectoryaccountcreationmode="True"
validatorenabled="True" width="300px"></wssawc:peopleeditor>

Aspx.Cs Page:

ArrayList arrUsers = new ArrayList();
PickerEntity UserEntity = new PickerEntity();
SPFieldUserValueCollection fieldUsrValues = new SPFieldUserValueCollection();                  
int UsrCount = UserPicker.Accounts.Count;
for (int j = 0; j < UsrCount; j++)
{
    UserEntity = (PickerEntity) UserPicker.Entities[j];
    string  UserAcctName = UserEntity.Description;
    Hashtable PeopleEditorData = UserEntity.EntityData;
    string strUserLogin = UserEntity.Key;
    arrUsers.Add(strUserLogin);
}
foreach (object obj in arrUsers)
{
   string login = obj.ToString();
   SPSecurity.RunWithElevatedPrivileges(delegate()
   {
    using (SPSite elevatedSite = new SPSite(web.Site.ID))
    {
      elevatedSite.AllowUnsafeUpdates = true;
      SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID);
      {
        elevatedWeb.AllowUnsafeUpdates = true;
        SPUser User = elevatedWeb.EnsureUser(login);
        SPFieldUserValue val = new SPFieldUserValue(web,User.ID, User.Name);
        fieldUserValues.Add(val);
       }
      }
     });
   }
reqItem["UserNames"] = fieldUserValues;

Get multiple users from People Editor and update column of type “People and Group” – Method2

if (UserPickerOwners.Accounts.Count > 0)
{ reqItem["SiteOwner"] = GetUsersFromPeoplePicker(); }


protected SPFieldUserValueCollection GetUsersFomPeoplePicker(string usrType)
{
  ArrayList arrUsersMain = new ArrayList();
  ArrayList arrUsersSec = new ArrayList();
  PickerEntity UserEntity = new PickerEntity();
  SPFieldUserValueCollection fieldUsrValues = new SPFieldUserValueCollection();
  int UsrCount = 0;

  arrUsersMain = UserPickerOwners.Entities;
  UsrCount = UserPickerOwners.Accounts.Count;

  for (int j = 0; j < UsrCount; j++)
  {
    UserEntity = (PickerEntity)arrUsersMain[j];         
    string strUserLogin = UserEntity.Key;
    arrUsersSec.Add(strUserLogin);
  }      

   foreach (object obj in arrUsersSec)
   {
    string login = obj.ToString();
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
      using (SPSite elevatedSite = new SPSite(web.Site.ID))
      {
          elevatedSite.AllowUnsafeUpdates = true;
          SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID);
          {
               elevatedWeb.AllowUnsafeUpdates = true;
               SPUser User = elevatedWeb.EnsureUser(login);
               SPFieldUserValue val = new SPFieldUserValue(web, User.ID, User.Name);
               fieldUsrValues.Add(val);
           }
         }
      });
    }
   return (fieldUsrValues); 

}


Get single user from PeopleEditor and update column of type “People
and Groups”.

Aspx Page:
<%@ Register TagPrefix="wssawc" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>

<wssawc:peopleeditor id="UserPickerRequestedFor" runat="server" allowempty="False"
height="20px" multiselect="true" selectionset="User" showcreatebuttoninactivedirectoryaccountcreationmode="True"
validatorenabled="True" width="300px"></wssawc:peopleeditor>

Aspx.Cs Page:
PickerEntity UserEntity = new PickerEntity();
int usrCount = UserPicker.Accounts.Count;
for (int i = 0; i < usrCount; i++)
  {
   UserEntity = (PickerEntity)UserPicker.Entities[i];
   string  userAcctName = UserEntity.Description;
   Hashtable peopleEditorData = UserEntity.EntityData;
   string strUserLogin = UserEntity.Key;
   SPSecurity.RunWithElevatedPrivileges(delegate()
   {
   using (SPSite elevatedSite = new SPSite(web.Site.ID))
   {
    elevatedSite.AllowUnsafeUpdates = true;
    SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID);
    {
       elevatedWeb.AllowUnsafeUpdates = true;
       SPUser user = elevatedWeb.EnsureUser(strUserLogin);
    }
   }
 });
SPUser usrToADD = web.AllUsers[strUserLogin];
reqItem["ReqMgr"] = usrToADD;

 


Sharepoint List operations -SPList - Programatically update different column in SPList

Sharepoint List operations :: SPList

Reference a List by its name using the web object[Referenced by current context]

SPSite site = SPContext.Current.Site;
SPWeb web = site.OpenWeb();
SPList DEptList = web.Lists["Departments"]; 

Reference a List Item using its ID

SPListItem  item = DEptList.GetItemById(requestID);
Reference a List Item  filter using a query
SPQuery query = new SPQuery();
query.Query += "<Where><And><Eq><FieldRef Name='Title' />";
query.Query += "<Value Type='Text'>" + role + "</Value></Eq></And></Where>";
SPListItemCollection itemCol = SystemList.GetItems(query);
foreach (SPListItem item in itemCol)
{   
      AdGroup = item["ADGroup"].ToString();
      AdFolder = item["ADFolder"].ToString();

Get value of a column “Single Line Text Column” from an listitem and update a textbox.

txtFax.Text = item["Fax"].ToString();

Get value of a column “People and Group” from an listitem and update a textbox.

char[] charToRemove = { '#', ' ', ';' };
txtNe.Text = item["ReqMgr"].ToString().Remove(0, 3).TrimStart(charToRemove);

 Get multiple users “Names” from People and Groups Column and update a dropdown list

String strFolderOwner = item["Owner"].ToString();
char[] toSplitter = { ';' };
string[] arrOwnerName = strFolderOwner.Split(toSplitter);
for (int i = 1; i < arrOwnerName.Length; i++)
{
string owner = arrOwnerName[i].Substring(arrOwnerName[i].IndexOf("#") + 1);
if ((i % 2) != 0)
    {
         DropFolderOwner.Items.Add(new ListItem(owner, ownerID));
    }
}

Get SPUser value from“People and Group” column.

string strUserValue = item["Head"].ToString(); 
str = strUserValue.Split(';')[0];
deptHeadID = Convert.ToInt32(str);
SPUser depthead = web.AllUsers.GetByID(deptHeadID);

Get value of a column “Date and Time” from an listitem and update a textbox.

string reqDate = item["RequestedDate"].ToString();
DateTime rDate = DateTime.Parse(reqDate);
txtRequestedDate.Text = rDate.ToShortDateString();

 Open and read an attachment from a SPList and using a hyperlink

string fileAttachmentUrl = ""; int attachCount = 0;
attachCount = item.Attachments.Count;
if (attachCount > 0)
{
      SPAttachmentCollection attachCollec = item.Attachments;
      foreach (string fileName in attachCollec)
      {
           fileAttachmentUrl = attachCollec.UrlPrefix + fileName;
           LinkToAttachment.Visible = true;
           LinkToAttachment.Text = "Click here to view " + fileName;
           LinkToAttachment.NavigateUrl = fileAttachmentUrl;
      }
 }

Get value of a column “Yes\No” .

Boolean isVend = (Boolean)item["VAVendor"];

OR

Boolean allResponsed = Convert.ToBoolean(surveyItem["AllResponsesReceived"]);

Get from a “Multiple Choice column"

String str = item["Approval"].ToString();
str = str.Replace("<div>","");str = str.Replace("</div>","");

Check if a column is empty of not.
item["ContactTitle"] != null
For a column of type MultiLine Text also check :
    item["ContactEmail"].ToString() != "<div></div>"

  Add to a column of type string:
SPListItem reqItem = VList.Items.Add();
reqItem["RName"] = currentUser.Name.ToString();
reqItem.Update();

  Add to column of type people and groups:
The user under whose account will have read permissions to the site and contribute permissions to the SharePoint List. So add a “user” to site using escalated privileges and then add to the column.
string Login = "xxx-1\\login”;
SPSecurity.RunWithElevatedPrivileges(delegate()
 {
       using (SPSite elevatedSite = new SPSite(web.Site.ID))
       {
            elevatedSite.AllowUnsafeUpdates = true;
            SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID);
            {
                  elevatedWeb.AllowUnsafeUpdates = true;
                  SPUser manager = elevatedWeb.EnsureUser(Login);
             }
       }
  });
SPUser mgrToADD = web.AllUsers[managerLogin];
reqItem["ReqMgr"] = mgrToADD;

 Add multiple users to type people and groups.
ArrayList arrUsers = new ArrayList();
PickerEntity UserEntity = new PickerEntity();
SPFieldUserValueCollection fieldUsrValues = new SPFieldUserValueCollection();                  
// GET multiple SIMILAR TO USERs FROM THE PEOPLE PICKER
int UsrCount = UserPicker.Accounts.Count;
for (int j = 0; j < UsrCount; j++)
{
    UserEntity = (PickerEntity) UserPicker.Entities[j];
    UserAcctName = UserEntity.Description;
    Hashtable PeopleEditorData = UserEntity.EntityData;
    string strUserLogin = UserEntity.Key;
    arrUsers.Add(strUserLogin);
}
foreach (object obj in arrUsers)
{
   string login = obj.ToString();
   SPSecurity.RunWithElevatedPrivileges(delegate()
   {
    using (SPSite elevatedSite = new SPSite(web.Site.ID))
    {
      elevatedSite.AllowUnsafeUpdates = true;
      SPWeb elevatedWeb = elevatedSite.OpenWeb(web.ID);
      {
        elevatedWeb.AllowUnsafeUpdates = true;
        SPUser User = elevatedWeb.EnsureUser(login);
        SPFieldUserValue val = new SPFieldUserValue(web,User.ID, User.Name);
        fieldUserValues.Add(val);
       }
      }
     });
   }
reqItem["UserNames"] = fieldUserValues;
Add an attachment to a list item:
if (FileUploadW9.PostedFile != null && FileUploadW9.HasFile)
{
        Stream fStream = FileUploadW9.PostedFile.InputStream;
        byte[] contents = new byte[fStream.Length];
        fStream.Read(contents, 0, (int)fStream.Length);
        fStream.Close();
        fStream.Dispose();

       SPAttachmentCollection attachments = reqItem.Attachments;
        string fileName = Path.GetFileName(FileUploadW9.PostedFile.FileName);
        attachments.Add(fileName, contents);
}
Add to a “Yes\No” columns:
reqItem["AccessSimilarTo"] = true;