How would you guys conditionally disable checkboxes in an asp treeview?
For instance, if an application user does not have a certain permission, disable that permission entry checkbox in a permissions treeview.
Here's what i'm looking for, this is the equivaqlent in a winform app (the checkboxes are disabled where the text is grayed out):

I saw other solutions where the click event on the checkboxes is intercepted and ignored. I would prefer a solution where the checkboxes are simply set to disabled.
I'm looking for a C# solution but will be happy with a C#/Javascript solution.
Thanks!
Ok, found a fairly clean solution to this:
in code-behind:
TreeNode newNode = new TreeNode(permission.ToString());
newNode.SelectAction = TreeNodeSelectAction.None; // no Link
if (shouldDisableCheckbox)
{
// Set a class so disabled nodes can be formatted thru CSS
// and be identifiable as disabled in Javascript.
newNode.Text = "<span class=disabledTreeviewNode>" + newNode.Text +"</span>";
}
nodes.Add (newNode);
in Javascript, scan all treeview nodes for those that have that className and disable the checkboxes associated to them:
// Called via a startup script created in Code Behind.
// Disables all treeview checkboxes that have a text with a class=disabledTreeviewNode.
// treeviewID is the ClientID of the treeView
function DisableCheckBoxes(treeviewID)
{
TREEVIEW_ID = treeviewID;
var treeView = document.getElementById(TREEVIEW_ID);
if (treeView)
{
var childCheckBoxes = treeView.getElementsByTagName("input");
for (var i = 0; i < childCheckBoxes.length; i++)
{
var textSpan = GetCheckBoxTextSpan(childCheckBoxes[i]);
if (textSpan.firstChild)
if (textSpan.firstChild.className == "disabledTreeviewNode")
childCheckBoxes[i].disabled = true;
}
}
}
function GetCheckBoxTextSpan(checkBox)
{
// Set label text to node name
var parentDiv = checkBox.parentNode;
var nodeSpan = parentDiv.getElementsByTagName("span");
return nodeSpan[0];
}
Sadly, I don't have enough reputation to be able to comment directly on zukanta's answer which is a bit of a pain, but I had to make a modification in the javascript to make this work:
if (textSpan.firstChild)
if (textSpan.className == "disabledTreeviewNode")
childCheckBoxes[i].disabled = true;
i.e. replace textSpan.firstChild.ClassName with textSpan.ClassName
Also worth pointing out that the JavaScript will error out unless all of your tree nodes in the treeview that you are addressing have a
<span></span>
in them. You get a null reference at
if (textSpan.firstChild)
and no subsequent nodes are processed.
I got around this point by adding a span with class=enabledTreeviewNode to all tree nodes that I didn't want disabled.
You could also handle the exception in the JavaScript, I guess.
Hope this helps someone who stumbles across this (otherwise excellent) solution later on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With