Ads

Saturday, 23 March 2013

C# code to create and Update list Views Programmatically in SharePoint 2010

using (SPSite oSPsite = new SPSite("http://MyWebSiteURL/"))
{
    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, true, false, SPViewCollection.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;
}

No comments:

Post a Comment

Ads