Tuesday, July 29, 2008

Building TreeView Programmably in a Recursively Fashion

Below is an example of building a TreeView from a registry hierarchy. Note that RegistryKey and Registry objects are in Microsoft.Win32 namespace.

private int maxDepth = 0, depth = 0;

protected void Page_Load(object sender, EventArgs e)
{
RegistryKey schangeRoot = Registry.LocalMachine.OpenSubKey("Software\\SeaChange", false);

TreeNode rootNode = new TreeNode(schangeRoot.Name);

Traverse(schangeRoot, rootNode);

Response.Write(maxDepth.ToString() + "
" + depth.ToString());

TreeView1.Nodes.Add(rootNode);
}

private void Traverse(RegistryKey current, TreeNode currentNode)
{
Response.Write(depth.ToString() + current.Name + "
");

if (current.SubKeyCount <= 0)
{
if (depth > maxDepth)
maxDepth = depth;

return;
}

foreach (string subkeyName in current.GetSubKeyNames())
{
// Before traversing the subkey, create a new node for it
TreeNode childNode = new TreeNode(subkeyName);

// Traverse subkey
depth++;
Traverse(current.OpenSubKey(subkeyName), childNode);
depth--;

// Finish traversing the subkey, add the subkey to this node
currentNode.ChildNodes.Add(childNode);
}
}

No comments: