Step by step SharePoint Development Study Notes series 11, Sharepoint list operations

Source: Internet
Author: User

Summary

The custom web part in SharePoint involves operations on items in the list. This document explains how to modify items in the list.

Let's first look at an example.

        /// <summary>        ///         /// </summary>        /// <param name="ID"></param>        /// <returns></returns>        public SPListItemCollection GetSPListItemCollection(string ID)        {            SPListItemCollection itemCollection = new SPListItemCollection();            SPSecurity.RunWithElevatedPrivileges(                    delegate                    {                        using (SPSite spsite = new SPSite(this.CurrentUrl))                        {                            using (SPWeb spWeb = spsite.OpenWeb())                            {                                SPList listInstance = spWeb.Lists[this.ListName];                                SPQuery query = new SPQuery();                                query.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + ID + "</Value></Eq></Where>";                                itemCollection = listInstance.GetItems(query);                            }                        }                    }                );            return itemCollection;        }

Spsecurity. runwithelevatedprivileges () is used to increase the operation permission level to operate the site!

Usage:

Spsecurity. runwithelevatedprivileges (delegate () {code}); Raising the permission will allow the code to be executed with the permissions of SharePoint \ system!

Change the code of a specified item

        public string AddNewItem()        {            string retVal = string.Empty;            try            {                SPSecurity.RunWithElevatedPrivileges(delegate()                {                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))                    {                        using (SPWeb web = site.OpenWeb())                        {                            SPList list = web.Lists["TEST"];                            SPListItem item = list.Items.Add();                            item["Title"] = string.Format("Test at {0}", DateTime.Now.ToString());                            item.Update();                        }                    }                    retVal = "operation  success!";                });            }            catch (Exception ex)            {                retVal += ex.Message;            }            return retVal;        }

If no trace is left, use systemupdate;

Example:

        public string AddNewItem()        {            string retVal = string.Empty;            try            {                SPSecurity.RunWithElevatedPrivileges(delegate()                {                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))                    {                        using (SPWeb web = site.OpenWeb())                        {                            SPList list = web.Lists["TEST"];                            SPListItem item = list.Items.Add();                            item["Title"] = string.Format("Test at {0}", DateTime.Now.ToString());                            item.SystemUpdate();                        }                    }                    retVal = "operation  success!";                });            }            catch (Exception ex)            {                retVal += ex.Message;            }            return retVal;        }

In many cases, we need to allow insecure modifications. Use this allowunsafeupdates.

Example:

        public string AddNewItem()        {            string retVal = string.Empty;            try            {                SPSecurity.RunWithElevatedPrivileges(delegate()                {                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))                    {                        using (SPWeb web = site.OpenWeb())                        {                            web.AllowUnsafeUpdates = true;                            SPList list = web.Lists["TEST"];                            SPListItem item = list.Items.Add();                            item["Title"] = string.Format("Test at {0}", DateTime.Now.ToString());                            item.SystemUpdate();                            web.AllowUnsafeUpdates = false;                        }                    }                    retVal = "operation  success!";                });            }            catch (Exception ex)            {                retVal += ex.Message;            }            return retVal;        }

To delete an item in Sharepoint, perform the following operations.

        /// <summary>        ///         /// </summary>        /// <returns></returns>        private SPList GetCurrentList()        {            using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))            {                using (SPWeb web = siteCollection.OpenWeb())                {                    SPList list = web.Lists[this.ListName];                    return list;                }            }        }        /// <summary>        ///         /// </summary>        /// <param name="id"></param>        /// <param name="version"></param>        /// <param name="recycle"></param>        public void DeleteItemByIDVersion(int id, int version, bool recycle)        {            SPListItem item = GetCurrentList().GetItemById(id);            if (recycle)            {                item.Versions.GetVersionFromID(version).Recycle();            }            else            {                item.Versions.GetVersionFromID(version).Delete();            }        }        /// <summary>        /// Property that holds the list name.        /// </summary>        public override string ListName        {            get { return "Test"; }        }

If only the data of the released version of item is retrieved, the following processing can be performed.

        private NewEntity GetLastApproveVersionByItem(SPListItem item)        {            NewEntity result = null;            if (item == null) return result;            if (item.Level == SPFileLevel.Published)            {                result = this.ConvertToEntity(item);            }            else if (item.Versions != null && item.Versions.Count > 0)            {                foreach (SPListItemVersion itemVersion in item.Versions)                {                    if (itemVersion.Level == SPFileLevel.Published)                    {                        result = this.ConvertToEntity(itemVersion);                        break;                    }                }            }            return result;        }

Summary

SharePoint's list operations mainly include adding, deleting, and modifying item data in the list. Note that the site of the current operation is opened here. Spcontext. Current. Web. url obtains the value of the currently opened page.

Author: Spring Yang

Source: http://www.cnblogs.com/springyangwc/

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.