As the title explains, I am trying to remove the default Web Parts that are associated to list items and replace them with my own custom web parts.

Here is what I've attempted so far:

SPList list = Web.Lists["MyList"];
string DefaultNewForm_url = list.DefaultNewFormUrl;

SPFile defaultNewForm = Web.GetFile(DefaultNewForm_url);
SPLimitedWebPartManager manager = defaultNewForm.GetLimitedWebPartManager(PersonalizationScope.Shared);
manager.WebParts[0].Hidden = true; //Is the correct way to close out the default webpart?
string WebPartURL = "http://mysite/_catalogs/wp/MyWebPart.webpart";
XmlTextReader reader = new XmlTextReader(new StringReader(Web.GetFileAsString(WebPartURL)));
System.Web.UI.WebControls.WebParts.WebPart wp = (System.Web.UI.WebControls.WebParts.WebPart)manager.ImportWebPart(reader, out err);
wp_RmaAdj.Title = "Test Title";
manager.AddWebPart(wp, "Main", 0);

Web.AllowUnsafeUpdates = false;

This is the error I get when navigating to the list items Display Form:

Web Part Error: A Web Part or Web Form Control on this Page cannot be displayed or imported. The type MyWebPart.WebPart, MyWebPartProject, Version=, Culture=neutral, PublicKeyToken=18eb8b20d1498694 could not be found or it is not registered as safe.

I'm assuming this is coming from the fact that I may not be closing the default webpart correctly? Please correct me if I'm wrong.

  • I have had that error on another scenario, please validate if you have you webpart within "<SafeControls>" tag on the web.config from your web app. – agzertuche Jul 16 '14 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.