c#语言asp.net实现treeview控件

时间:2021-10-31 19:47:07

 

 

从数据库里读数据就不写了吧?假设你得到了一个存放数据实体数组叫emps[],里面放的全是emp实体.

                foreach (Emp item in emps)

                {

                    TreeNode pNode = new TreeNode();

                    if (item.ParentNodeId == 0)//父节点

                    {

                        pNode.Text = item.DisplayName;

                        pNode.Value = item.NodeId.ToString();

                        tvSide.Nodes.Add(pNode);

                    }//tvSideTreeViewID

                    else

                    {

                        TreeNode cNode=new TreeNode (item.DisplayName,item.NodeId.ToString());

                        foreach (TreeNode node in tvSide.Nodes)

                        {

                            if (item.ParentNodeId.ToString() == node.Value)

                                node.ChildNodes.Add(cNode);

                        }

                    }

                }

 

或者下面的方式

string strSql = "select id,name from groupinfo order by id";

        SqlDataAdapter sda = new SqlDataAdapter(strSql, strconn);

        sda.Fill(dtGroup);

        sda.Dispose();

 

        for (int i = 0; i < dtGroup.Rows.Count; i++)

        {

            treeNode = new TreeNode(dtGroup.Rows[i]["name"].ToString(), dtGroup.Rows[i]["id"].ToString());

            TreeView1.Nodes.Add(treeNode);

        }

 

        foreach (TreeNode node in TreeView1.Nodes)

        {

            dtName=new DataTable();

            string strSql1 = "select id,name,imgurl,jobs,groupid from PersonInfo where groupid='"+node.Value.ToString()+"' order by id";

            SqlDataAdapter sda1 = new SqlDataAdapter(strSql1, strconn);

            sda1.Fill(dtName);

            sda1.Dispose();

          

            if (dtName == null || dtName.Rows.Count == 0)

            { }

            else

            {

                for (int j = 0; j < dtName.Rows.Count; j++)

                {

                    TreeNode treenode1 = new TreeNode(dtName.Rows[j]["name"].ToString(), dtName.Rows[j]["id"].ToString());

                    node.ChildNodes.Add(treenode1);

                }

            }

        }

 

 

试试这个:(这种方式效率更高)

 

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack) buildTree();

}

 

private void buildTree()

{

ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["ID"], ds.Tables[0].Columns["ParentID"]);

 

foreach (DataRow dbRow in ds.Tables[0].Rows)

{

if ((int)dbRow["ParentID"]==0)

{

 

TreeNode newNode = CreateNode(dbRow["ID"].ToString(), dbRow["Context"].ToString());

TreeView1.Nodes.Add(newNode);

PopulateSubTree(dbRow, newNode);

}

}

}

 

private void PopulateSubTree(DataRow dbRow, TreeNode node)

{

foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))

{

TreeNode childNode = CreateNode(childRow["ID"].ToString(), childRow["Context"].ToString());

node.ChildNodes.Add(childNode);

PopulateSubTree(childRow, childNode);

}

}

 

private TreeNode CreateNode(string nodeID, string text)

{

TreeNode node = new TreeNode();

node.Value = nodeID;

node.Text = text;

return node;

}

 

 

 

 

来自csdn上面的例子我试过可以

1.下载地址

http://msdn.microsoft.com/downloads/samples/internet/ASP_DOT_NET_ServerControls/WebControls/default.asp

安装后,通过自定义工具箱”->“.net框架组件TreeView添加到工具箱里

2.运行时无法显示

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

 

3.显示格式出错(非树状显示)

TreeView要求客户端浏览器版本为IE5.5及以上,最好要求客户端升级为IE6.0

 

4.框架里使用TreeView

设置NavigateUrlTarget属性,可更新另外的Frame

 

5.找不到TreeNode

使用TreeView,最好添加namespaceusing 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.TreeView展开无闪烁的解决方法

http://expert.csdn.net/Expert/topic/1300/1300576.xml

 

客户端控制TreeView

http://expert.csdn.net/Expert/topic/1382/1382892.xml

 

1.设置所选节点,如选中第二个节点

function SetSelNode()

{

TreeView1.selectedNodeIndex="1";

}

 

2.得到所选节点的TextIDNodeData

function GetAttribute()

{

alert(TreeView1.getTreeNode(TreeView1.selectedNodeIndex).getAttribute("Text"));

}

替换TextIDNodeData,可分别得到所选节点的IDNodeData

 

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 NodeArray=new Array();

NodeArray=TreeView1.getChildren();

for(i=0;i<NodeArray.length;i++)

{

cNode=NodeArray[i];

alert(cNode.getAttribute("Text"));

}

 

 

1、用代码在treeview web控件中,添加node的方法

 

表字段:编号,父编号,名称

数据:

1 0 *

2 1 湖南

3 1 湖北

 

void creattree(string text,TreeNode tnd,string pid)

{

 

TreeNode t2=new TreeNode();

t2.Text=text;

 

tnd.Nodes.Add(t2);

 

生成

string str1 ="父编号 = '"+pid+"'";

DataRow[] dryl = dataSet31.Tables [0].Select(str1);

 

for(int i=0;i<=dryl.GetUpperBound(0);i++)

{

 

creattree(dryl[i][2].ToString(),t2,dryl[i][0].ToString());

}

}

 

 

//

TreeNode t1=new TreeNode();

t1.Text="地区信息";

TreeView2.Nodes.Add(t1);

 

creattree("*",t1,"1");

 

 

2、如何为TreeView添加事件?

 

Private Sub TreeView1_indexChanged(ByVal sender As Object, ByVal e As

Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs) Handles

TreeView1.SelectedIndexChange

Dim a As Integer

a = TreeView1.SelectedNodeIndex

TextBox1.Text = CStr(a)

End Sub

但是AutoPostBack设置为True的话,TreeView还要刷新,闪烁,我的TreeView比较庞大

,这可怎么办???苦恼中。。。

 

3、为什么TreeView 中的SelectedIndexChange为什么不执行???

 

AutoPostBack属性为真,SelectedIndexChange才能被执行。

不过这样的话你选择时会感到刷新得让你痛苦,根据你的具体实现的目的,采用变通的

方法,尽量不使用SelectedIndexChange事件吧。

 

 

selectedindexchange事件挂到控件上没有?

InitializeComponent方法中检查检查

 

4、如何判断 TreeView 的一个节点下是否有子节点???

 

if(selNode.Nodes.Count==0){

//该节点没有字节点

}

 

5、如何得到 TreeView 的当前选择节点???

 

1.Tree.GetNodeFromIndex(Tree.SelectedNodeIndex.ToString())

2.private void TreeView1_SelectedIndexChange(object sender,

Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs e)

e.NewNode即为所选节点

 

6treeview实现两层节点没问题,扩展到无限层就出问题了?

 

我的那个做法还不够完善,对于节点数较少的情况可以这样做,对于节点数较多的情况

,你就不能这样做了,你应该只加载一级,当点击节点展开时,再加载它的下一级子节

点。

数据库结构如下:

表名:Table1

ParentID varchar 20:父节点

ID varchar 20:节点

Name varchar 50:名称

 

来来来,这里给你个例程,再给个我的网页上的TreeViwe看看,一万个子节点都没问题。

http://dev1.eraserver.net/czc888/webform1.aspx

至于那三个图象的意义你看我的网页就知道了。分别表示一页纸(没有子节点)、一本

关闭的书(有子节点),一本打开的书(当前节点被展开)

 

void creat_node(string

name,Microsoft.Web.UI.WebControls.TreeNode t1,string number)

{

//定义一个新的结点

 

Microsoft.Web.UI.WebControls.TreeNode t2=new

Microsoft.Web.UI.WebControls.TreeNode();

t2.ID=number;

t2.Text=name;

 

 

//判断是否为根结点

TreeView1.ExpandedImageUrl="images/Depart03.bmp";

if(t1.ID.Trim()=="###")

{

TreeView1.Nodes.Add(t2);

t2.ImageUrl="images/Depart01.bmp";

}

else

{

t1.Nodes.Add(t2);

t2.ImageUrl="images/Depart01.bmp";

t1.ImageUrl="images/Depart02.bmp";

}

 

 

//取得这个结点的所有子结点,利用递归自动生成

string mySelectQuery = "SELECT ParentID, ID,Name FROM table1

where ParentID='" + number +"'";

string MyConnString="provider=Microsoft.Jet.OLEDB.4.0;Data

Source="+Server.MapPath(".")+"/dt/mydata.mdb";

OleDbConnection myConnection = new

OleDbConnection(MyConnString);

OleDbCommand myCommand = new

OleDbCommand(mySelectQuery,myConnection);

myConnection.Open();

OleDbDataReader myReader;

myReader = myCommand.ExecuteReader();

while (myReader.Read())

{

creat_node(myReader.GetString(2),t2,myReader.GetString(1));

 

}

myReader.Close();

myConnection.Close();

 

}

 

private void CreateProviderTreeBtn_Click(object sender,

System.EventArgs e)

{

Microsoft.Web.UI.WebControls.TreeNode t1=new

Microsoft.Web.UI.WebControls.TreeNode();

creat_node("",t1,"###");

 

 

7、怎样使用TreeView???

 

//初始化TreeView数据

private void InitTV(int intVOrderLen)

{

SqlDataReader dr;

SqlCommand myCommand;

string strSel = "select * from bas_enterprise where

len(vieworder)="+intVOrderLen+" order by vieworder";

myCommand = new SqlCommand (strSel, myConnection);

dr=myCommand.ExecuteReader();

while (dr.Read ())

{

TreeNode pNode=new TreeNode ();

pNode.Text =dr["EntpName"].ToString ();

pNode.ID =dr["ViewOrder"].ToString ();

TreeView1.Nodes .Add (pNode);

 

}

dr.Close ();

 

}

 

 

private void TreeView1_SelectedIndexChange(object sender,

Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs e)

{

TreeNode NewNode=TreeView1.GetNodeFromIndex

(TreeView1.SelectedNodeIndex);

string strNodeId=NewNode.ID .ToString ();

SqlDataReader dr;

SqlCommand myCommand;

int intVOrderLen=strNodeId.Length+2;

string strSel = "select * from bas_enterprise where

len(vieworder)="+intVOrderLen+" and vieworder like '%"+strNodeId+"__%'

order by vieworder";

myCommand = new SqlCommand (strSel, myConnection);

dr=myCommand.ExecuteReader();

NewNode.Nodes .Clear();

while (dr.Read ())

{

TreeNode pNode=new TreeNode ();

pNode.Text =dr["EntpName"].ToString ();

pNode.ID =dr["ViewOrder"].ToString ();

NewNode.Nodes.Add (pNode);

}

dr.Close ();

TreeView1.ExpandLevel=1;

}

 

 

8、在treeview中如何查找一个值,并选中它?

 

问题:

各位,在已经建好的树中如何查找一个文本或者是treenodesid,找到后选中它?

 

答案:

for(int i=0;i<TreeView1.Nodes.Count;i++)

if(TreeView1.Nodes[i]==TextBox1.Text)

{

string index1=TreeView1.Nodes[i].GetNodeIndex();//取得index

TreeView1.SelectedNodeIndex=index1;

    }

 

9、如何取得TreeView中各项的值??

 

private void TreeView1_SelectedIndexChange(object sender,

Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs e)

{

Microsoft.Web.UI.WebControls.TreeNode

NewNode=TreeView1.GetNodeFromIndex(TreeView1.SelectedNodeIndex);

Label1.Text =NewNo

 

 

如果通过代码要在父结点中增加子节点,代码如何实现?

父节点代码如下:

TreeNode pNode = new TreeNode();

pNode.ID = "Root";

pNode.Text = strNodeName;

TreeView1.Nodes.Add(pNode);

如果要在根结点"Root"下面再增加子节点,如何写代码?

TreeView1.Nodes.AddAt(pNode);这种方式好象不行.

TreeView1.Nodes[0].Nodes.Add(pNewNode);

 

 

/*************.Cs 中的代码****************************

 

string strScript="<script language=/"javascript/" >";

strScript+=" function GetNode() /n"+"{ /n";

strScript+=" alert(TreeView1.getTreeNode(TreeView1.clickedNodeIndex).getAttribute('Text'));/n" ;

strScript+=" alert(TreeView1.getTreeNode(TreeView1.clickedNodeIndex).getAttribute('CheckBox'));/n";

strScript+=" alert(TreeView1.getTreeNode(TreeView1.clickedNodeIndex).getAttribute('Checked'));/n";

strScript+=" if (TreeView1.getTreeNode(TreeView1.clickedNodeIndex).getAttribute('Checked'))/n";

strScript+=" TreeView1.getTreeNode(TreeView1.clickedNodeIndex).setAttribute('Checked','false');/n";

strScript+=" else /n";

strScript+=" TreeView1.getTreeNode(TreeView1.clickedNodeIndex).setAttribute('Checked','true');/n";

strScript+=" /n } /n";

strScript+="</script>";

if(! this.IsClientScriptBlockRegistered("myjs"))

{

this.RegisterClientScriptBlock("myjs",strScript);

}

 

 

***************************************************//

 

现在我想在客户端点击父节点的checkbox则下级也被选中,可是使用下面的代码,只能表面选中,在服务器端却得不到,请问有什么其它好法子

<script language=/"javascript/" >

function GetNode()

{

var choose;

var indexid;

indexid=TreeView1.clickedNodeIndex;

if (TreeView1.getTreeNode(indexid).getAttribute('Checked'))

{

choose=false;

}

else

{

choose=true;

}

TreeView1.getTreeNode(indexid).setAttribute('Checked',choose);

var NodeArray=new Array();

NodeArray=TreeView1.getTreeNode(indexid).getChildren();

for(i=0;i<NodeArray.length;i++)

{

var tempindex=indexid+"."+i;

TreeView1.getTreeNode(indexid).setAttribute('Checked',choose);

}

}

//-->

</script>

 

相关文章