Add and Configure ListViewWebpart programitically In SharePoint Webpart Publishing Page

List View Webpart is one of the most commonly used webpart in SharePoint. It is nothing but a view of a list. When we add listview webpart to a page it creates a new hidden view of the list. There are ways by which we

can customize list view webpart like security settings, view fields, tool bar options etc. A important point related to List View Webparts is :-

 

If we set the viewGuid Property of List view webpart to any existing view guid( for e.g default view guid) then copy of that view will be created and attached to list view webpart. Any changes to existing view will not reflect automatically in list view webpart.

 

//// Here i am creating helper class for defining properties of ListViewWebpart, it will be helpful if you have to configure many list view parts in your solution

public class ListViewWebpartHelper
    {
        private bool _customView = false;
        private string _query = string.Empty;
        private string _toolbar = string.Empty;
        private string _authorizationlevel = string.Empty;

//// To Define if we are going to use custom view of default list view of webpart
        public bool customView
        {
            get
            {
                return _customView;
            }
            set
            {
                _customView = value;
            }
        }
        public string AuthorizationLevel
        {
            get
            {
                return _authorizationlevel;
            }
            set
            {
                _authorizationlevel = value;
            }
        }
           
        public string[] ViewFields {get;set;}
         
        public string query {
            get
            {
                return _query;
            }
            set
            {
                _query = value;
            }
        }
        public string toolbar
        {
            get
            {
                return _toolbar;
            }
            set
            {
                _toolbar = value;
            }
        }

    }

//// Set Properties of List View webpart

          

file URL = "http://sitename/pages/MyPage.aspx" //// Set Page URL

string[] OCGroup = "UserGroup"//// Set Group Names for which List View Webpart will be visible

helper = new ListViewWebpartHelper();

helper.customView = true;// if needs Custom View

helper.ViewFields = { "Title", "AssignedTo", "StartDate" };// Set Fields which should be visible in List view Webpart

helper.query = string.Format("<GroupBy Collapse=\"FALSE\"><FieldRef Name=\"{0}\"/></GroupBy>","Title");// Set SP Query for View

AddListViewWebPart(web, ListName, "title" URL, "Center", 2, true, helper);

 

///// Add ListViewWebpart into a Page

<summary>
        /// Adds the list view web part.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="ListName">Name of the list.</param>
        /// <param name="title">The title.</param>
        /// <param name="PageURL">The page URL.</param>
        /// <param name="ZoneID">The zone ID.</param>
        /// <param name="ZoneIndex">Index of the zone.</param>
        /// <param name="publish">if set to <c>true</c> [publish].</param>
        /// <param name="viewHelper">The view helper.</param>
       

 

 public static void AddListViewWebPart(SPWeb web, string ListName, string title, string PageURL, string ZoneID, int ZoneIndex, bool publish, ListViewWebpartHelper viewHelper)
        {
               SPFile file = web.GetFile(PageURL);
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                    file.CheckOut();
                string DisplayTitle = string.Empty;
                ListViewWebPart lvw = null;
                bool isDuplicate = false;
                try
                {
                    using (SPLimitedWebPartManager webPartManagerLimited = web.GetLimitedWebPartManager(PageURL, PersonalizationScope.Shared))
                    {
                        lvw = new ListViewWebPart();
                        SPList list = web.Lists[ListName];
                        if (list == null)
                            throw new ArgumentException("List not found ");
                        lvw.ListName = list.ID.ToString("B").ToUpperInvariant();
                        lvw.TitleUrl = list.DefaultViewUrl;
                        lvw.Title = title;
                        lvw.BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
                        lvw.ChromeType = PartChromeType.TitleOnly;
                        if (viewHelper != null && viewHelper.customView)
                        {
                          //// To Set Security settings of View 

if (!string.IsNullOrEmpty(viewHelper.AuthorizationLevel))
                            {
                                lvw.AuthorizationFilter = viewHelper.AuthorizationLevel;

                            }

                            //// To Set View Guid with Default View Guid

if (viewHelper.ViewFields == null || viewHelper.ViewFields.Count() == 0)
                            {
                                lvw.ViewGuid = list.DefaultView.ID.ToString("B").ToUpperInvariant();
                            }
                        }
                        else
                        {
                            lvw.ViewGuid = list.DefaultView.ID.ToString("B").ToUpperInvariant();
                        }
                        foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in webPartManagerLimited.WebParts)
                        {
                            if (webpart.Title == title) / //// To Prevent Duplicates Webparts into a page
                            {
                                isDuplicate = true;
                                break;
                            }
                        }
                        if (!isDuplicate)
                        {
                            webPartManagerLimited.AddWebPart(lvw, ZoneID, ZoneIndex);
                        }
                        list.Update();
                        web.Update();
                        webPartManagerLimited.Web.Dispose();
                    }
//// Override existing view with Custom Fields and custom query....

 if (viewHelper != null && viewHelper.customView && !isDuplicate)
                    {
                        using (SPLimitedWebPartManager webPartManagerLimited = web.GetLimitedWebPartManager(PageURL, PersonalizationScope.Shared))
                        {
                            var ViewWebPart = (ListViewWebPart)webPartManagerLimited.WebParts.Cast<System.Web.UI.WebControls.WebParts.WebPart>().FirstOrDefault(w => w.Title.Equals(title));
                            var list = web.Lists[ListName];
                            var view = list.Views.Cast<SPView>().FirstOrDefault(w => w.ID.ToString("B").Equals(ViewWebPart.ViewGuid, StringComparison.OrdinalIgnoreCase));
                            if (viewHelper.ViewFields != null && viewHelper.ViewFields.Count() > 0)
                            {
                                view.ViewFields.DeleteAll();
                                foreach (string field in viewHelper.ViewFields)
                                {
                                    view.ViewFields.Add(field); ///// Add New fields
                                }
                            }
                            if (!string.IsNullOrEmpty(viewHelper.query))
                                view.Query = viewHelper.query; ///// Set SP Query
                            view.Toolbar = viewHelper.toolbar;
                            view.Update();
                            webPartManagerLimited.Web.Dispose();
                        }
                    }
                }
                finally
                {
                    if (lvw != null)
                        lvw.Dispose();
                    file.CheckIn(string.Empty);
                    if (publish && file.InDocumentLibrary)
                    {
                        file.Publish("Publishing Changes Added");
                        if (file.Item.ModerationInformation != null)
                            file.Approve("Changes are approved");
                    }
                    web.Update();
                }
        }