Disable or grey out a node in the TreeNode Editor

mr-euro picture mr-euro · Sep 22, 2009 · Viewed 23.5k times · Source

How do I disable a specific node so the user can not select it. Hiding it for the user is also valid.

I tried the Visible property but that hides the entire tree (all nodes). I only want a few of the nodes disabled/hidden.

C# using Visual Studio 2005 TreeNode Editor.

Answer

Fredrik Mörk picture Fredrik Mörk · Sep 22, 2009

The TreeNode itself does not have any Enabled property, so you will need to find some means of tracking that state. One way to do this is to create a new class that inherits TreeNode and that features an Enabled property. Another way is to maintain a list of disabled tree nodes.

Once that is done, you can use the ForeColor property of the TreeNode to have it appear grayed out (for instance using the SystemColors.GrayText value).

Finally you can use the BeforeSelect event to evaluate whether it's OK for the user to select a particular node, and use the Cancel property of the event args in that event to prevent selecting it if that node is disabled:

private void TreeView_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
    e.Cancel = !NodeIsEnabled(e.Node);
}