Monday, August 15, 2011

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


Scenario:

For the following code i was getting following error at the closing bracket of "ImageButton1_Click" methode below is code.

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

 protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            using (SPSite site =SPContext.Current.Site )
            {
                using (SPWeb web = site.OpenWeb())
                {
                    // get wikipagelibrary and file
                    int count = 0;
                    SPList WikiList = web.Lists["WikiPageLibrary"];
                    if( int.Parse(WikiList.Items[0]["LikeCount"].ToString())!=null)
                    count = int.Parse(WikiList.Items[0]["LikeCount"].ToString()) + 1;
                    SPListItem item = WikiList.Items[0];
                    item["LikeCount"] = count;
                    item.Update();
                    web.AllowUnsafeUpdates = false;
                }
            }
        }
Solution:

Then I changed the code  using (SPSite site =SPContext.Current.Site ) to
using (SPSite site =new SPSite (SPContext.Current.Site.Url)) and error gone;

No comments:

Post a Comment