1

I have created a CAML query to get some particular items on a list, that contains OR:

 <Or>
    <Eq><FieldRef Name='Title'/><Value Type='Text'>tileA</Value></Eq>
    <Eq><FieldRef Name='Title'/><Value Type='Text'>titleB</Value></Eq>
 </Or>

Now the query works fine if I pass it to list.GetItems() metod, but it doesn't work when I use it like that:

SPContext.Current.List.DefaultView.Query = myStringQuery;
SPContext.Current.List.DefaultView.Update();

I place the code in a webpart (Page_Load()), that is added to the list, the code executes, but the view remains unfiltered. Anyone knows what might be the reason for that?

matt137
  • 169
  • 1
  • 14

1 Answers1

2

Two things:

First, make sure your CAML is wrapped in a Where element:

<Where>
    <Or>
        <Eq><FieldRef Name='Title'/><Value Type='Text'>tileA</Value></Eq>
        <Eq><FieldRef Name='Title'/><Value Type='Text'>titleB</Value></Eq>
    </Or>
</Where>

Second, rearrange your code like this:

SPView view = SPContext.Current.List.DefaultView;
view.Query = myStringQuery;
view.Update();

I know the code blocks looks the same, but neither SPContext nor DefaultView use private fields. For example, here is the implementation of DefaultView:

internal SPView DefaultView
{
  get
  {
    if (this.m_iDefaultViewIndex == -1)
      return (SPView) null;
    else
      return this[this.m_iDefaultViewIndex];
  }
}

public SPView this[int iIndex]
{
  get
  {
    if (iIndex < 0 || iIndex >= this.Count)
      throw new ArgumentOutOfRangeException();
    else
      return new SPView(this, this.m_arrViewSchema, iIndex);
  }
}

So with:

SPContext.Current.List.DefaultView.Query = myStringQuery;
SPContext.Current.List.DefaultView.Update();

The first line sets the Query property of an instance of DefaultView while the second line calls Update on a new instance of the DefaultView.

Rich Bennema
  • 10,295
  • 4
  • 37
  • 58
  • As for the CAML query you're right, but the query is wrapped in , just forgot to add it here since i don't have access to my original code atm. I will give a feedback on how your solution works when I test it at work – matt137 Sep 08 '11 at 20:13
  • thanks for the info about the DefaultView, i've always wondered why this is happening... – int32 Sep 09 '11 at 05:44
  • so apparently it works only when I do something like this: `SPSite site = SPContext.Current.Site;` and then `using (SPWeb web = site.RootWeb) { var currentView = web.Lists["myList"].DefaultView;` however, I need to refresh the list in browser to see the changes (I even moved the code to OnInit() on the webpart), so it's still far from perferct, however your solution led to the right path, thanks! – matt137 Sep 09 '11 at 07:49
  • @matt137, do not wrap RootWeb in a using statement. See http://blogs.msdn.com/b/rogerla/archive/2008/02/12/sharepoint-2007-and-wss-3-0-dispose-patterns-by-example.aspx#SPDisposeCheckID_140 for more info. – Rich Bennema Sep 09 '11 at 12:35