SharePoint List View Web Part - Programmatic Approach

There are many SharePoint web parts which ship as Out of the box with the SharePoint and one of those is the View web part. When you want to show the data in your lists and libraries there are many approaches including customizations but this can also be done by simply adding the view web parts on pages but this depends on requirements. A List or Library view web parts can be added directly in web part zones on pages and you are done to show the list or library data.

But I was more curious to take a look at how we can add this web parts programmatically? I searched on the internet (that's what the first thing we all doJ), and I got many posts to do this, some were really useful.

When we simply add the web part on the page through code behind using an object of class "ListViewWebPart" then this works very fine (once the web part properties are correctly initialized) but the problem is that when I was adding using this approach, the tool bar was not getting added correctly. So I again found one more approach by which we add the tool bar explicitly and then remove the already added tool bar with "ListViewWebPart".

So I have created a simple check box web browsable web part's property which allows us to select to show tool bar or not. If we don't choose to show the tool bar then web part simply renders the list view without tool bar, a link at the bottom of List view to add / upload documents will be added.

Here is the code.

 

public class GListView : WebPart

{

        #region Prive Variables

 

        private string _listName;

        private Guid _siteID;

        private Guid _webID;

        private SPList _list;

        private SPContext _context;

        private ListViewWebPart _listViewWebPart;

        private SPView _listView;

        private bool _showToolBar;

 

        #endregion

 

        #region Public Properties

 

 

        [Personalizable(true),

        Category("Custom"),

        WebBrowsable(true),

        WebDisplayName("List Name"),

        WebDescription("List Name")]

        public string ListName

        {

            get { return _listName; }

            set { _listName = value; }

        }

 

        [Personalizable(true),

        Category("Custom"),

        WebBrowsable(true),

        WebDisplayName("Show Tool Bar"),

        WebDescription("Check To Show Tool Bar")]

        public bool ShowToolBar

        {

            get { return _showToolBar; }

            set { _showToolBar = value; }

        }

 

 

        #endregion

 

        #region Overrides - CreateChildControls

 

        protected override void CreateChildControls()

        {

          base.CreateChildControls();

          try

          {

             _siteID = SPContext.Current.Site.ID;

             _webID = SPContext.Current.Web.ID;

 

             //Getting List

             if (!string.IsNullOrEmpty(ListName))

             {

 

              SPSecurity.RunWithElevatedPrivileges(delegate()

              {

                using (SPSite site = new SPSite(_siteID))

                {

                  using (SPWeb web = site.OpenWeb(_webID))

                  {

                     _list = web.Lists[ListName];

                  }

               }

              });

             }

 

  //Getting Context

 _context = SPContext.GetContext(HttpContext.Current, _list.DefaultView.ID, _list.ID, SPContext.Current.Web);

 

                //Initiating Control

                InitializeListView(ShowToolBar);

 

                //Adding Control

                if (_listViewWebPart != null)

                {

                    _listViewWebPart.GetDesignTimeHtml();

                    this.Controls.Add(_listViewWebPart);

                }

 

            }

            catch (Exception ex)

            {

                this.Controls.Add(new LiteralControl(string.Format("{0}-{1}", "Error", ex.Message)));

            }

 

        }

 

        #endregion

 

        #region Private Methods

 

        /// <summary>

        /// Initializes the list view.

        /// </summary>

        private void InitializeListView(bool _showToolBar)

        {

          if (_list != null)

          {

           _listViewWebPart = new ListViewWebPart();

           _listViewWebPart.ListName = _list.ID.ToString("B").ToUpperInvariant();

           _listViewWebPart.TitleUrl = _list.DefaultViewUrl;

           _listViewWebPart.WebId = _list.ParentWeb.ID;

 

           if (_showToolBar)

           {

             //Add Tool Bar

             AddToolBar();

 

             _listView = _list.DefaultView;

             _listViewWebPart.ViewGuid = _listView.ID.ToString("B").ToUpperInvariant();

 

             //Removing ToolBar

             foreach (Control _control in _listViewWebPart.Controls)

             {

               if (_control.GetType().Equals(typeof(ViewToolBar)))

               {

                 _control.Visible = false;

                 break;

               }

             }

 

            }

            else

            {

              _listView = _list.GetUncustomizedViewByBaseViewId(0);

              _listViewWebPart.ListViewXml = _listView.HtmlSchemaXml;

 

            }

          }

        }

 

        /// <summary>

        /// Adds the tool bar.

        /// </summary>

        private void AddToolBar()

        {

            ViewToolBar _viewToolbar = new ViewToolBar();

            if (_context != null)

            {

                _viewToolbar.RenderContext = _context;

                this.Controls.Add(_viewToolbar);

            }

        }

 

        #endregion

 

    }

Reference : Here and Here