TreeView控件通过数据库动态生成树状结构

一、已知数据结构表

 

TreeView控件通过数据库动态生成树状结构 

二、数据访问基类

 

public static string connectionStr = @"Provider=Microsoft.Jet.OleDb.4.0;Data Source='" + Application.StartupPath + "\\AutoCADDemo.mdb" + "'";

 

#region 返回查询的DataTable
        public static DataTable GetDataTable(string safeSql)
        {
            DataSet ds = new DataSet();
            try
            {
                OleDbConnection connection = new OleDbConnection(connectionStr);
                OleDbDataAdapter da = new OleDbDataAdapter(safeSql, connection);
                da.Fill(ds);
            }

            catch { }

            return ds.Tables[0];
        }
#endregion

 

三、生成TreeView的关键代码

 

#region 初始化清单结构树

            TreeNode tree = new TreeNode();
            string strSql = "select * from View_ProjectChapter";
            DataTable dt = AccessData.GetDataTable(strSql);

            foreach (DataRow row in dt.Rows)
            {
                if (tree.Nodes.Count == 0)
                {
                    tree.Text = row[0].ToString();
                    tree.Nodes.Add(row[1].ToString()).Nodes.Add(row[2].ToString());
                }
                else
                {
                    if (row[1].ToString() != tree.Nodes[tree.Nodes.Count - 1].Text)
                    {
                        tree.Nodes.Add(row[1].ToString()).Nodes.Add(row[2].ToString());
                    }
                    else
                    {
                        tree.Nodes[tree.Nodes.Count - 1].Nodes.Add(row[2].ToString());
                    }
                }
            }

            this.treeViewProject.Nodes.Add(tree);

#endregion

 

四、生成TreeView结构树的样式

 

TreeView控件通过数据库动态生成树状结构 

你可能感兴趣的:(treeview)