Thursday, 29 November 2012


In SharePoint, View is a virtual representation of a set of data from a specific list. We can programmatically create and update views for a list.
Provided below is an example in C#.Net which explains the approach of creating and updating views. The code is divided in to 2 parts i.e. Part I - describes how to create a view by assigning specific fields from a list, and Part II - describes how to update an existing view by adding few more fields to it.
using (SPSite oSPsite = new SPSite("http://website_url/"))
{
    oSPsite.AllowUnsafeUpdates = true;
    using (SPWeb oSPWeb = oSPsite.OpenWeb())
    {
        oSPWeb.AllowUnsafeUpdates = true;
        /* get the list instance by list name */
        SPList list = oSPWeb.Lists["List_Name"];
        /* ======== Part I (create a view) ======== */
        // add the field names to the string collection
        StringCollection strViewFields = new StringCollection();
        strViewFields.Add("FullName");
        strViewFields.Add("Address");
        strViewFields.Add("City");
        strViewFields.Add("State");
        // create a standard view with the set of fields defined in the collection
        list.Views.Add("View_Name", strViewFields, String.Empty,
            100, truefalseSPViewCollection.SPViewType.Html, false);
        /* ==== End Part I ==== */
        /* ==== Part II (add fields to an existing view) ==== */
        // get the view instance by view display name
        SPView view = list.Views["Existing_View_Name"];
        // add fields to the view
        view.ViewFields.Add("Zip");
        view.ViewFields.Add("Country");
        // update view for new fields
        view.Update();
        /* ==== End Part II ==== */
        /* update the list */
        list.Update();
        oSPWeb.AllowUnsafeUpdates = false;
    }
    oSPsite.AllowUnsafeUpdates = false;
}

Author: Sreekanth Reddy M


No comments:

Post a Comment