Saturday 31 August 2013

List Operation

Attach File/Document to List Item programmatically in SharePoint 2010 using C#

        public  int AddNewItemWithAttachment()
        {
             // Get name of the file 
            string _Str_File_Name = fuAttachment.PostedFile.FileName;
           //  Get stream data by following way
            byte[] contents = GetFileStream();

           // Declare variable which hold the newly created item id.
            int _Int_ID = 0;

           //  Follow the steps to insert new item into your sharepoint list with attachment. 
           //  Create new instance of site with your current application
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            { 
            //  Create new web instance and open web for current application
                using (SPWeb web = site.OpenWeb())
                { 
                   //  Create new list object and get your list
                    SPList list = web.Lists["EmployeeList"]; 
                   //  Set allowunsafeupdates for web & site to true
                    site.AllowUnsafeUpdates = true;
                    web.AllowUnsafeUpdates = true; 
                   //  Create new list item object and add new item for newly created list object 
                    SPListItem item = list.Items.Add();
                    // Assign value for newly created item
                    item["Title"] = txtFirstName.Text.Trim();
                    item["FirstName"]  = txtFirstName.Text.Trim();
                    item["LastName"]  = txtLastName.Text.Trim();
                    item["Address"]  = txtAddress.Text.Trim();
                    item["Phone"]  = txtPhone.Text.Trim();
                    item["City"]  = txtCity.Text.Trim();
                    item["State"]  = txtState.Text.Trim();
                    item["Country"] = txtCountry.Text.Trim();     
                    //- Assign selected filename and stream data
                    if (!string.IsNullOrEmpty(_Str_File_Name) && (contents.Length > 0))
                    {
                    SPAttachmentCollection fileAttach = item.Attachments;
                    fileAttach.Add(_Str_File_Name, contents );
                    }
                   //  Update item which will add new item to list
                    item.Update();
                    // if you want to manipulate on newly created item then you can get id of the newly created item by following way
                  // return the ID
                   return  _Int_ID = item.ID;
                }
            }        

        }

Add  Attach File/Document to List Item By ListItemID programmatically in SharePoint 2010 using C#

        public void attachmentbylistid(int ItemId)
        {
            using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb _web = _site.OpenWeb())
                {
                    // for testing Let's suppose your Item Id is 1
                  // int ItemId = 1;
                    SPList oList = _web.Lists["EmployeeList"];
                    SPListItem _item = oList.GetItemById(ItemId);
                    if (fileUpload.HasFile)
                    {
                        _web.AllowUnsafeUpdates = true;
                        Stream fs = fileUpload.PostedFile.InputStream;
                        byte[] _bytes = new byte[fs.Length];
                        fs.Position = 0;
                        fs.Read(_bytes, 0, (int)fs.Length);
                        fs.Close();
                        fs.Dispose();

                        _item.Attachments.Add(fileUpload.PostedFile.FileName, _bytes);
                        _item.Update();
                        _web.AllowUnsafeUpdates = false;
                    }
                }
            }

        }


Delete the Attach File/Document to List Item programmatically in SharePoint 2010 using C#

// pass ListItem ID , File name
        private void DeleteAttachment(int NodeID, String strFileName)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            SPList List = SPContext.Current.Web.Lists["EmployeeList"];
            SPListItem delItem = List.GetItemById(NodeID);
            SPAttachmentCollection atCol = delItem.Attachments;
            foreach (string strDelfileName in atCol)
            {
                if (strDelfileName == strFileName)
                {
                    atCol.Delete(strDelfileName);
                    delItem.Update();
                    return;
                }
            }

        }


Add new Items into List programmatically in SharePoint 2010 using C#
        private void AddListItem()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["EmployeeList"];
                    web.AllowUnsafeUpdates = true;
                    SPListItem item = list.Items.Add();
                    item["Title"] = txtFirstName.Text.Trim();
                    item["FirstName"] = txtFirstName.Text.Trim();
                    item["LastName"] = txtLastName.Text.Trim();
                    item["Address"] = txtAddress.Text.Trim();
                    item["Phone"] = txtPhone.Text.Trim();
                    item["City"] = txtCity.Text.Trim();
                    item["State"] = txtState.Text.Trim();
                    item["Country"] = txtCountry.Text.Trim();
                    item.Update();
                    web.AllowUnsafeUpdates = false;
                }
            }
        }


Update List Items By ListItemID  into List programmatically in SharePoint 2010 using C#

        public void UpdateListItem(int _ListItemID)
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists["EmployeeList"];    
                    SPQuery _Query = new SPQuery();
                    _Query.Query = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter' >{0}</Value> </Eq> </Where>", _ListItemID); 
                    
                    //- Assign query to list and get item on the basis of the query build above
                    SPListItemCollection common = list.GetItems(_Query);
                    // Assign value for newly created item
                    if (common.Count > 0)
                    {
                        web.AllowUnsafeUpdates = true;
                        //Get first list item from the result list
                        SPListItem item = common[0];
                        item["Title"] = txtFirstName.Text.Trim();
                        item["FirstName"] = txtFirstName.Text.Trim();
                        item["LastName"] = txtLastName.Text.Trim();
                        item["Address"] = txtAddress.Text.Trim();
                        item["Phone"] = txtPhone.Text.Trim();
                        item["City"] = txtCity.Text.Trim();
                        item["State"] = txtState.Text.Trim();
                        item["Country"] = txtCountry.Text.Trim();
                        item.Update();
                        web.AllowUnsafeUpdates = false;
                    }                    
                }
            }
        }

Delete List Items By ListItemID into List programmatically in SharePoint 2010 using C#

        public void DeleteListItem(int _ListItemID)
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists["EmployeeList"];
                    SPQuery _Query = new SPQuery();
                    _Query.Query = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter' >{0}</Value> </Eq> </Where>", _ListItemID);

                    //- Assign query to list and get item on the basis of the query build above
                    SPListItemCollection common = list.GetItems(_Query);
                    // Assign value for newly created item
                    if (common.Count > 0)
                    {
                        //- Set allowunsafeupdates for web to true
                        web.AllowUnsafeUpdates = true; 
                        //- Delete selected item from fetched list 
                        common[0].Delete(); 
                        //- Update item which will add new item to list
                        web.Update(); 
                    }
                }
            }

        }





      Get SharePoint List Item by ID

        private void GetListItembyID(int ItemID)
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["EmployeeList"];
SPListItem Item = list .GetItemById(ItemID);
Response.Write("Item Title: " + Item["Title"].ToString());
               }
          }
      }

Deleting Multiple Versions of a List Item

When you delete multiple versions of a list item, use the DeleteByID method; do not use the Delete method. You will experience performance problems if you delete each SPListItemVersion object from an SPListItemVersionCollection object. The recommended practice is to create an array that contains the ID properties of each version and then delete each version by using the SPFileVersionCollection.DeleteByID method. The following code examples demonstrate both the approach that is not recommended and the recommended approach to deleting all versions of the first item of a custom list.
Good Coding Practice
Deleting each version of a list item by using the SPFileVersionCollection.DeleteByID method
SPSite site = new SPSite("site url");
SPWeb web = site.OpenWeb();
SPList list = web.Lists["custom list name"];
SPListItem item = list.GetItemById(1);
SPFile file = web.GetFile(item.Url);
SPFileVersionCollection collection = file.Versions;
ArrayList idList = new ArrayList();
foreach (SPFileVersion ver in collection)
{  idList.Add(ver.ID);
}foreach (int verID in idList)
{try{
  collection.DeleteByID(verID);
}catch (Exception ex)
{  MessageBox.Show(ex.Message); 
}}
If you are deleting versions of items in a document library, you can use a similar approach by retrieving the SPListItem.File.Versions property.

No comments:

Post a Comment