I'm running this code to copy views from a list to another:

foreach (SPView vw in listTempl.Views)
    SPView thisVw = myList.Views[vw.Title];
    if (thisVw == null)
         myList.Views.Add(vw.Title, vw.ViewFields.ToStringCollection(),
             vw.Query, vw.RowLimit, vw.Paged, vw.DefaultView);

The code should run within an Event Receiver. Indeed it doesn't get executed past the if() part: when it comes to a view which is not present in the target list, code interrupts in some way (the event receiver is not executed past that).

Same code (properly adapted) in powershell runs OK:

foreach ($vw in $listTempl.Views)
    $thisVw = $myList.Views[$vw.Title];
    if ($thisVw -eq $null)
        $myList.Views.Add($vw.Title, $vw.ViewFields.ToStringCollection(),
                            $vw.Query, $vw.RowLimit, $vw.Paged, $vw.DefaultView);

I put a breakpoint at the if() line: it is reached for every existing view (eg. the default ones) but it seems to be even skipped for new views.

I tried checking for null view.Title instead of the view itself, with no luck.

I think I am approaching in a wrong way, could you give me any hint?

  • 1
    Put a breakpoint @ the line SPView thisVw = myItem.Views[vw.Title] in C# and check the value of myItem.Views by adding it to a watch. That should give you a hint on why you are not able to find the view. – Arsalan Shahid May 22 '15 at 16:51
  • 1
    Is myItem a list item or is it a list? – Graham May 22 '15 at 17:00

It seems you are using a cached version of SPWeb object. Try creating new SPWeb object and retrieving SPList and SPViews.

Also try recycling SharePoint Timer Service.

  • the C# code would run within an EventReceiver. Should I use the "using SPWeb..." syntax? – En-j May 26 '15 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.