如何添加数据库中的信息加载到树形控件中?如何遍历控件中的信息?如何对控件中的信息进行增删查改?

数据库设计:

主界面:

代码:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using TreeSolution.BLL;
using TreeSolution.Model;

namespace 树型测试
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //当窗体加载时,加载树形节点
        private void Form1_Load(object sender, EventArgs e)
        {
            T_TreeBLL treeBLL = new T_TreeBLL();
            IEnumerable<T_Tree> tree = treeBLL.GetByParentId(0);
            foreach (T_Tree node in tree)
            {
                TreeNode treeNode = new TreeNode();
                treeNode.Text = node.Name;
                treeNode.Tag = node;//将每一个节点所对应的model都放到它的Tag上
                treeView1.Nodes.Add(treeNode);
                FillChildren(treeNode,(int)node.Id);
            }
        }
        /// <summary>
        /// 把以parentId为父节点的节点都添加到parentNode下
        /// </summary>
        /// <param name="pareNode">父节点</param>
        /// <param name="parentId"></param>
        private void FillChildren(TreeNode pareNode, int parentId)
        {
            T_TreeBLL treeBLL = new T_TreeBLL();
            IEnumerable<T_Tree> tree = treeBLL.GetByParentId(parentId);
            foreach (T_Tree node in tree)
            {
                TreeNode treeNode = new TreeNode();
                treeNode.Text = node.Name;
                treeNode.Tag = node;//将每一个节点所对应的model都放到它的Tag上
                pareNode.Nodes.Add(treeNode);
                //把所有的以我parentid的都加载到我的下面
                FillChildren(treeNode, (int)node.Id);
            }
        }
        //点击当前节点,显示他的文字
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            string s = e.Node.Text.ToString();
            MessageBox.Show(s);
        }
        //遍历节点
        #region 遍历节点
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (TreeNode node in treeView1.Nodes)
            {
                DisplayNode(node);
            }
        }
        //递归调用的节点
        private void DisplayNode(TreeNode node)
        {
            textBox1.AppendText(node.Text + "\r\n");
            if (node.Nodes.Count > 0)
            {
                foreach (TreeNode childNode in node.Nodes)
                {
                    DisplayNode(childNode);
                }
            }
        }
        #endregion
        /// <summary>
        /// 修改节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            T_Tree model = (T_Tree)treeView1.SelectedNode.Tag;
            EditNode form = new EditNode();
            form.NodeName = model.Name;
            form.NodeBody = model.Body;
            if (form.ShowDialog() == DialogResult.OK)
            {
                model.Name = form.NodeName;
                model.Body = form.NodeBody;
                new T_TreeBLL().Update(model);
            }
        }

 


 

 /// <summary>
        /// 添加根节点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddRootNode_Click(object sender, EventArgs e)
        {
            EditNode form = new EditNode();
            if (form.ShowDialog()!=DialogResult.OK)
            {
                return;
            }
            T_Tree model = new T_Tree();
            model.Name = form.NodeName;
            model.Body = form.NodeBody;
            model.ParentId = 0;
            //添加信息并返回新添加的Id
            int id=new T_TreeBLL().AddNew(model);
            //将新增的Id赋给对象
            model.Id = id;
            //添加节点到Treeview控件上
            TreeNode node=new TreeNode();
            node.Text=model.Name;
            node.Tag = model;
            treeView1.Nodes.Add(node);
           
        }
        //增加子节点
        private void btnAddChildNode_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode = treeView1.SelectedNode;
            if (selectedNode == null)
            {
                MessageBox.Show("没有节点被选中");
                return;
            }
            EditNode form = new EditNode();
            if (form.ShowDialog()!=DialogResult.OK)
            {
                return;
            }
            //获得选中节点的(父节点的)模型对象
            T_Tree parentModel=(T_Tree)selectedNode.Tag;
            T_Tree model = new T_Tree();
            //EditNode form = new EditNode();
            model.Name = form.NodeName;
            model.Body = form.NodeBody;
            model.ParentId = parentModel.Id;
            model.Id=new T_TreeBLL().AddNew(model);
            //添加节点
            TreeNode treeNode = new TreeNode();
            treeNode.Text = model.Name;
            treeNode.Tag = model;
            selectedNode.Nodes.Add(treeNode);

        }
        //删除节点
        private void btnDelete_Click(object sender, EventArgs e)
        {
            //选中节点
            TreeNode selectedNode = treeView1.SelectedNode;
            if (selectedNode == null)
            {
                MessageBox.Show("没有节点被选中");
                return;
            }
            selectedNode.Remove();
            T_Tree model = (T_Tree)selectedNode.Tag;
            new T_TreeBLL().DeleteAllNode((int)model.Id);
        }

    }
}

 

修改界面:

代码:

using System;
using System.Windows.Forms;

namespace 树型测试
{
    public partial class EditNode : Form
    {
        public EditNode()
        {
            InitializeComponent();
        }

        public string NodeName
        {
            get { return txtName.Text; }
            set { txtName.Text = value; }
        }
        public string NodeBody
        {
            get { return txtBody.Text; }
            set { txtBody.Text = value; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}

 总图:

sqlhelper:

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace TreeSolution.DAL
{
    class SqlHelper
    {
        public static readonly string connstr =
            ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;

        public static int ExecuteNonQuery(string cmdText,
            params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        public static object ExecuteScalar(string cmdText,
            params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    cmd.Parameters.AddRange(parameters);
                    return cmd.ExecuteScalar();
                }
            }
        }

        public static DataTable ExecuteDataTable(string cmdText,
            params SqlParameter[] parameters)
        {
            using (SqlConnection conn = new SqlConnection(connstr))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = cmdText;
                    cmd.Parameters.AddRange(parameters);
                    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        adapter.Fill(dt);
                        return dt;
                    }
                }
            }
        }

        public static SqlDataReader ExecuteDataReader(string cmdText,
            params SqlParameter[] parameters)
        {
            SqlConnection conn = new SqlConnection(connstr);
            conn.Open();
            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = cmdText;
                cmd.Parameters.AddRange(parameters);
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
    }
}

三层模型的代码:

model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TreeSolution.Model
{
    partial class T_Tree
    {
        public System.Int32? Id { get; set; }
        public System.Int32? ParentId { get; set; }
        public System.String Name { get; set; }
        public System.String Body { get; set; }
    }
}

DAL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TreeSolution.Model;
using System.Data.SqlClient;
using System.Data;
namespace TreeSolution.DAL
{
    partial class T_TreeDAL
    {
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model">数据模型</param>
        /// <returns></returns>
        public int AddNew(T_Tree model)
        {
            string sql = "insert into T_Tree(ParentId,Name,Body) output inserted.id values(@ParentId,@Name,@Body)";
            int id = (int)SqlHelper.ExecuteScalar(sql
            , new SqlParameter("ParentId", model.ParentId)
            , new SqlParameter("Name", model.Name)
            , new SqlParameter("Body", model.Body)
            );
            return id;
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="model">一个数据模型</param>
        /// <returns></returns>
        public bool Update(T_Tree model)
        {
            string sql = "update T_Tree set ParentId=@ParentId,Name=@Name,Body=@Body where id=@id";
            int rows = SqlHelper.ExecuteNonQuery(sql
            ,new SqlParameter("Id", model.Id)
            ,new SqlParameter("ParentId", model.ParentId)
            ,new SqlParameter("Name", model.Name)
            ,new SqlParameter("Body", model.Body)
            );
            return rows > 0;
        }
        /// <summary>
        /// 删除某一节点
        /// </summary>
        /// <param name="id">id号</param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            int rows = SqlHelper.ExecuteNonQuery("delete from T_Tree where id=@id",
            new SqlParameter("id",id));
            return rows > 0;
        }
        /// <summary>
        /// 将一行数据转化为model
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private static T_Tree ToModel(DataRow row)
        {
            T_Tree model = new T_Tree();
            model.Id = row.IsNull("Id")?null:(System.Int32?)row["Id"];
            model.ParentId = row.IsNull("ParentId")?null:(System.Int32?)row["ParentId"];
            model.Name = row.IsNull("Name")?null:(System.String)row["Name"];
            model.Body = row.IsNull("Body")?null:(System.String)row["Body"];
            return model;
        }
        /// <summary>
        /// 获得Id为多少的对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T_Tree Get(int id)
        {
            DataTable dt = SqlHelper.ExecuteDataTable("select * from T_Tree  whereid=@id",
            new SqlParameter("id",id));
            if (dt.Rows.Count > 1)
            {throw new Exception("more than 1 row was found");}
            if (dt.Rows.Count <= 0){return null;}
            DataRow row = dt.Rows[0];
            T_Tree model = ToModel(row);
            return model;
        }
        /// <summary>
        /// 获得几级节点
        /// </summary>
        /// <param name="id"></param>
        /// <returns>返回集合</returns>
        public IEnumerable<T_Tree> GetByParentId(int id)
        {
            List<T_Tree> list = new List<T_Tree>();
            DataTable dt = SqlHelper.ExecuteDataTable("select * from T_Tree  whereParentId=@parentid",
            new SqlParameter("parentid", id));
            foreach (DataRow row in dt.Rows)
            {
                list.Add(ToModel(row));
            }
            return list;
        }
        /// <summary>
        /// 返回所有的T_Tree对象
        /// </summary>
        /// <returns>返回T_Tree对象的泛型集合(只读属性)</returns>
        public IEnumerable<T_Tree> ListAll()
        {
            List<T_Tree> list = new List<T_Tree>();
            DataTable dt = SqlHelper.ExecuteDataTable("select * from T_Tree");
            foreach (DataRow row in dt.Rows){
                list.Add(ToModel(row));
            }
            return list;
        }

       //删除当前节点的所有子节点
        public void DeleteAllNode(int id)
        {
            IEnumerable<T_Tree> children = GetByParentId(id);
            foreach (T_Tree model in children)
            {
                DeleteAllNode((int)model.Id);
            }
            Delete(id);
        }

}
}

BLL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TreeSolution.Model;
using TreeSolution.DAL;
namespace TreeSolution.BLL
{
    partial class T_TreeBLL
    {
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int AddNew(T_Tree model)
        {
            return new T_TreeDAL().AddNew(model);
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            return new T_TreeDAL().Delete(id);
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(T_Tree model)
        {
            return new T_TreeDAL().Update(model);
        }
        /// <summary>
        /// 查询某一Id的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T_Tree Get(int id)
        {
            return new T_TreeDAL().Get(id);
        }
        /// <summary>
        /// 返回集合
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IEnumerable<T_Tree> GetByParentId(int id)
        {
            return new T_TreeDAL().GetByParentId(id);
        }
        /// <summary>
        /// 查询所有的数据
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T_Tree> ListAll()
        {
            return new T_TreeDAL().ListAll();
        }


       /// <summary>
        /// 删除所有节点
        /// </summary>
        /// <param name="id"></param>
        public void DeleteAllNode(int id)
        {
            new T_TreeDAL().DeleteAllNode(id);
        }   

}
}