farosch
farosch

Reputation: 228

populate treeview recursively

I have a DataGridView which displays all group members of our ActiveDirectory. When double-clicking on a group I want to show all members and sub-members of this group (including users) in a treeView. I have made several attempts to do this but my problem is that the procedure needs to run until all members and sub-members have been added to the treeView, which I am unable to do. Is there some kind of pattern that I need to use for this? Starting from this, how should my code look like?

PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, name);

var nodes = new List<TreeNode>();
foreach (Principal p in gp.GetMembers())
{
     nodes.Add(new TreeNode(p.Name));
}
treeView.Nodes.AddRange(nodes.ToArray());

Upvotes: 0

Views: 562

Answers (2)

Remko
Remko

Reputation: 7340

Querying Active Directory can take a bit of time, especially in larger environments with lots of objects or when you have a slower connection to a Domain Controller.

Therefore I recommended you only enumerate and fill the top level nodes in the TreeView and then on expanding an OU or Container you enumerate the children.

This makes your application responsive and quick as typically user will only expand a few nodes and not all of them.

Upvotes: 1

Freek W.
Freek W.

Reputation: 406

Maybe use IEnumerable to select all parent and children objects.

Use this topic: How to get all children of a parent control? Or this topic on Nodes: How do I get all children from a given parent node?

Upvotes: 1

Related Questions