adandelion

诗词在线 http:/www.chinapoesy.com


诗词在线 |唐诗|宋词|元曲|诗经|离骚|乐府|现代诗歌

博客园 首页 联系 订阅 管理

2.包括TreeView的asp.net程序的打包问题:
http://ttyp.cnblogs.com/archive/2005/06/01/165621.html
http://community.csdn.net/Expert/topic/4300/4300558.xml?temp=.7716028

在web.config加入以下节

    <configSections>
        
<section name="MicrosoftWebControls" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />    
    
</configSections>
 
    
<MicrosoftWebControls>
        
<add key="CommonFiles" value="/web/treepath/"></add>        
    
</MicrosoftWebControls>


注意:configSections一定要放在第一个子节最前面.

剪切默认网站的webctrl_client目录到虚拟目录web/treepath/下,运行程序,树型界面出现了,只是前面的加减号出现问题,再右键查看WEB代码,发现SystemImagesPath属性还是指到webctrl_client目录下,看了SystemImagesPath的代码,把treeview控件的SystemImagesPath设置为空,再次运行程序,OK!全部通过,treeview的图片目录再也不需要依赖默认网站的图片目录了,打包也变的方便了

3.客户端操作TreeView带CheckBox的好例子(1)--选择 /取消父节点后其所有子节点自动选择 /取消。不过里面有点小问题要注意:

(1)就是如何初始化已经选择的节点:注意要从客户端初始化的(把选择的节点放在客户端一个隐藏域里通过JS初始化).如果你在服务器端初始化了将无法在客户端修改它的状态.

(2)如何获得客户端设置的节点:在客户端改变了选择状态(node.setAtrribute("check","ture"))后,通过服务器端是无法获得选择的值的,也只能在客户端获得它(通过一个input type="hiiden" runat="server"来保存选择的值).
上面两个问题都是参考了下面的代码完成的.


两个客户端操作TreeView节点CheckBox的小例子 (转江雨.net)(自动选择子节点)
下面是修改后详细代码:

<script language="javascript">

            
//初始化选中节点
            function initchecknode()
            
{
                
//获得需要初始化选择状态的节点的字符串.
                var selectedNodes = document.all.checkedNodes.value;
                
var arrayNodes = new Array();
                arrayNodes 
= selectedNodes.split(",");
                
var AllRootNode=new Array();
                AllRootNode
=document.getElementById("TreeView1").getChildren();
                
//初始化选择的节点
                findAndCheckedNodes(AllRootNode,arrayNodes);
            }


            
//根据已选择的节点的字符串初始化选择的节点
            function findAndCheckedNodes(NodeArray,nodeDatas)
            
{
                
//alert(NodeArray.length);
                 if(parseInt(NodeArray.length)==0)
                 
{
                    
return;
                }

                
else
                
{
                    
for(var i=0;i<parseInt(NodeArray.length);i++)
                    
{
                        
var cNode,nodeData;
                        cNode
=NodeArray[i];
                        
////如果该节点在nodeDatas里则初始化checked = true;
                        nodeData = cNode.getAttribute("NodeData");
                        
for(var j=0;j<nodeDatas.length;j++)
                        
{
                            
if(nodeDatas[j] == nodeData)
                            
{
                                cNode.setAttribute(
"checked","true");
                                
break;
                            }

                        }

                        
//如果有子节点,则继续递归
                        if(parseInt(cNode.getChildren().length)!=0)
                        findAndCheckedNodes(cNode.getChildren(),nodeDatas);    
                    }

                }

            }

            
            
//节点的oncheck事件
            function tree_oncheck(tree)
            
{
                
var node=tree.getTreeNode(tree.clickedNodeIndex);
                
var Pchecked=tree.getTreeNode(tree.clickedNodeIndex).getAttribute("checked");
                setcheck(node,Pchecked);
                document.all.checkedNodes.value
="";
                document.all.unchecked.value
="";
                FindCheckedFromNode(TreeView1);
            }

            
//设置子节点选中
            function setcheck(node,Pc)
            
{
                
var i;
                
var ChildNode=new Array();
                ChildNode
=node.getChildren();
                 
                
if(parseInt(ChildNode.length)==0)
                    
return;
                
else
                
{
                    
for(i=0;i<ChildNode.length;i++)
                    
{
                        
var cNode;
                        cNode
=ChildNode[i];
                        
if(parseInt(cNode.getChildren().length)!=0)
                            setcheck(cNode,Pc);
                        cNode.setAttribute(
"checked",Pc);
                    }

                }

            }

            
//获取所有节点状态
            function FindCheckedFromNode(node) 
            
{
                
var i = 0;
                
var nodes = new Array();
                nodes 
= node.getChildren();
                 
                
for (i = 0; i < nodes.length; i++
                
{
                    
var cNode;
                    cNode
=nodes[i];
                    
if (cNode.getAttribute("checked"))
                        AddChecked(cNode);
                    
else
                        AddUnChecked(cNode);
                      
                    
if (parseInt(cNode.getChildren().length) != 0 ) 
                    
{
                        FindCheckedFromNode(cNode);
                    }

                }

            }

            
//添加选中节点
            function AddChecked(node) 
            
{
                document.all.checkedNodes.value 
+= node.getAttribute("NodeData");
                document.all.checkedNodes.value 
+= ',';
            }

            
//添加未选中节点
            function AddUnChecked(node)
            
{
                document.all.unchecked.value 
+= node.getAttribute("NodeData");
                document.all.unchecked.value 
+= ',';
            }

            
        
</script>

    <body MS_POSITIONING="FlowLayout" onload="initchecknode()">
        
<form id="Form1" method="post" runat="server">
            
<FONT face="宋体">
                
<TABLE class="main" id="Table1">
                    
<TR>
                        
<TD></TD>
                        
<TD align="center" height="50">权限管理</TD>
                        
<TD></TD>
                    
</TR>
                    
<TR>
                        
<TD></TD>
                        
<TD>用户名:
                            
<asp:label id="lblUserName" runat="server">Label</asp:label></TD>
                        
<TD></TD>
                    
</TR>
                    
<TR>
                        
<TD></TD>
                        
<TD><iewc:treeview id="TreeView1" runat="server" ExpandLevel="1" SelectExpands="True" SystemImagesPath="/webctrl_client/1_0/treeimages/"
                                ImageUrl
="images/fclose.gif" SelectedImageUrl="images/bookmark.gif" ExpandedImageUrl="images/fopen.gif"
                                Target
="main" AutoSelect="True" wilth="100%"></iewc:treeview></TD>
                        
<TD></TD>
                    
</TR>
                    
<TR>
                        
<TD></TD>
                        
<TD align="center" height="50">
                            
<asp:button id="BtnSure" runat="server" Text="保存"></asp:button>&nbsp;
                        
</TD>
                        
<TD></TD>
                    
</TR>
                
</TABLE>
            
<INPUT id="checkedNodes" type="hidden" size="32" runat="server" NAME="checkedNodes"> <!--已经选择的节点每个节点间用","分隔.-->
            
<INPUT id="unchecked" type="hidden" size="32">
        
</form>
    
</body>

主要后台代码:




        
//数据访问实例
protected ClassConn connE = new ClassConn();

private void Page_Load(object sender, System.EventArgs e)
{
    
// 在此处放置用户代码以初始化页面
    if ( !IsPostBack)
    
{
        TreeView1.Attributes.Add(
"oncheck","tree_oncheck(this)");
        ViewState[
"UserId"= Request.QueryString["id"]+string.Empty;

        
//初始化用户名
        lblUserName.Text=connE.GetFieldValue("string","select name from EPM_EmployeeList where id = "+ViewState["UserId"].ToString());
        ViewState[
"dsTree"= connE.getDs("select * from EPM_DepartmentList where corpid="+Session["EnterpriseId"].ToString()+" and (type ="+Session["EnterpriseType"].ToString()+" or type=2)  and state=1 order by ShowIndex");
        connE.Close();
        
//初始化权限信息    
        InitData();


        
    }

}



/// <summary>
/// 初始化权限树.
/// </summary>
/// <param name="nFatherid">父节点的ID</param>
/// <param name="node"></param>

protected void initTree( int nFatherid,TreeNode fatherNode)
{
    DataSet ds 
= (DataSet)ViewState["dsTree"];
    DataView dv 
= new DataView(ds.Tables[0]);
    dv.RowFilter 
= "[parentDeptid] = "+nFatherid;
    
    
foreach ( DataRowView Row in dv )
    
{
        TreeNode node 
= new TreeNode();
        
if (fatherNode == null)//根节点
        {
            node.Text
=Row["name"].ToString();
            node.NodeData 
= Row["id"].ToString();
            node.CheckBox 
= true;
            
this.TreeView1.Nodes.Add(node);
            
//node.Expanded=false;//是否展开,若设置为true 则ExpandLevel="1" 无效
            initTree(Int32.Parse(Row["id"].ToString()),node);//递归
        }

        
else
        
{
            node.Text 
= Row["name"].ToString();
            node.NodeData 
= Row["id"].ToString();
            
//node.NavigateUrl = Row["url"].ToString();
            node.CheckBox = true;
            fatherNode.Nodes.Add(node);
            initTree(Int32.Parse(Row[
"id"].ToString()),node);//递归
        }

    }


}


/// <summary>
/// 设置权限的字符串,没个权限间用逗号分隔.
/// </summary>
/// <returns></returns>

private string  InitPowers()
{
    
string strPowers = string.Empty;
    
string strSql = "select id, DeptID from  EPM_PowerList where EMPid ="+ViewState["UserId"].ToString();
    SqlDataReader reader 
= connE.getDreader(strSql);
    
while(reader.Read())
    
{
        
if (strPowers.Length == 0)
        
{
            strPowers 
= reader[1].ToString();
        }

        
else
        
{
            strPowers 
+= ","+reader[1].ToString();
        }

    }

    reader.Close();
    
return strPowers;
}


/// <summary>
/// 初始化权限树
/// </summary>

private void InitData()
{
    
//获得权限字符串
    string strPowers = InitPowers();
    
//把权限字符串赋给checkedNodes.
    this.checkedNodes.Value = strPowers;
    
//初始化菜单树,使用递归调用.
    this.TreeView1.Nodes.Clear();
    initTree(
0,(TreeNode)null);
}




/// <summary>
/// 保存权限的设置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

private void BtnSure_Click(object sender, System.EventArgs e)
{
    
//先删除原来权限的设置
    string strSql = "delete from EPM_PowerList where empid="+ViewState["UserId"].ToString();
    connE.runSqlOnly(strSql);
    
//重新设置权限
    SaveTree();
    connE.Alert(
"保存成功!",Page);

    
//重新在服务器端初始权限信息
    InitData();
    
}


/// <summary>
/// 保存树中已选择的节点
/// </summary>


protected void SaveTree()
{
    
//获得所有已经选择的接点
    string strSelected = string.Empty;
    strSelected 
= this.checkedNodes.Value;
    
if(strSelected != string.Empty)
    
{
        strSelected 
= strSelected.Substring(0,strSelected.Length-1);
        
string [] strSelecteds  = strSelected.Split(',');
        
foreach(string str in strSelecteds)
        
{
            
string strSql = "insert EPM_PowerList (EMPid,deptid) values ('"+ViewState["UserId"].ToString()+"','"+str+"')";
            connE.runSqlOnly(strSql);
        }

    }

    
}


3.客户端操作TreeView带CheckBox的好例子(2)--选择子节点后自动选择父节点;取消子节点后根据情况的递归取消父节点。
把上面的tree_oncheck()修改一下,然后增加两个方法setParent()和checkBrother(),代码如下:

//节点的oncheck事件
function tree_oncheck(tree)
{
    
var node=tree.getTreeNode(tree.clickedNodeIndex);
    
var Pchecked=tree.getTreeNode(tree.clickedNodeIndex).getAttribute("checked");
    setcheck(node,Pchecked);
    setParent(node,Pchecked);
//如果是选择那么选择其父接点.
    document.all.checkedNodes.value="";
    document.all.unchecked.value
="";
    FindCheckedFromNode(TreeView1);
}


//设置子节点选中/取消;
//
同时需要设置父节点的状态(如果是取消选中的话,仅仅设置本节点及其所有字接点,不涉及父接点)
function setParent(node,Pc)
{
    
var parentNode = node.getParent();
    
if(parentNode)
    
{    
        
var parentNodeFather = parentNode.getParent();
        
if(parentNodeFather)
        
{
            setParent(parentNode,Pc);
        }

        
if(Pc)
            
{parentNode.setAttribute("checked",Pc);}
        
else
        
{
            checkBrother(parentNode,Pc,node.getAttribute(
"NodeData"))
        }

    }

}

//检查子接点是否有选择的,如果有一个选择了,那返回true
//
只查第一级节点.
function checkBrother(parentNode,Pc,nodeData)
{
    
var childNodes = new Array();
    childNodes 
= parentNode.getChildren();
    
if(childNodes.length >0)
    
{
        
var bChecked = true;
        
for(var i=0;i<childNodes.length;i++)
        
{
            
if(childNodes[i].getAttribute("checked"== true &&  childNodes[i].getAttribute("NodeData"!= nodeData)
            
{
                
//alert(i+childNodes[i].getAttribute("Text"));
                bChecked = false;
                
break;
            }

        }

        
if(bChecked)
        
{
            parentNode.setAttribute(
"checked",Pc);
        }

        
else
        
{
            
//所有父结点选择
            setParent(parentNode,!Pc)
        }

    }

    
else
    
{
        parentNode.setAttribute(
"checked",Pc);
    }

}



4.TreeView节点的精确定位问题(通过NodeData来定位)

    //Page_Load事件里根据NodeData来展开到到定位的节点
    
//这里是修改别人的(作者是根据Node的Text定位的.
    FindInTree2(Request.QueryString["selectedNodeData"].ToString());

    
//根据NodeDate寻找节点
    private void FindInTree2(string strNodeData)
    
{  
        
foreach (TreeNode tn in TreeView1.Nodes)            
        
{
            
if (tn.NodeData != strNodeData)
            
{   
                FindInTree2(tn,strNodeData);
            }
 
            
else
            
{   
                ExpandTree2(tn);
                
return;
            }

        }

    }

    
//根据NodeDate寻找节点
    private void FindInTree2(TreeNode objTreeNode,string strNodeData)
    
{   
        
foreach (TreeNode tn in objTreeNode.Nodes)            
        
{
            
if (tn.NodeData != strNodeData)
            
{

                FindInTree2(tn,strNodeData);
            }
 
            
else
            
{   
                ExpandTree2(tn);
                
return;
            }

        }

    }

    
//根据NodeDate展开节点
    private void ExpandTree2(TreeNode objTreeNode)
    
{   
        
string strIndex = "0";

        objTreeNode.Expanded 
= true;

        strIndex 
= objTreeNode.GetNodeIndex();

        
while (objTreeNode.Parent is TreeNode)
        
{
            objTreeNode 
= ((TreeNode)objTreeNode.Parent);
            objTreeNode.Expanded 
= true;                
        }


        TreeView1.SelectedNodeIndex 
= strIndex;
    }



5.asp.net 2.0里TreeView已经集成了,不需要单独安装了,但现在偶觉得,他只是换汤不换药,特别是在节点定位,和客户端操作上这两个关键问题上没啥改进.(偶没用过只是看了它的介绍.)

ASP.NET 2.0 的TreeView 控件介绍(转载)

TreeView客户端操作在这里啊~~~~~~~~~~~~
http://msdn.microsoft.com/library/default.asp?url=/workshop/webcontrols/behaviors/library/TreeView/TreeView.asp

http://www.microsoft.com/china/msdn/archives/library/workshop/webcontrols/overview/treeview.asp



1.下面的为转载:

1.下载地址
http://msdn.microsoft.com/downloads/samples/internet/ASP_DOT_NET_ServerControls/WebControls/default.asp
下载后是后缀为bat的版本
(1)bulid.将bulid.bat的路径指向csc.exe所在路径,生成Microsoft.Web.UI.WebControls.dll。
(2)在wwwroot下创建空目录webctrl_client\1_0。
(3)将build\Runtime下的文件拷至webctrl_client\1_0下。
(4)选择工具箱的自定义工具箱,添加Microsoft.Web.UI.WebControls.dll。
有些麻烦
但如果你能找到后缀是msi的自动安装版本,直接下一步就行(我一直用这个版本,hoho)
安装后,通过“自定义工具箱”->“.net框架组件”把TreeView添加到工具箱里

2.运行时无法显示
一般是TreeView的版本问题,最好下载英文版自动安装版本重新安装,安装前应该先到添加删除程序里卸掉原版本

3.显示格式出错(非树状显示)
TreeView要求客户端浏览器版本为IE5.5及以上,最好要求客户端升级为IE6.0

4.框架里使用TreeView
设置NavigateUrl、Target属性,可更新另外的Frame

5.找不到TreeNode类
使用TreeView,最好添加namespace:using Microsoft.Web.UI.WebControls;

6.遍历TreeView节点(递归算法)
private void Page_Load(object sender, System.EventArgs e)
{
 GetAllNodeText(TreeView1.Nodes);
}
void GetAllNodeText(TreeNodeCollection tnc)
{
 foreach(TreeNode node in tnc)
 {
  if(node.Nodes.Count!=0)
   GetAllNodeText(node.Nodes);
  Response.Write(node.Text + " ");
 }
}

7.得到node结点的父节点
TreeNode pnode;
if(node.Parent is TreeNode)
 pnode=(TreeNode)node.Parent;
else
 //node is root node

8.修改TreeView样式(示例)
<iewc:TreeView id="TreeView1" runat="server" HoverStyle="color:blue;background:#00ffCC;" DefaultStyle="background:red;color:yellow;" SelectedStyle="color:red;background:#00ff00;">
用代码:
TreeView1.DefaultStyle["font-size"] = "20pt";

9.展开时不提交,改变选择节点时才提交
将autopostback设置成false; 
在body里添加  <body  onload="initTree()"> 
然后在PageLoad里写: 
string  strTreeName  =  "TreeView1"; 
string  strRef  =  Page.GetPostBackEventReference(TreeView1); 
string  strScript  =  "<script  language=\"JavaScript\">  \n"  +  "<!--  \n"  +  "            function  initTree()  {  \n"  +"                        "  +  strTreeName  +  ".onSelectedIndexChange  =  function()  {  \n"  +    "if  (event.oldTreeNodeIndex  !=   
event.newTreeNodeIndex)  \n"  +  "this.queueEvent('onselectedindexchange',  event.oldTreeNodeIndex  +  ','  +  event.newTreeNodeIndex);  \n"  +    "window.setTimeout('"  +  strRef.Replace("'","\\'")    +  "',  0,  'JavaScript');  \n"  +    "                        }  \n"  +      "            }  \n"  +    "//  -->  \n"  +  "</script>"; 
Page.RegisterClientScriptBlock("InitTree",strScript  ); 
 
这样就只有你点击的节点更改的时候才提交!

10.TreeView结合XML
把XML文件设置为如下格式,然后直接设置TreeNodeSrc为该XML文件就行
<?xml version="1.0" encoding="GB2312"?>
<TREENODES>
 <TREENODE TEXT="node0" EXPANDED="true">
  <TREENODE TEXT="node1"/>
  <TREENODE TEXT="node2"/>
 </TREENODE>
 <TREENODE TEXT="node3" NavigateURL="3.aspx"/>
</TREENODES>
或者用代码
TreeView1.TreeNodeSrc="a.xml";
TreeView1.DataBind();

 11.请问,在页面加载时,如何选中Treeview某一节点?

index属性,是一个如1.1.0的东西,解析这个字符串,然后定位

private void ExpandNode(string selID)//selID like 1.1.0
{
 char[] mySplit = new char[]{'.'};
 string [] nodeArray = selID.Split(mySplit);

 TreeNode myNode = null;
 for(int i=0;i<nodeArray.Length;i++)
 {
  if(i==0)
   myNode = tree.Nodes[Convert.ToInt32(nodeArray[i])];
  else
   myNode = myNode.Nodes[Convert.ToInt32(nodeArray[i])];

  myNode.Expanded = true;  
  tree.SelectedNodeIndex = myNode.GetNodeIndex();
 }   
}

客户端控制TreeView
http://expert.csdn.net/Expert/topic/1382/1382892.xml

1.设置所选节点,如选中第二个节点
function SetSelNode()
{
 TreeView1.selectedNodeIndex="1";
}

2.得到所选节点的Text,ID或NodeData
function GetAttribute()
{
 alert(TreeView1.getTreeNode(TreeView1.selectedNodeIndex).getAttribute("Text"));
}
替换Text为ID或NodeData,可分别得到所选节点的ID或NodeData

3.修改节点属性,如修改第一个节点的Text
function ModifyNode()
{
 var node=TreeView1.getTreeNode("0");
 node.setAttribute("Text","hgknight");
}

4.得到点击节点
function TreeView1.onclick()
{
 alert(TreeView1.getTreeNode(TreeView1.clickedNodeIndex).getAttribute("Text"));
}

5.添加节点
function AddNode()
{
 var node=TreeView1.createTreeNode();
 node.setAttribute("Text","hgknight");
 TreeView1.add(node);   
}

6.js遍历所有节点
 var AllRootNode=new Array();
 AllRootNode=TreeView1.getChildren();
 AlertNode(AllRootNode);  

 function AlertNode(NodeArray)
 {
  if(parseInt(NodeArray.length)==0)
   return;
  else
  {
   for(i=0;i<NodeArray.length;i++)
   {
    var cNode;
    cNode=NodeArray[i];
    alert(cNode.getAttribute("Text"));
    if(parseInt(cNode.getChildren().length)!=0)
     AlertNode(cNode.getChildren());   
   }
  }
 }

--------------------------------------------------------------------------------------------------------------------------------------------------------

<iewc:treeview id="TreeView1" runat="server" wilth="100%" AutoSelect="True" BorderWidth="2px" Target="main"
ExpandedImageUrl="images/fopen.gif" SelectedImageUrl="images/bookmark.gif" ImageUrl="images/fclose.gif"
BorderColor="AliceBlue" BackColor="#ffffcc" SystemImagesPath="../webctrl_client/1_0/treeimages/"
SelectExpands="True" ExpandLevel="1"></iewc:treeview>
-----------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Microsoft.Web.UI.WebControls;
namespace aspnetc.admin
{
/// <summary>
/// left 的摘要说明。
/// </summary>
public class left : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label lblName;
protected Microsoft.Web.UI.WebControls.TreeView TreeView1;
protected System.Web.UI.WebControls.HyperLink hlkLogOut;
protected System.Web.UI.WebControls.Label Label2;

ClassConn connE = new ClassConn();

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if (!IsPostBack)
{
lblName.Text=Session["userName"]!=null ? Session["userName"].ToString():string.Empty;
try
{
//添加命令,从数据库中得到数据
SqlDataAdapter ada = new SqlDataAdapter("select * from menues where state=1 order by sortIndex",connE.GetConn());
DataSet ds=new DataSet();
ada.Fill(ds);
this.ViewState["ds"]=ds;
}
catch (Exception ex)
{
throw (ex);  
}
finally
{
connE.Close();
}
//调用递归函数,完成树形结构的生成
AddTree(0, (TreeNode)null);
}
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{   
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

/// <summary>
///  递归添加树的节点
/// </summary>
/// <param name="ParentID"></param>
/// <param name="pNode"></param>
public void AddTree(int ParentID,TreeNode pNode)
{
DataSet ds=(DataSet) this.ViewState["ds"];
DataView dvTree = new DataView(ds.Tables[0]);
//过滤ParentID,得到当前的所有子节点
dvTree.RowFilter =  "[parentId] = " + ParentID;

foreach(DataRowView Row in dvTree)
{
TreeNode Node=new TreeNode() ;
if(pNode == null)
{    //添加根节点
Node.Text = Row["name"].ToString();
TreeView1.Nodes.Add(Node);
//Node.Expanded=false;//是否展开若设置为true 则ExpandLevel="1"无效
AddTree(Int32.Parse(Row["ID"].ToString()), Node);    //再次递归
}
else

if(4>3)
{
//添加当前节点的子节点
Node.Text = Row["name"].ToString();
//Node.Target = mainFrame;
Node.NavigateUrl = Row["url"].ToString();
pNode.Nodes.Add(Node);
//Node.Expanded = false;
AddTree(Int32.Parse(Row["ID"].ToString()),Node);     //再次递归
}
}
}                  
}           
   

}
}
----------------------------------------------------------------------------------------------------------------------------------------

http://www.microsoft.com/china/MSDN/library/archives/library/DNAspp/html/aspnet-usingtreeviewieWebcontrol.asp


 IEWebControl TreeView右键菜单实例     选择自 hgknight 的 Blog

一个IEWebControl TreeView右键菜单的例子,实现了添加、修改和删除功能,复制即可运行
更多TreeView的客户端操作参见
http://www.csdn.net/Develop/read_article.asp?id=22100

<%@ Register TagPrefix="iewc" Namespace="Microsoft.Web.UI.WebControls" Assembly="Microsoft.Web.UI.WebControls, Version=1.0.2.226, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<HTML>
 <HEAD>
  <title>TreeView控件右键菜单</title>
  <style>
  <!--
   .skin
   {
   cursor:default;
   font:menutext;
   position:absolute;
   text-align:left;
   font-family: Arial, Helvetica, sans-serif;
   font-size: 10pt;
   width:120px;
   background-color:menu;
   border:1 solid buttonface;
   visibility:hidden;
   border:2 outset buttonhighlight;
   }
   .menuitems
   {
   padding-left:15px;
   padding-right:10px;
   }
   -->
  </style>
 </HEAD>
 <body onclick="hideMenu()">
  <form id="TreeView" method="post" runat="server">
   <iewc:TreeView id="TreeView1" runat="server" ExpandLevel="3" HoverStyle="color:blue;background:#ffff00;">
    <iewc:TreeNode Text="Node0" Expanded="True">
     <iewc:TreeNode Text="Node3">
      <iewc:TreeNode Text="Node5"></iewc:TreeNode>
      <iewc:TreeNode Text="Node6"></iewc:TreeNode>
     </iewc:TreeNode>
     <iewc:TreeNode Text="Node4"></iewc:TreeNode>
    </iewc:TreeNode>
    <iewc:TreeNode Text="Node1" Expanded="True">
     <iewc:TreeNode Text="Node7">
      <iewc:TreeNode Text="Node8"></iewc:TreeNode>
     </iewc:TreeNode>
    </iewc:TreeNode>
    <iewc:TreeNode Text="Node2" Expanded="True">
     <iewc:TreeNode Text="Node9"></iewc:TreeNode>
     <iewc:TreeNode Text="Node10">
      <iewc:TreeNode Text="Node11"></iewc:TreeNode>
      <iewc:TreeNode Text="Node12"></iewc:TreeNode>
     </iewc:TreeNode>
    </iewc:TreeNode>
   </iewc:TreeView>
   <div id="popupMenu" class="skin" onMouseover="highlighItem()" onMouseout="lowlightItem()" onClick="clickItem()">
    <div class="menuitems" func="add">添加</div>
    <hr>
    <div class="menuitems" func="delete">删除</div>
    <div class="menuitems" func="modify">修改</div>
   </div>
  </form>
  <script language="javascript">
   var menuskin = "skin";
   var node = null;

   function hideMenu()
   {
    popupMenu.style.visibility = "hidden";
   }

   function highlighItem()
   {
    if (event.srcElement.className == "menuitems")
    {
     event.srcElement.style.backgroundColor = "highlight";
     event.srcElement.style.color = "white";
    }
   }

   function lowlightItem()
   {
    if (event.srcElement.className == "menuitems")
    {
     event.srcElement.style.backgroundColor = "";
     event.srcElement.style.color = "black";
     window.status = "";
    }
   }

   function clickItem()
   {    
    if (event.srcElement.className == "menuitems")
    {
     if(event.srcElement.getAttribute("func") == "add" && node != null)
     {
      var newNode=TreeView1.createTreeNode();
      newNode.setAttribute("Text","new Node");
      node.add(newNode);
     }
     else if (event.srcElement.getAttribute("func") == "delete" && node != null)
     {
      node.remove();
     }
     else if (event.srcElement.getAttribute("func") == "modify" && node != null)
     {
      node.setAttribute("Text","hgknight");
     }
    }
   }
   
   function TreeView1.oncontextmenu()
   {
    var nodeindex = event.treeNodeIndex;
    if (typeof(nodeindex) == "undefined")
    {
     node = null;
     return;
    }
    
    node = TreeView1.getTreeNode(nodeindex);
    
    var rightedge = document.body.clientWidth-event.clientX;
    var bottomedge = document.body.clientHeight-event.clientY;
    if (rightedge <popupMenu.offsetWidth)
    {
     popupMenu.style.left = document.body.scrollLeft + event.clientX - popupMenu.offsetWidth;
    }
    else
    {
     popupMenu.style.left = document.body.scrollLeft + event.clientX;
    }
    if (bottomedge <popupMenu.offsetHeight)
    {
     popupMenu.style.top = document.body.scrollTop + event.clientY - popupMenu.offsetHeight;
    }
    else
    {
     popupMenu.style.top = document.body.scrollTop + event.clientY;
    }
    popupMenu.style.visibility = "visible";
    return false;
   } 
   
  </script>
 </body>
</HTML>
-----------------------------------------------------------------------------
服务器端选择一节点下所有子节点(先选择再CHECK,麻烦)
private void TreeView1_Check(object sender, Microsoft.Web.UI.WebControls.TreeViewClickEventArgs e)
  {
   Microsoft.Web.UI.WebControls.TreeNode node=TreeView1.GetNodeFromIndex(TreeView1.SelectedNodeIndex.ToString());
   //connE.Alert(node.NodeData.ToString(),Page);
   SetAllNodeData(node.Nodes);
  }

  private void  SetAllNodeData(TreeNodeCollection tnc)
  { 
   
   foreach(TreeNode node in tnc)
   {
    if(node.Nodes.Count!=0)
    {
     SetAllNodeData(node.Nodes);
    }
    if (node.Checked)
    {
     node.Checked = false;
    }
    else
    {
     node.Checked = true;
    }
 
   }
  }

Microsfot.Web.UI.WebControls.TreeView JavaScript控制方法研究
http://caidaoli.cnblogs.com/archive/2005/02/23/108317.html?Pending=true#Post

  1. 被选择的节点的索引:
    tree.selectedNodeIndex

  2. 被单击的节点的索引:
    tree.clickedNodeIndex

  3. 获取一个节点:
    tree.getTreeNode(nodeIndex)

  4. 在根节点下增加一个子节点:
    var tree = document.all['TreeView1'];
    var node = tree.createTreeNode() ;
    tree.add(node);
    node.setAttribute( "text", "aaaa");

  5. 在当前节点下增加一个子节点:
    var tree = document.all['TreeView1'];
    var node = tree.createTreeNode() ;
    var parentNode = tree.getTreeNode( tree.clickedNodeIndex);
    parentNode.add(node);
    node.setAttribute( "text", "aaaa");

  6. 通过XML文件来增加子节点:
    node.setAttribute("NavigateUrl","xxx");
    node.databind();
  7. 动态增加子节点后自动展开:
    node.setAttribute('expanded', 'true');//MS提供的HTC中需要修改一个地方,否则就会产生一个异常
  8. 获取节点的属性:
    node.getAttribute("xxx")
  9. 设置节点的属性 :
    node.setAttribute('xxx', 'xxxx');
    1. 常用属性列表:
    1. 属性
    含义
    CheckBox True False 是否有选择框
    checked True False 选择框是否被选中
    Expanded True False 是否展开
    ImageURL   正常状态下左边的图标
    SelectedImageUrl   当节点被选择时左边的图标
    ExpandedImageUrl   当节点被展开后左边的图标
    Target   目标框架
    navigateurl   目标URL
    type   节点的类型
    childtype   子节点的类型
    Text   节点显示的文本
    innerText    
    innerHTML    
    defaultstyle   默认的风格
    hoverstyle   当鼠标移到节点的上面时的风格
    selectedstyle   当节点被选择时的风格
    treenodesrc    
    1. 获取父节点:
      node.getParent()
    2. 获取子节点:
      node.getChildren()
    3. 判断节点是否有子节点
      node.getChildren().length > 0
    4. 响应onselectedindexchange事件:
      var tree = document.all["tvMain"];
      tree.attachEvent("onselectedindexchange", SelectedIndexChange);

  • posted on 2005-09-13 09:46  猪头  阅读(12829)  评论(9编辑  收藏  举报

    欢迎访问诗词在线http://www.chinapoesy.com   诗词在线 |唐诗|宋词|元曲|诗经|离骚|乐府|古典诗歌|现代诗歌|古典诗词|现代诗词|诗歌可以陶冶你的情操、丰富你的生活,让你更具内涵。诗词在线打造中国最好的诗词社区!

    诗词在线社区

    126在线阅读网 历史书籍、文学书籍、小说。。。