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 just fine.
What is happening here? What can I do to get the title of the list item when passing in a view?
Check your view definition. Is "Title" one of the fields included in the view definition?
In your first code snippet you're filtering items from your list based on the view. In the second snippet, you're accessing the items directly from the list without filtering.
As an aside: looping on list.Items is a bad idea. Unfortunately the implementation of this property in SharePoint causes 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)
{
...
}
It's sharepooint bug connecting with GetItems by SPView object. When you will retrieve view from list, for example: list.Views["View Name"] ViewFields contains only two fields(Title, LinkTitle) and the SPQuery for retrieved view is empty. If you wanna to filter your list items or get fields via SPQuery class.
Also you wanna to get working state the GetItems(spView) method. You can reset HttpContext and then try to get spView.
For example:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With