Monday, 2 March 2015

How to add an item into list and update if already exists.

public void UpdateProjectTimelineSummaryTasks(SPListItem itmSummary)
        {
            // find ProjectTimelineSummaryTasks list from root site.
            // add/update summary item under this list.
            using (SPSite site = new SPSite(itmSummary.Web.Site.Url))
            {
                using (SPWeb web = site.RootWeb)
                {
                    SPList list = web.Lists.TryGetList(Constants.LIST_PROJECT_SUMMARY_TASKS);
                    if (list != null)
                    {
                        string foreign_key = Convert.ToString(itmSummary["ID"]);
                        string word = itmSummary.Web.Url;
                        string[] wordArr = word.Split('/');
                        string weburl = wordArr[3] + "/" + wordArr[4];

                        //SPListItem _currentItem = list.Items.Add();
                        SPWeb webSite = itmSummary.Web;
                        SPQuery query = new SPQuery();
                        var fkey = SharePointUtility.GetListFieldInternalName(web, Constants.LIST_PROJECT_SUMMARY_TASKS, Constants.COL_FOREIGN_KEY);
                        query.Query = "   <Where><And><Eq><FieldRef Name='" + fkey + "' /><Value Type='Text'>" + foreign_key + "</Value></Eq><Eq><FieldRef Name='WebUrl' /><Value Type='Text'>" + weburl + "</Value></Eq></And></Where>";

                        SPListItemCollection listItemCollection = list.GetItems(query);

                        //IF ITEM IS ALREADY ADDED INTO LIST ; THEN JUST UPDATE IT.
                        if (listItemCollection.Count > 0)
                        {
   //GET THE CURRENT ITEM FROM COLLECTION- WHICH WILL UPDATE
                            SPListItem itemToUpdate = listItemCollection[0];
                            //to do : here we can write code form update the field
                           
                            itemToUpdate.Update();
                        }
//IF ITEM IS NOT EXIST IN THE LIST ; THEN IT WILL ADD
                        else
                        {
                            SPListItem _currentItem = list.Items.Add();
                            //to do : here we can write code form ADD the field value
                            _currentItem[Constants.COL_SITEURL] = word;
                            _currentItem.Update();
                        }
                    }
                }
            }
        }

No comments:

Post a Comment