开发者

Removing web part from page programatically - problem with usings

I've tried to do that in fou开发者_如何学Gor different ways:

Like this:

try
{
    SPSite site = SPContext.Current.Site;
    SPWeb web = site.OpenWeb();
}
catch (Exception ex) {}

And like this:

try
{
    using (SPSite site = SPContext.Current.Site) {
       using (SPWeb web = site.OpenWeb()) {
       }
     }
}
catch (Exception ex) {}

And in other 2 combination with/without usings and other 2 with

SPWeb web = SPContext.Current.Web;

Every of them give me one of two errors:

"Trying to use an SPWeb object that has been closed or disposed and is no longer valid."

or

"The operation could not be completed because the Web Part is not on this page.".

Any ideas how to do that properly?


From Disposing Objects:

SPContext objects are managed by the SharePoint framework and should not be explicitly disposed in your code. This is true also for the SPSite and SPWeb objects returned by SPContext.Site, SPContext.Current.Site, SPContext.Web, and SPContext.Current.Web.

For more information, see SharePoint 2007 and WSS 3.0 Dispose Patterns by Example. Also, you may want to use SPDisposeCheck. It give guidance when and when not to dispose SharePoint objects.

If still get the error on SPContext.Current.Site even after removing the incorrect usings, try recycling the application pool or run iisreset.


I doubt the spcontext is the issue. But you should not be disposing of the context web. Can you post your full code block to see where the issue lies.


Here's the code:

            try
        {
            // usings here

            web.AllowUnsafeUpdates = true;
            SPLimitedWebPartManager man = web.GetLimitedWebPartManager("FormServerTemplates/Statistica.aspx", PersonalizationScope.Shared);

            ContentEditorWebPart wp = new ContentEditorWebPart();
            wp.ID = "newlyCreatedWP";

            man.AddWebPart(wp, this.Zone.ID, 2);
            web.AllowUnsafeUpdates = false;
            web.Update();
        }
        catch (Exception e)
        {
            Label l = new Label();
            l.Text = e.Message;
            this.Controls.Add(l);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜