Friday, January 16, 2009

How to Expand/Collapse a TreeView with Javascript

I encountered a task today that I thought would be extremely simple: Add a button that would expand/collapse a treeview in a toggle-like manner:

But after I implemented my code, it kept getting stuck on "Expand All". The reason turned out to be that the button was forcing a partial postback in the AJAX Update Panel, even though I had no server-side event defined.

The solution was to modify the client-side click definition a little:

OnClientClick="buttonExpandCollapse_Click(); return false;" />

If you don't add the "return false;" addendum then a postback occurs.

Here by the way is the Javascript code that this button calls:

var treeExpanded;
function buttonExpandCollapse_Click()
{
if (treeExpanded == null)
treeExpanded = false;

var button = $get('<%= buttonExpandCollapse.ClientID %>');
var treeView = <%= treeViewMain.ClientID %>;

// TreeView expand/collapse code here; varies depending on the type of treeview control

if (treeExpanded)
button.value = 'Expand All';
else
button.value = 'Collapse All';

treeExpanded = !treeExpanded;
}

No comments:

Post a Comment