Wednesday, July 4, 2012

Programmatically get/search SharePoint List items using SPView, SPList.GetItems (SPView)


using (SPSite site = SPContext.Current.Site)
{
  if (site != null)
  {
     using (SPWeb web = site.OpenWeb())
     {
        SPList list = web.Lists["your list name"];

        if (list != null)
        {
            foreach (SPListItem item in list.Items)
            {
            //do something here
            //If you are using ascx page for webpart
            //or want to display on aspx page
           
            Response.Write(item.Title.ToString());

            }
        }
        web.Close();
     }
     site.Close();
   }
}

----------------------------------
SPList.GetItems Method (Microsoft. SharePoint)
Returns a collection of items from the list.
Overload List
Name
Description
SPList.GetItems (SPQuery)
Returns a collection of items from the list based on the specified query.
SPList.GetItems (SPView)
Returns a collection of list items from the list based on the specified view.
SPList.GetItems (SPQuery, String)
Returns a collection of list items from the list based on the specified query and view.
Because SharePoint views (SPView) don't contain definition for SPListItems or SPListItemCollections, we can programmatically retrieve list items from a list in the criteria specified by a view you've created. Items received this way also preserves sorting.
                We do the trick using following code:
SPListItemCollection coll = web.Lists["ListName"].GetItems(web.Lists["ListName"].Views["ViewName"]);
                Complete code block:
using (SPSite site = new SPSite("http://stec/testweb"))
{
    if (site != null)
    {
        using (SPWeb web = site.OpenWeb())
        {

            SPList list = web.Lists["ListName"];

            if (list != null)
            {
                SPListItemCollection coll = web.Lists["ListName"].GetItems(web.Lists["ListName"].Views["ViewName"]);

                foreach (SPListItem item in coll)
                {
                    //do something
                    //if you are testing on console application
                    Console.WriteLine(item.Title.ToString());
                }
            }
            web.Close();
        }
        site.Close();
    }
}

[where "ListName" and "ViewName" are the names of your lists and views, respectively.]


No comments:

Post a Comment