前台代碼
複製代碼 代碼如下:
<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());
}
}