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;




No comments: