前台代码
<script type="text/javascript"> //客户端捕捉事件 function CheckEvent() { var objNode = event.srcElement; if (objNode.tagName == "INPUT" && objNode.type == "checkbox") { var objParentDiv = objNode.id.replace("CheckBox", "Nodes"); if (objNode.checked == true) { setChildCheckState(objParentDiv, true); setParentCheckeState(objNode, true); } else { setChildCheckState(objParentDiv, false); if (!HasOtherChecked(objNode)) { setParentCheckeState(objNode, false); } } } } //判断是否有并行的其他节点被选中 function HasOtherChecked(objNode) { var objParentDiv = WebForm_GetParentByTagName(objNode, "div"); var chks = objParentDiv.getElementsByTagName("INPUT"); for (var i = 0; i < chks.length; i++) { if (chks[i].checked && chks[i].id != objNode.id) { return true; } } return false; } //设置父节点 function setParentCheckeState(objNode, chkstate) { try { var objParentDiv = WebForm_GetParentByTagName(objNode, "div"); if (objParentDiv == null || objParentDiv == "undefined ") { return; } else { var objParentChkId = objParentDiv.id.replace("Nodes", "CheckBox"); var objParentCheckBox = document.getElementById(objParentChkId); if (objParentCheckBox) { objParentCheckBox.checked = chkstate; setParentCheckeState(objParentDiv, chkstate); } } } catch (e) { } } //设置子节点 function setChildCheckState(nodeid, chkstate) { var node = document.getElementById(nodeid); if (node) { var chks = node.getElementsByTagName("INPUT"); for (var i = 0; i < chks.length; i++) { chks[i].checked = chkstate; } } } </script> <body> <form id="form1" runat="server"> <asp:TreeView ID="TreeView1" runat="server" ShowCheckBoxes="All" onclick="CheckEvent()"> </asp:TreeView> </form> </body>
后台代码:private void BindGrid()
{
DataTable mytable = menuTableBll.GetAllList().Tables[0]; //获取数据
CreateTree(mytable, TreeView1.Nodes, "0");
}
private void CreateTree(DataTable dtNodeSets, TreeNodeCollection node, string parent_id)
{
DataView dvList = new DataView(dtNodeSets);
dvList.RowFilter = "MeunParentId =" + parent_id;
TreeNode nodeTemp;
foreach (DataRowView dv in dvList)
{
nodeTemp = new TreeNode();
nodeTemp.Text = dv["MenuName"].ToString();
nodeTemp.Expanded = true;
nodeTemp.ToolTip = dv["MeunId"].ToString();
node.Add(nodeTemp);
CreateTree(dtNodeSets, nodeTemp.ChildNodes, dv["MeunId"].ToString());
}
}