Wednesday 24 March 2010

Setting a TreeView node in focus

Lately I have been working on a couple of projects and one of them involved a fairly long ASP.NET TreeView control. The requirement was to have it so that when a user clicked on a node, the TreeView would have that selected node in focus after the postback. This proved to be a little troublesome as there is a built in method called HideSelection in the Windows Forms version however that property does not exist in the ASP.NET version of the control.
So while browsing the web, I noticed a couple of people were having the same issue with this control. I managed to hack together some JavaScript using some of the existing script provided by the .NET framework. The following code sets the currently selected TreeViewNode into focus.
function SetSelectedTreeNodeVisible(controlID) {
var theForm = document.forms['aspnetForm'];
if (!theForm) {
theForm = document.aspnetForm;}
var selectedID = theForm.elements[controlID];
if (selectedID != null) {
var selectedNode = document.getElementById(selectedID.value);
if (selectedNode != null) { selectedNode.scrollIntoView(true); }
}
}

To use this code in your page, just call the function like so
SetSelectedTreeNodeVisible('<%= TreeViewName.ClientID %>_SelectedNode');

Replace TreeViewName with the name of your TreeView control. This code should be called at the end of the page so that the treeView has had time to load.

1 comment:

Anonymous said...

Sir, i've decided to take the 70-511 exam(TS: Windows Applications Development with Microsoft .NET Framework 4) some time after it goes live... So, by the time the Microsoft Press Training Kit gets "RTM'd", can i use the MCTS Self-Paced Training Kit (Exam 70-502): Microsoft® .NET Framework 3.5 - Windows® Presentation Foundation Application Development as a preparation guide? And should i go for MSDN Library preparation or the great Wrox Press books? Plz help me sir...