tags:

views:

1682

answers:

4

I'm adding a new field to a list and view. To add the field to the view, I'm using this code:

view.ViewFields.Add("My New Field");

However this just tacks it on to the end of the view. How do I add the field to a particular column, or rearrange the field order? view.ViewFields is an SPViewFieldCollection object that inherits from SPBaseCollection and there are no Insert / Reverse / Sort / RemoveAt methods available.

+2  A: 

You should be able to type:

view.ViewFields.Insert(0, "My New Field");

which will add the new field at the beginning of the collection (change 0 to whatever column index you like).

You can re-order columns with .Reverse() and .Sort(), or write your own re-ordering logic using .Insert() and .RemoveAt().

MusiGenesis
this doesn't actually work - as the question states, there are no Sort / Reverse / Insert methods available for SPViewFieldCollection.
Blakomen
@Blakomen: I didn't notice the `sharepoint` tag when I answered this - "Sharepoint" wasn't originally in the title. I have absolutely no knowledge of Sharepoint whatsoever.
MusiGenesis
+1  A: 

I've found removing all items from the list and readding them in the order that I'd like works well (although a little drastic). Here is the code I'm using:

string[] fieldNames = new string[] { "Title", "My New Field", "Modified", "Created" };
SPViewFieldCollection viewFields = view.ViewFields;
viewFields.DeleteAll();
foreach (string fieldName in fieldNames)
{
    viewFields.Add(fieldName);
}
view.Update();
Alex Angas
A: 

You have to use the follow method to reorder the field

 string reorderMethod = @"<?xml version=""1.0"" encoding=""UTF-8""?> 
                          <Method ID=""0,REORDERFIELDS""> 
                          <SetList Scope=""Request"">{0}</SetList>  
                          <SetVar Name=""Cmd"">REORDERFIELDS</SetVar>  
                          <SetVar Name=""ReorderedFields"">{1}</SetVar>  
                          <SetVar Name=""owshiddenversion"">{2}</SetVar>  
                          </Method>";
+1  A: 

Deleting the fields will result in loss of data This post gives a better solution than deleting all fields and adding them.

http://www.alexbruett.net/?p=48

ashwnacharya
The question was about reordering the fields within a view not a list. But thanks for the link, it will be handy!
Alex Angas