Wednesday, October 28, 2009

Watch out for dispose issue in the snippets for Visual Web Parts

The code snippet below has an issue that you need to watch out...
The dispose guidelines have NOT changed in SP2010, so you have to be careful:

protected void Page_Load(object sender, EventArgs e)
SPWeb thisWeb = null;
TreeNode node;
thisWeb = SPContext.Current.Web;
//Add the Web's title as the display text for the tree node, and add the URL as the NavigateUri
node = new TreeNode(thisWeb.Title, null, null, thisWeb.Url, "_self");
//The Visual Web Part has a treeview control called siteStructure
//Get a reference to the current node, so child nodes can be added in the correct position
TreeNode parentNode = node;
//Iterate through the Lists collection of the Web
foreach (SPList list in thisWeb.Lists)
if (!list.Hidden)
node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
foreach (SPWeb childWeb in thisWeb.Webs)
//Call our own helper function for adding each child Web to the tree
addWebs(childWeb, parentNode);
// have to dispose those
// you should use a try finally block to trap exceptions,
// but at least do:


// you should not dispose the web that you got from the context
// note that this finally block is obsolete now


Update: These issues have been fixed thanks to Paul Andrew.


Post a Comment

Links to this post:

Create a Link

<< Home