Question

in feature upgrading I have to add a field to the list view, that will point to new column in content type.

Currently my code is based on the assumption that view's title is All Links (I got it through the debugger). So it's the snippet:

                SPView view;
                try
                {
                    view = list.Views["All Links"];
                }
                catch
                {
                    view = list.Views[0]; // just in case
                }
                view.ViewFields.Add("NewField");
                view.Update();

Now it works, but the assumption is that the title of the view is All Links (or there's only one view [0]). I didn't find title inside schema.xml nor in other places. What is the best secure way to update the view in code? (or perhaps there's a better way to update it, for instance with XML, but I as far as I know when feature is upgraded schema.xml file is not taken into account).

Thanks,Pawel

Was it helpful?

Solution

To find the default title of a view inside schema.xml, look at the DisplayName attribute of appropriate the View element. If the attribute value is "All Links", then you could be fine.

If, as in the case of the out of the box Links list definition, the value is something like $Resources:core,All_Links;, then there is more to consider. If your sites are English only, then you still could be fine searching for "All Links". But if you have other language sites, you will need to do something like this:

string title = SPUtility.GetLocalizedString(
    "$Resources:All_Links;", 
    "core", 
    web.Language);
SPView view = list.Views[title];

Now, even if the attribute value is "All Links" or if all sites are in English, there is still the possibility (especially in an Upgrading event) that the title has been changed from the default. In those cases, I prefer to search by BaseViewID. Unfortunately, there is not an indexer for BaseViewID, so I use the following code:

private SPView GetView(SPList list, string id)
{
    SPView view = null;
    foreach (SPView v in list.Views)
    {
        if (id == v.BaseViewID)
        {
            view = v;
            break;
        }
    }
    return view;
}

OTHER TIPS

Another way to retrieve your View is by using SPWeb.GetViewFromUrl("Lists/{List_Name}/{View_Name}.aspx"), cf. msdn article

Then your code would look something like this (if your feature is Web - scoped):

SPWeb web = (SPWeb)properties.Feature.Parent;    
SPView view = web.GetViewFromUrl("Lists/<List_Name>/All Links.aspx");
view.ViewFields.Add("NewField"); 
view.Update();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top