Saturday, March 3, 2012

SharePoint 2010 : Remove a WebPart from Page programmatically using C#.

Goal

To remove webparts from a page programmatically using C#.

Code

/// <summary>
/// This function will remove web parts with title passed
/// </summary>
/// <param name="_web">Web object</param>
/// <param name="_pageUrl">The url of the page on which the web part exists.</param>
/// <param name="_title">The title of the Web part</param>
private void RemoveWebPart(SPWeb _web, string _pageUrl, string _webPartTitle)
{
    //Remove the control once the page is copied
    Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager _webPartCollection = _web.GetLimitedWebPartManager(_pageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

    //Retrive the webpart and remove
    IList<Microsoft.SharePoint.WebPartPages.WebPart> _listFormWebParts = (from _wp in _webPartCollection.WebParts.Cast<Microsoft.SharePoint.WebPartPages.WebPart>()
                                                                            where string.Compare( _wp.Title , _webPartTitle  , true ) == 0
                                                                            select _wp).ToList();

    //Check if there are any web parts found
    if (_listFormWebParts != null)
    {
        foreach (Microsoft.SharePoint.WebPartPages.WebPart _listFormWebPart in _listFormWebParts)
        {
            //Remove the webpart
            _webPartCollection.DeleteWebPart(_listFormWebPart);

            //Update
            _web.Update();
        }
    }
}


Tip

Suppose we dont want to remove the webpart using "Title" we want to remove the webpart with type.
//Retrive the webpart and remove
IList<Microsoft.SharePoint.WebPartPages.WebPart> _listFormWebParts = (from _wp in _webPartCollection.WebParts.Cast<Microsoft.SharePoint.WebPartPages.WebPart>()
                                                                        where _wp.GetType() == typeof(Microsoft.SharePoint.WebPartPages.ListFormWebPart)
                                                                        select _wp).ToList();

8 comments:

  1. Giving error Unable to cast object type.

    "Unable to cast object of type 'VisualWebPartProject1.VisualWebPart1.VisualWebPart1' to type 'Microsoft.SharePoint.WebPartPages.WebPart'.
    "

    Can you please help me out ?

    ReplyDelete
  2. I have modified Microsoft.SharePoint.WebPartPages.WebPart

    To

    System.Web.UI.WebControls.WebParts.WebPart

    and It works for me. :) Thanks Again

    ReplyDelete
    Replies
    1. @Pritesh,

      Glad it worked for you, but the code i have used is 100% working code and this same code is being used in one of my project.

      Thanks,
      Maulik Dhorajia

      Delete
    2. hi maulik,
      actually i have a small requirement. i am able to get all the calendar list names into dropdown list. when i select on one particular calendar it is showing in the web part page. but my problem is that when i select another calendar from the drop down it is not replacing the existing one but it is creating after that are below that.
      my code is as follows can u help me out how to fix it
      protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
      {

      string filename = "SitePages/WPcal.aspx";
      using (SPSite osite = new SPSite("http://hifx-2:2727/sites/SampleTest/"))
      {
      using (SPWeb oWeb = osite.OpenWeb())
      {
      oWeb.AllowUnsafeUpdates = true;
      SPList list = oWeb.Lists[ddllist1.SelectedItem.ToString()];
      SPLimitedWebPartManager webPartManager = oWeb.GetLimitedWebPartManager(filename, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);




      ListViewWebPart listViewWebPart = new ListViewWebPart();
      listViewWebPart.ListName = list.ID.ToString("B").ToUpper();
      listViewWebPart.TitleUrl = list.DefaultViewUrl;
      listViewWebPart.ViewType = ViewType.Calendar;
      listViewWebPart.ViewGuid = string.Empty;

      webPartManager.AddWebPart(listViewWebPart, "Bottom", 0);
      oWeb.AllowUnsafeUpdates = false;

      }
      }
      }

      Delete
    3. @surabhisusheel,

      It's because you are adding the new Calendar but not removing the old web part which is already there.

      For the first time there wont be a calender in web part but once you select a calender there will be at least one in the web part.

      Kindly change the logic to remove the calendar if there is one. Let me know if this was helpful.

      Thanks,
      Maulik Dhorajia

      Delete
    4. i have tried to delete by uisng ur code but it is not working

      Delete
    5. @surabhishsheel,

      As I have mentioned to one of the readers that this code which I am using is already in use. I am using it in one of my project and it works fine. If you can give me the error, I can try and help you out.

      Thanks,
      Maulik Dhorajia

      Delete
  3. thank you very very much

    it works for me :D

    i used also the comment @ Maulik Dhorajia: System.Web.UI.WebControls.WebParts.WebPart

    ReplyDelete