Troubleshooting SPView: ViewFields Doesn’t Return the Fields Selected in the View for Display

// October 28th, 2008 // Sharepoint

Earlier, when I was working on a web part, I ran into an issue; SPView.ViewFields wouldn’t return the fields I have selected in the view.

The following code:

SPView oListView = docList.Views[this.ViewName];

SPViewFieldCollection ViewcollListItems = oListView.ViewFields;

returned Columns in the default view i.e.: Type, Name, Modified, and Modified By, for the document library. I was passing the custom ViewName which I have created. So basically, it returned the default columns.

I stumbled across the following thread on MSDN forum and found the solution, thanks to Michael.

If you are using SPContext in your code, then change the following line from:

SPWeb contextWeb = SPContext.Current.Web;

to the following:

SPWeb contextWeb = SPContext.Current.Site.OpenWeb(SPContext.Current.Web.ServerRelativeUrl);

This did the trick for me.

Leave a Reply