1
\$\begingroup\$

I have a TreeView called myTreeView. I want to be able to write a single statement after which myTreeView.SelectedNode is null, but TreeView.SelectedNode doesn't have a setter. I've looked at the decompiled source of TreeView, and there is a SetSelectedNode method (that can accept null), but it's internal.

So I made this extension method:

public static void ClearSelection(this TreeView treeView)
{
    var currentSelection = treeView.SelectedNode;
    if (currentSelection != null)
    {
        currentSelection.Selected = false;
    }
}

and now I can just say

myTreeView.ClearSelection();

But this seems insane. Am I missing something?

\$\endgroup\$
2
\$\begingroup\$

There's no in-built method to do this. Your extension method looks great.

Even if TreeView did have an obscurely-named method to clear its selected node, I can only imagine it doing exactly the same as what you've written anyway.

| improve this answer | |
\$\endgroup\$
0
\$\begingroup\$

If you havent already figured it out:

currentSelection.SelectedNode.Checked = false;

Hope that helps :)

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ I think you're confusing the Checked and Selected properties. If the TreeView has ShowTextBoxes = true then it will show a checkbox next to each node. These can be checked and unchecked, and you can retrieve checked nodes with the CheckedNodes property. However, when a node is clicked it becomes selected (provided it is not a navigation node). This is then the SelectedNode - irrespective of whether it has been checked. \$\endgroup\$ – James Dec 29 '11 at 22:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.