1 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using TreeView.BLL; using TreeView.Model; 2 3 namespace TreeView { public partial class Form1 : Form { public Form1() { InitializeComponent(); } 4 5 private void Form1_Load(object sender, EventArgs e) { Loadbook(); } 6 7 private void Loadbook() { treeView1.Nodes.Clear(); IEnumerable<ContruduceBook> list = new ContruduceBookBLL().GetContuduceBookbyParentId(0); foreach (ContruduceBook item in list) { TreeNode treenode = new TreeNode(); treenode.Text = item.Publisher; treenode.Tag = item; treeView1.Nodes.Add(treenode); FillChildNode(treenode, item.Id.Value); } } /// <summary> /// 递归算法加载到treeview 中 /// </summary> /// <param name="parenttreenode"></param> /// <param name="parentId"></param> private void FillChildNode(TreeNode parenttreenode, int parentId) { IEnumerable<ContruduceBook> list = new ContruduceBookBLL().GetContuduceBookbyParentId(parentId); foreach (ContruduceBook item in list) { TreeNode treenode = new TreeNode(); treenode.Text = item.Publisher; treenode.Tag = item; parenttreenode.Nodes.Add(treenode); } } 8 9 private void btnEdit_Click(object sender, EventArgs e) { ContruduceBook book = treeView1.SelectedNode.Tag as ContruduceBook; Edit edit = new Edit(); 10 11 edit.PublisherName= book.Publisher ; edit.Context= book.BookContext.ToString(); //edit.ShowDialog(); if (edit.ShowDialog()==DialogResult.OK) { book.Publisher= edit.PublisherName; book.BookContext = edit.Context; treeView1.SelectedNode.Tag = book; treeView1.SelectedNode.Text = book.Publisher; 12 13 new ContruduceBookBLL().Update(book); //Loadbook(); } 14 15 } 16 17 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { textBox1.Text = ((ContruduceBook)e.Node.Tag).BookContext.ToString(); } 18 19 private void btnAdd_Click(object sender, EventArgs e) { ContruduceBook book = new ContruduceBook(); Add add = new Add(); 20 21 if (add.ShowDialog() == DialogResult.OK) { book.Publisher = add.PublisherName; book.BookContext= add.Context; if (add.ParentId == 0) { book.ParentId = 0; book.Id = new ContruduceBookBLL().AddNew(book); TreeNode tr = new TreeNode(); tr.Text = book.Publisher; tr.Tag = book; treeView1.Nodes.Add(tr); 22 23 } else { if (treeView1.SelectedNode==null) { MessageBox.Show("没有选中项!"); } book.ParentId = ((ContruduceBook)treeView1.SelectedNode.Tag).Id; book.Id = new ContruduceBookBLL().AddNew(book); TreeNode tr = new TreeNode(); tr.Text = book.Publisher; tr.Tag = book; treeView1.SelectedNode.Nodes.Add(tr); } } } } }