# Is this really what has to be done to clear the selection of an ASP.NET TreeView?

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?

## 2 Answers

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.

If you havent already figured it out:

currentSelection.SelectedNode.Checked = false;


Hope that helps :)

• 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. – James Dec 29 '11 at 22:47