您的当前位置:首页正文

C#使用递归算法给TreeView控件绑定数据

2024-11-07 来源:个人技术集锦

/// <summary>
        /// 查找根节点(parent_ID为0的节点)的子节点
        /// </summary>
        /// <param name="parent_ID">参数,接收根节点ID即0</param>
        public void bindtree(string parent_ID)
        {
            this.tvgood.Nodes.Clear();
            DataTable dt = frmgb.Getdata(parent_ID);
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TreeNode node = new TreeNode();
                    node.Text = dt.Rows[i]["gt_Name"].ToString();
                    node.Tag = dt.Rows[i]["gt_ID"].ToString();
                    DataTable dt1 = frmgb.Getdata(node.Tag.ToString());
                    this.tvgood.Nodes.Add(node);//把指定节点添加到控件中
                    frmgb.bindnode(node);//递归遍历制定节点下的子节点
                }
            }
        }

        /// <summary>
        /// 递归遍历指定节点下的子节点
        /// </summary>
        /// <param name="nd">参数,接收节点对象</param>
        public void bindnode(TreeNode nd)
        {
            try
            {
                DataTable dt = Getdata(nd.Tag.ToString());
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TreeNode node = new TreeNode();
                    node.Text = dt.Rows[i]["gt_Name"].ToString();
                    node.Tag = dt.Rows[i]["gt_ID"].ToString();
                    DataTable dt1 = Getdata(node.Tag.ToString());
                    nd.Nodes.Add(node);//把指定节点添加到控件中
                    bindnode(node);
                }
            }
            catch (Exception error)
            {
                throw error;
            }
        }

 /// <summary>
        /// 从数据库中查找指定节点(ID)的子节点
        /// </summary>
        /// <param name="ID">参数</param>
        /// <returns>返回DataSet</returns>
        public DataTable Getdata(string ID)
        {
            try
            {
                DataTable dt = Query.ProcessSql("select * from POS_GoodsType where  gt_FatherNode=" + ID, Constants.DBNAME);
                return dt; //返回含有ID的数据
            }
            catch (Exception error)
            {
                throw error;
            }
        }

点击节点查询类型下的所属商品时目标明确将父节点和所有子节点循环拼接起来字符串在商品表中根据GoodType in (2,3)去查

显示全文