Search code examples
visual-studio-2010sharepoint-2010

SharePoint 2010: edit a view programmatically


As the title says, i need a way to programmatically edit an existing view of a list in sharepoint 2010. I have found a lot of examples about creating a new view:

SPList documents = web.Lists["Documents"];
StringCollection fields = new StringCollection();
fields.Add("Type");
fields.Add("Name");
fields.Add("File Size");
fields.Add("Modified");
fields.Add("Modified By");
fields.Add("Version");
var query = new XElement("Where",
    new XElement("Eq",
        new XElement("FieldRef", new XAttribute("Name", "Project")),
        new XElement("Value", new XAttribute("Type", "Lookup"), "alpha")
    )
).ToString(SaveOptions.DisableFormatting);

SPView view = documents.Views.Add(
    "ProjectFilter",
    fields,
    query,
    100,
    false,
    false,
    Microsoft.SharePoint.SPViewCollection.SPViewType.Html,
    false);

I also have found some examples about editing an existing list in terms of displayed fields:

SPList documents = web.Lists["Documents"];
SPview view = documents.Views["All Documents"];
view.ViewFields.Add("Price");
view.Update();

The only thing i haven't found is a way to modify an existing view filtering it with a CAML query, in the same way as the example above when i have created it

Is there a way to do this?


Solution

  • Ok here's the solution!

    SPList documents = web.Lists["Documents"];
    SPView docview = documents.Views["Project Filtered"];
    
    var docquery = new XElement("Where",
        new XElement("Eq",
            new XElement("FieldRef", new XAttribute("Name", "Project")),
            new XElement("Value", new XAttribute("Type", "Lookup"), "alpha")
        )
    ).ToString(SaveOptions.DisableFormatting);
    
    docview.Query = docquery;
    docview.Update();