SPList.GetItems (view) returns an exception when trying to get the title of an element

When I try:

using (SPWeb web = site.OpenWeb("/")) { SPList list = web.Lists["Blah"]; SPView view = web.GetViewFromUrl("http://foo.com/Lists/Blah/View%20Name.aspx"); foreach (SPListItem item in list.GetItems(view)) { writer.write(item.Title); } } 

item.Title gets me an ArgumentException.

But when I just use

 foreach (SPListItem item in list.Items) { writer.write(item.Title); } 

It works great.

What's going on here? What can I do to get the title of a list item when passing in a view?

+4
source share
2 answers

Check your definition. Is the "Title" one of the fields included in the view definition?

In your first code snippet, you filter the items from your list based on the view. In the second fragment, you get access to the elements directly from the list without filtering.

As an aside: loop on the list. It is a bad idea. Unfortunately, implementing this property in SharePoint forces it to retrieve items from the database for each iteration of the loop. This code is preferred and equivalent:

 SPListItemCollection listItems = list.Items; foreach (SPListItem item in listItems) { ... } 
+9
source

This is a sharepooint error related to the GetItems of a SPView object. When you get the view from the list, for example: list.Views ["View Name"] ViewFields contains only two fields (Title, LinkTitle), and SPQuery for the removed view is empty. If you want to filter list items or get fields through the SPQuery class.

You also want to get the working state of the GetItems (spView) method. You can reset the HttpContext and then try to get spView.

For instance:

  private SPListItemCollection GetItemsByEventType() { HttpContextHelper.ResetCurrent(); SPList list; try { SPWeb web = Context.Site.OpenWeb(Context.Web.ID); try { list = web.Lists[ListName]; } catch (Exception) { list = web.GetListFromUrl(ListName); } if (!String.IsNullOrEmpty(ListViewName)) { SPView view = list.Views.Cast<SPView>() .Where(t => t.Title == ListViewName) .FirstOrDefault(); return list.GetItems(view); } } finally { HttpContextHelper.RestoreCurrent(); } return list.Items; } protected new SPContext Context { get { return SPContext.GetContext(base.Context); } } public class HttpContextHelper { #region Fields [ThreadStatic] private static HttpContext _current; #endregion #region Methods public static void ResetCurrent() { if (_current != null) { throw new InvalidOperationException(); } _current = HttpContext.Current; HttpContext.Current = null; } public static void RestoreCurrent() { HttpContext.Current = _current; _current = null; } #endregion } 
+1
source

Source: https://habr.com/ru/post/1286028/


All Articles