用到TreeView的CheckBox时,通常需要联动操作,即父节点被选中,则子节点全部选中,反之一样,这样的需求用JavaScript实现比较适合,如果用c#代码实现这样的效果,性能是不如JavaScript的
贴上代码: Code
<script type="text/javascript" language="javascript">
//checkbox点击事件
function OnCheckEvent()
{
var objNode = event.srcElement;
if(objNode.tagName != "INPUT" || objNode.type != "checkbox")
return;
//获得当前树结点
var ck_ID = objNode.getAttribute("ID");
var node_ID = ck_ID.substring(0,ck_ID.indexOf("CheckBox")) + "Nodes";
var curTreeNode = document.getElementById(node_ID);
//级联选择
SetChildCheckBox(curTreeNode,objNode.checked);
SetParentCheckBox(objNode);
}
//子结点字符串
var childIds = "";
//获取子结点ID数组
function GetChildIdArray(parentNode)
{
if (parentNode == null)
return;
var childNodes = parentNode.children;
var count = childNodes.length;
for(var i = 0;i < count;i ++)
{
var tmpNode = childNodes[i];
if(tmpNode.tagName == "INPUT" && tmpNode.type == "checkbox")
{
childIds = tmpNode.id + ":" + childIds;
}
GetChildIdArray(tmpNode);
}
}
//设置子结点的checkbox
function SetChildCheckBox(parentNode,checked)
{
if(parentNode == null)
return;
var childNodes = parentNode.children;
var count = childNodes.length;
for(var i = 0;i < count;i ++)
{
var tmpNode = childNodes[i];
if(tmpNode.tagName == "INPUT" && tmpNode.type == "checkbox")
{
tmpNode.checked = checked;
}
SetChildCheckBox(tmpNode,checked);
}
}
//设置父结点的checkbox
function SetParentCheckBox(childNode)
{
if(childNode == null)
return;
var parent = childNode.parentNode;
if(parent == null || parent == "undefined")
return;
do
{
parent = parent.parentNode;
}
while (parent && parent.tagName != "DIV");
if(parent == "undefined" || parent == null)
return;
var parentId = parent.getAttribute("ID");
var objParent = document.getElementById(parentId);
childIds = "";
GetChildIdArray(objParent);
//判断子结点状态
childIds = childIds.substring(0,childIds.length - 1);
var aryChild = childIds.split(":");
var result = false;
//当子结点的checkbox状态有一个为false,其父结点包括祖先的checkbox状态为false
var mark=0;
for(var i in aryChild)
{
var childCk = document.getElementById(aryChild[i]);
if(childCk.checked)
mark++;
}
if(mark==aryChild.length)
result=true;
parentId = parentId.replace("Nodes","CheckBox");
var parentCk = document.getElementById(parentId);
if(parentCk == null)
return;
if(result)
parentCk.checked = true;
else
parentCk.checked = false;
SetParentCheckBox(parentCk);
}
</script>
TreeView1.Attributes.Add("onClick", "OnCheckEvent()");