I am trying to enumerate a list based on a selected view - basically, programmatically doing what is visually shown when viewing a list.

I will be using this to output a file, so I am first getting all the fields and then each item setup as a table, eg:

Field1, Field2, Field3, Field4
Item1Field1, Item1Field2, Item1Field3, Item1Field4
Item2Field1, Item2Field2, Item2Field3, Item2Field4

My problem is, I only want the fields that are visible when you view it on the page. I build the query using this:

SPQuery query = new SPQuery(list.Views['Viewname']);
query.RowLimit = uint.MaxValue;
SPListItemCollection items = list.GetItems(query);

I can then get the fields that are given in the views using items.QueryFieldNames (or alternatively list.Views['Viewname'].ViewFields, but they are identical). However, these fields use the internal names and for obvious reasons I want to display the DisplayName for each field. I tried using list.Fields[viewfield], but it only takes a GUID, an index or the DisplayName, neither of which I have.

Is there any smart way to get a list of SPFields for a specific view / query?


Probably you're looking for the SPList.Fields.GetFieldByInternalName method. This will allow you to get the field by it's internal name, like this:

foreach (string fieldName in list.Views['Viewname'].ViewFields)
    var field = list.Fields.GetFieldByInternalName(fieldName)
    // do whatever you need with SPField object
| improve this answer | |

SPFields are defined at the list level, not to an individual view or query. Instead of list.Fields[viewfield], try this : list.Fields.GetFieldByInternalName(viewfield)

more info : http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldcollection.getfieldbyinternalname.aspx

| improve this answer | |

You have the internal name so you can get the display name as shown below:

| improve this answer | |

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.