Search code examples
sharepointlistviewweb-parts

sharepoint add webpart to page using C#


I have a problem with adding sharepoint listviewwebparts to a webpart page. i want to do it programmatically with C#. i have made the page but adding the listviewwebpart isnt working. code is below.

   private void addListViewWebPart(SPFeatureReceiverProperties properties, String _listName)
        {
            using (SPWeb _web = properties.Feature.Parent as SPWeb)
            {
                SPList _list = _web.Lists.TryGetList(_listName);

                if (_list != null)
                {
                    ListViewWebPart _webPart = new ListViewWebPart();

                    _webPart.ZoneID = "Left";
                    _webPart.ListName = _list.ID.ToString("B").ToUpper();
                    _webPart.ViewGuid = _list.Views[0].ID.ToString("B").ToUpper();

                    SPWebPartCollection _webPartColl = _web.GetWebPartCollection("Default.aspx", Storage.Shared);
                    System.Guid _guid = _webPartColl.Add(_webPart);
                }
            }
        }

anyone knows why it isnt working?

thanks in advance.


Solution

  • You will need to use the SPLimitedWebPartManager and its AddWebPart Method.

    There is an example in this blog.: Add Web Part programmatically using SPLimitedWebPartManager.