C# — WinForm TreeView篇


好像有些里的兄弟看不上这些小小的积累,没有关系,我就当是为自己记录的随笔,如果最后也能帮助到某些人就更好。

这一篇的主角是TreeView:

方法组如下:

1、TreeView根节点读取数据部分

提醒一点:ImageList控件ImageIndex,SelectedImageIndex属性,第一个是未选中时图片下标,第二个是选中时图片下标




public static void Root(TreeView T,ImageList I)
        {
            using (BLLConnect a = new BLLConnect())
            {
                string sql = "select * from setup where set_fatherid = 0 and boo_flag = '是'";
                TreeNode nodes = new TreeNode();
                SqlCommand comm = a.ReturnSqlCommand(sql);
                SqlDataReader reader = comm.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        nodes.Name = reader["set_id"].ToString();
                        nodes.Text = reader["set_name"].ToString();
                    }
                    reader.Close();
                    a.Close();
                    //查找”父节点“为”根节点“的所有节点
                    string sql1 = "select * from setup where boo_flag = '是' and set_fatherid=" + nodes.Name + "";
                    bind(comm, sql1, nodes);
                    T.Nodes.Add(nodes);
                    T.ImageList = I;
                    T.ImageIndex = 0;
                    T.SelectedImageIndex = 1;
                }
                else
                {
                    return;
                }
            }
        }


 

2、TreeView除根节点外读取数据循环部分(上面的方法调用的bind方法)



public static void bind(SqlCommand comm, string sql, TreeNode noed)
        {
            using (BLLConnect a = new BLLConnect())
            {
                comm = a.ReturnSqlCommand(sql);
                SqlDataReader reader = comm.ExecuteReader();
                List<TreeNode> A = new List<TreeNode>();
                while (reader.Read())
                {
                    TreeNode node1 = new TreeNode();
                    node1.Name = reader["set_id"].ToString();
                    node1.Text = reader["set_name"].ToString();
                    A.Add(node1);
                }
                reader.Close();
                a.Close();
                for (int i = 0; i < A.Count; i++)
                {
                    //查找每个节点下的所有子节点
                    string sql1 = "select * from setup where boo_flag = '是' and set_fatherid=" + A[i].Name + "";
                    noed.Nodes.Add(A[i]);
                    bind(comm, sql1, A[i]);//递归
                }
            }
        }

 

相应的数据库设计脚本如下


create table setup
(
        set_id int identity(1,1) primary key,
        set_center nvarchar(8),
        set_name nvarchar(15),
        set_fatherid int,
        boo_flag nvarchar(1) default '是'
)