Wednesday, December 28, 2011

Programmatically search a SharePoint list for a specific items

If you'd like to programmatically search a SharePoint list for specific list items that contain a certain value in one of the lists' fields, the following sample code will allow you to obtain any list items that precisely match the specified criteria:
    string searchValue = "ECM Project";
    using (SPSite site = new SPSite(siteGuid))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList projectList = web.Lists["Project List"];
            SPQuery query = new SPQuery();
            query.Query = string.Format("<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where>", searchValue);
            SPListItemCollection listItems = projectList.GetItems(query);
            web.AllowUnsafeUpdates = true;
            foreach (SPListItem listItem in listItems)
            {
                listItem["Title"] = "Enterprise Content Management Project";
                listItem.Update();
            }
            web.AllowUnsafeUpdates = false;
        }
    }
In this example, I'm performing a search on a custom SharePoint list called "Project List" for any list items that have "ECM Project" for the Title field. Once I find those list items, I replace the Title field with a value of "Enterprise Content Managment Project".

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.