递归绑定TreeView

  树形菜单在平常的开发中是最常见的了,自已也练习练习,先来看两个图:

  递归绑定TreeView                递归绑定TreeView

     效果图                         表结构

 

实现代码:

   private void Form1_Load(object sender, EventArgs e)
        {
            this.BindTree(0);
        }


        private DataSet GetData(int pid)
        {
            string strCon = @"Data Source=Agony\SQLSERVER2005;Initial Catalog=sports;Integrated Security=True";
            string sql = "SELECT * FROM sport WHERE pid=" + pid;
            SqlConnection conn = new SqlConnection(strCon);
            SqlDataAdapter da = new SqlDataAdapter(sql, conn);
            DataSet ds = new DataSet();
            da.Fill(ds, "sport");
            return ds;
        }

        //绑定父节点
        private void BindTree(int pid)
        {
            DataSet ds = GetData(pid);
            if (ds.Tables["sport"].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables["sport"].Rows.Count; i++)
                {
                    TreeNode node = new TreeNode();
                    node.Text = ds.Tables["sport"].Rows[i]["sname"].ToString();
                    node.Tag = ds.Tables["sport"].Rows[i]["id"].ToString();

                    this.treeView1.Nodes.Add(node);
                    BindChildNode(node);
                }
            }
        }

        //绑定子节点
        private void BindChildNode(TreeNode node)
        {
            TreeNode tn = node;
            int id = Convert.ToInt32(tn.Tag);
            DataSet ds = GetData(id);
            for (int i = 0; i < ds.Tables["sport"].Rows.Count; i++)
            {
                TreeNode nod = new TreeNode();
                nod.Text = ds.Tables["sport"].Rows[i]["sname"].ToString();
                nod.Tag = ds.Tables["sport"].Rows[i]["id"].ToString();


                tn.Nodes.Add(nod);
                BindChildNode(nod);
            }
        }

 

本文转自贺满博客园博客,原文链接:http://www.cnblogs.com/puresoul/archive/2012/03/15/1776370.html,如需转载请自行联系原作者。



上一篇:RecyclerView添加HeaderView和FooterView


下一篇:缩减Windows 7任务栏的高度