TreeView 常用代码C#

2020-09-16 14:24发布

数据库字段
ID
ParentID
EquipmentName
代码:

递归绑定
1protected void MachineBind(Int32 KindID)
2    {
3        TreeView1.Nodes.Clear();
4        TreeNode newnode = new TreeNode();
5        T_Machine dao = new T_Machine();
6
7        DataTable dt = dao.GetMachineByKindID(KindID);
8        this.InitTree(this.TreeView1.Nodes, 0, dt);
9    }
10
11    /**//// <summary>
12    /// 初始化树
13    /// </summary>
14    private void InitTree(TreeNodeCollection Nds, int parentID, DataTable dt)
15    {
16        TreeNode tmpNd;
17        DataRow[] rows = dt.Select("MachineParentID=" + parentID);
18        try
19        {
20            //使用foreach语句 来判断递归结束的条件
21            foreach (DataRow row in rows)
22            {
23                tmpNd = new TreeNode();
24                tmpNd.Value = row["MachineID"].ToString();
25                tmpNd.Text = row["MachineName"].ToString();
26                tmpNd.ToolTip = row["MachineFlag"].ToString();
27
28                Nds.Add(tmpNd);
29
30                InitTree(tmpNd.ChildNodes, Convert.ToInt32(tmpNd.Value), dt);
31            }
32        }
33        catch { }
34    }
35
36

查询
1查询#region 查询
2    protected void ImgBut_Select_Click(object sender, ImageClickEventArgs e)
3    {
4        TreeView1.CollapseAll();
5        GetNode(TreeView1.Nodes);
6    }
7 //递归查询
8    protected void GetNode(TreeNodeCollection tc)
9    {
10        foreach (TreeNode TNode in tc)
11        {
12            if (TNode.Text.IndexOf(txt_Select.Text.Trim())!=-1)
13            {
14                ExpandParent(TNode);
15                TNode.ImageUrl = "~/TreeLineImages/select.gif";
16            }
17            else
18            {
19                TNode.ImageUrl = "";
20            }
21
22            GetNode(TNode.ChildNodes);
23        }
24    }
25   //展开父节点
26    protected void ExpandParent(TreeNode node)
27    {
28        if (node.Parent != null)
29        {
30            node.Parent.Expand();
31            ExpandParent(node.Parent);
32        }
33    }
34    #endregion

 

删除
1/**//// <summary>
2    /// 删除 (需设置:TreeView1.ShowCheckBoxes = TreeNodeTypes.Leaf;)
3    /// </summary>
4    protected void but_Del_Click(object sender, EventArgs e)
5    {
6        T_Machine dao = new T_Machine();
7        Int32 count = TreeView1.CheckedNodes.Count;
8        for (int i = 0; i < count; i++)
9        {
10            dao.Delete(Convert.ToInt32(TreeView1.CheckedNodes[i].Value));
11        }
12        MachineBind(Convert.ToInt32(Menu1.SelectedItem.Value));
13    }
14

得到所有子节点
1    protected void DisplayChildNodesValue(TreeNodeCollection nodes)
2    {
3        foreach (TreeNode TNode in nodes)
4        {           
5            Response.Write(TNode.Value.ToString() + "<br>");           
6            DisplayChildNodesValue(TNode.ChildNodes);
7        }
8    }
9    protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
10    {
11        DisplayChildNodesValue(TreeView1.SelectedNode.ChildNodes);
12    }

标签: