VS.Net TreeView控件的使用
- -
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
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;
using System.Data.OracleClient;
using System.Text;
using System.Xml;
namespace WebApp
{
/// <summary>
/// 用户权限管理示例程序
/// </summary>
public class Tree : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.Button Button1;
protected Microsoft.Web.UI.WebControls.TreeView tvUser;
protected Microsoft.Web.UI.WebControls.TreeView tvRights;
protected System.Web.UI.WebControls.Button Button3;
protected System.Web.UI.WebControls.Button Button4;
protected System.Web.UI.WebControls.Button Button2;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!Page.IsPostBack)
{
this.InitTree();
}
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Button2.Click += new System.EventHandler(this.Button2_Click);
this.Button3.Click += new System.EventHandler(this.Button3_Click);
this.tvUser.SelectedIndexChange += new Microsoft.Web.UI.WebControls.SelectEventHandler(this.tvUser_SelectedIndexChange);
this.tvRights.Check += new Microsoft.Web.UI.WebControls.ClickEventHandler(this.tvRights_Check);
this.Button4.Click += new System.EventHandler(this.Button4_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void InitTree()
{
//RightsTree
OracleConnection conn = new OracleConnection("User ID = klmtsy4;PassWord=klmtsy4;Data Source=ORCL;");
DataSet ds = new DataSet("Rights");
OracleDataAdapter da = new OracleDataAdapter("select RightsID,RightsName,Parent as ParentID,HasChild from t_Rights",conn);
conn.Open();
da.Fill(ds,"Rights");
conn.Close();
this.tvRights.Nodes.Clear();
TreeNode root = new TreeNode();
root.Text="功能";
root.CheckBox = true;
root.Expanded = true;
this.tvRights.Nodes.AddAt(0,root);
this.CreateTree(ds.Tables["Rights"],root,"ParentID","0","RightsID","RightsName",true);
/*
DataRow[] arrayRow = ds.Tables["Rights"].Select("ParentID='0'");
foreach(DataRow row in arrayRow)
{
TreeNode node = new TreeNode();
node.Text = row["RightsID"].ToString().Trim()+"["+row["RightsName"].ToString().Trim()+"]";
node.NodeData=row["RightsID"].ToString().Trim();
node.CheckBox = true;
node.Expanded = true;
this.tvRights.Nodes[0].Nodes.Add(node);
this.CreateTree(ds.Tables["Rights"],node,"ParentID",node.NodeData.ToString(),"RightsID","RightsName",true);
}
*/
//User Tree
string sql = @"select t.* from
(select u.UserID as RoleID,u.UserName as RoleName,g.GrpID as ParentID from t_User u,t_Group g where u.GrpID = g.GrpID
union
select g.GrpID as RoleID,g.GrpName as RoleName,'0' as ParentID from t_Group g
)t
order by t.RoleID";
OracleDataAdapter daUser = new OracleDataAdapter(sql,conn);
conn.Open();
daUser.Fill(ds,"User");
conn.Close();
this.tvUser.Nodes.Clear();
TreeNode rootUser = new TreeNode();
rootUser.Text="人员";
rootUser.Expanded = true;
this.tvUser.Nodes.AddAt(0,rootUser);
this.CreateTree(ds.Tables["User"],rootUser,"ParentID","0","RoleID","RoleName",false);
/*
DataRow[] arrayRowUser = ds.Tables["User"].Select("ParentID='0'");
foreach(DataRow row in arrayRowUser)
{
TreeNode node = new TreeNode();
node.Text = row["RoleID"].ToString().Trim()+"["+row["RoleName"].ToString().Trim()+"]";
node.NodeData=row["RoleID"].ToString().Trim();
node.Expanded = true;
this.tvUser.Nodes[0].Nodes.Add(node);
this.CreateTree(ds.Tables["User"],node,"ParentID",node.NodeData.ToString(),"RoleID","RoleName",false);
}
*/
//选定某个用户
tvUser.Nodes[0].Expanded = true;
string index = "0.3";
tvUser.SelectedNodeIndex = index;
}
/// <summary>
/// 根据Field,Value 查找Table ,得到叶子数据
/// </summary>
/// <param name="table">总体数据集</param>
/// <param name="toot">根节点</param>
/// <param name="searchField">查找字段名称</param>
/// <param name="parentValue">父节点SearchField字段之值</param>
/// <param name="textField">树中节点的文本字段</param>
/// <param name="valueField">树中节点的值字段</param>
/// <param name="hasCheckBox">是否带有CheckBox</param>
private void CreateTree(DataTable table,TreeNode root,string searchField,string parentValue,string valueField,string textField,bool hasCheckBox)
{
DataRow[] arrayRow = table.Select(searchField+"='"+parentValue+"'");
foreach(DataRow row in arrayRow)
{
TreeNode node = new TreeNode();
node.Text = row[valueField].ToString().Trim()+"["+row[textField].ToString().Trim()+"]";
node.NodeData = row[valueField].ToString().Trim();
node.CheckBox = hasCheckBox;
node.Expanded = true;
root.Nodes.Add(node);
this.CreateTree(table,node,searchField,node.NodeData.ToString(),valueField,textField,hasCheckBox);
}
}
private void tvUser_SelectedIndexChange(object sender, Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs e)
{
//this.TextBox1.Text = e.NewNode.Length.ToString();
this.TextBox1.Text = tvUser.SelectedNodeIndex+tvUser.GetNodeFromIndex(tvUser.SelectedNodeIndex).Text;
string RoleID = tvUser.GetNodeFromIndex(tvUser.SelectedNodeIndex).NodeData.ToString();
this.SelsectRole(RoleID);
}
private void SelsectRole(string roleID)
{
//Get Rights of Role
OracleConnection conn = new OracleConnection("User ID = klmtsy4;PassWord=klmtsy4;Data Source=ORCL;");
DataSet ds = new DataSet("UserRights");
OracleDataAdapter da = new OracleDataAdapter("select * from t_UserRights",conn);
conn.Open();
da.Fill(ds,"UserRights");
conn.Close();
//Clear CheckedItem
this.ClearChecked(tvRights.Nodes[0]);
//Check the Item Of Rights Tree
this.CheckNode(ds.Tables["UserRights"],tvRights.Nodes[0],"UserID",roleID,"RightsID");
}
/// <summary>
/// 清除根节点及其子孙的Checked状态
/// </summary>
/// <param name="root">根节点</param>
private void ClearChecked(TreeNode root)
{
root.Checked = false;
foreach(TreeNode node in root.Nodes)
{
//node.Checked = false;
ClearChecked(node);
}
}
/// <summary>
/// 设置节点的父辈及其祖辈节点的Checked状态
/// </summary>
/// <param name="node">节点</param>
/// <param name="isChecked">是否被Checked</param>
private void CheckParent(TreeNode node,bool isChecked)
{
//必须用Node.Parent is TreeNode 来判断
if(node.Parent is TreeNode)
{
TreeNode parent = new TreeNode();
parent = (TreeNode)node.Parent;
parent.Checked = isChecked;
//如果节点有子节点被Checked,其也被Checked
foreach(TreeNode nodeChild in parent.Nodes)
{
if(nodeChild.Checked){parent.Checked=true;break;}
}
CheckParent(parent,isChecked);
}
}
/// <summary>
/// 设定根节点的子孙节点的Checked状态
/// </summary>
/// <param name="node">根节点</param>
/// <param name="isChecked">是否被Checked</param>
private void CheckChild(TreeNode node,bool isChecked)
{
foreach(TreeNode nodeChild in node.Nodes)
{
nodeChild.Checked = isChecked;
CheckChild(nodeChild,isChecked);
}
}
/// <summary>
/// 根据选定的人员/组,检查根节点的子孙节点,并更新Checked状态
/// </summary>
/// <param name="table">包含选定人员/组对应的数据集</param>
/// <param name="root">根节点</param>
/// <param name="filterField">过滤字段</param>
/// <param name="filterValue">过滤字段值</param>
/// <param name="valueField">要根据过滤条件查找的结果字段</param>
private void CheckNode(DataTable table,TreeNode root,string filterField,string filterValue,string valueField)
{
DataRow[] arrayRow = table.Select(filterField+"='"+filterValue+"'");
foreach(DataRow row in arrayRow)
{
foreach(TreeNode node in root.Nodes)
{
if(node.NodeData.Equals(row[valueField].ToString().Trim()))
{
node.Checked = true;
this.CheckParent(node,true);
this.CheckNode(table,node,filterField,filterValue,valueField);
}
}
}
}
private void Button1_Click(object sender, System.EventArgs e)
{
TreeNode nodeSelected = new TreeNode();
TreeNode node = new TreeNode();
string index = this.tvUser.SelectedNodeIndex;
if(index.Length.Equals(1))
{
node.Text = this.TextBox1.Text;
tvUser.Nodes.Add(node);
}
else
{
nodeSelected = tvUser.GetNodeFromIndex(index);
TreeNode parent = (TreeNode)nodeSelected.Parent;
node.Text = this.TextBox1.Text;
parent.Nodes.Add(node);
}
}
private void Button2_Click(object sender, System.EventArgs e)
{
TreeNode parent = new TreeNode();
TreeNode node = new TreeNode();
string index = this.tvUser.SelectedNodeIndex;
parent = tvUser.GetNodeFromIndex(index);
node.Text = this.TextBox1.Text;
parent.Nodes.Add(node);
}
private void Button3_Click(object sender, System.EventArgs e)
{
this.TextBox1.Text = tvRights.Nodes[0].Nodes[0].Text;
this.CheckParent(tvRights.Nodes[0].Nodes[0],true);
}
private void tvRights_Check(object sender, Microsoft.Web.UI.WebControls.TreeViewClickEventArgs e)
{
string index = e.Node;
TreeNode nodeSelected = new TreeNode();
nodeSelected = tvRights.GetNodeFromIndex(index);
this.CheckChild(nodeSelected,nodeSelected.Checked);
this.CheckParent(nodeSelected,nodeSelected.Checked);
}
private void Button4_Click(object sender, System.EventArgs e)
{
//得到 UserID
string index = tvUser.SelectedNodeIndex;
int iLevel = index.Split('.').Length-2;
if(iLevel<0)return;
string UserID = tvUser.GetNodeFromIndex(index).NodeData;
//遍历tvRights,得到权限组合
StringBuilder sb = new StringBuilder("<root>");
sb.Append("<RoleID>"+UserID+"</RoleID>");
sb.Append("<RoleType>"+iLevel.ToString()+"</RoleType>");
this.GetCheckedValue(sb,"RightsID",tvRights.Nodes[0]);
sb.Append("</root>");
//调用数据服务层,提交数据
string xmlData = sb.ToString();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlData);
//声明数据库操作类
OracleConnection conn = new OracleConnection("User ID = klmtsy4;PassWord=klmtsy4;Data Source=ORCL;");
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.Connection.Open();
OracleTransaction theTrans = conn.BeginTransaction();
cmd.Transaction = theTrans;
string sql = "";
try
{
XmlNode xn = xmlDoc.SelectSingleNode(@"//RoleID");
string RoleID = xn.InnerText;
xn = xmlDoc.SelectSingleNode(@"//RoleType");
string RoleType = xn.InnerText;
//删除用户的权限
sql = @"delete from t_RoleRights where RoleID='"+RoleID+"'";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
XmlNodeList xnl = xmlDoc.SelectNodes(@"//RightsID");
foreach(XmlNode node in xnl)
{
sql = @"insert into t_RoleRights values('"+RoleID+"','"+node.InnerText+"','"+RoleType+"')";
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
cmd.Transaction.Commit();
cmd.Connection.Close();
}
catch
{
cmd.Transaction.Rollback();
cmd.Connection.Close();
}
}
private void GetCheckedValue(StringBuilder sbItem,string strElement,TreeNode root)
{
foreach(TreeNode node in root.Nodes)
{
if(node.Checked)
{
sbItem.Append("<"+strElement+">"+node.NodeData+"</"+strElement+">");
}
GetCheckedValue(sbItem,strElement,node);
}
}
}
}
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();
客户端控制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());
}
}
}