部门树形结构。设计张部门表用于存储部门编码、名称、上级部门id,使用Treeview控件显示部门树,并实现部门增删改、移动、折叠等功能。特别提示,部门有层级关系,可用donetbar的adtree控件
代码如下
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace 部门树形结构 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 private void Form1_Load(object sender, EventArgs e) 21 { 22 BindTree("0"); 23 } 24 DBHelp s = new DBHelp(); 25 private void BindTree(string pid) 26 { 27 string str = "select * from biao where SJ_id=" + int.Parse(pid); 28 DataTable ta = s.getTableBySql(str); 29 if (ta.Rows.Count > 0) 30 { 31 for (int i = 0; i < ta.Rows.Count; i++) 32 { 33 TreeNode node = new TreeNode(); 34 node.Text = ta.Rows[i]["name"].ToString(); 35 node.Tag = ta.Rows[i]["id"].ToString(); 36 this.treeView1.Nodes.Add(node); 37 BindNode(node); 38 } 39 } 40 } 41 private void BindNode(TreeNode nd) 42 { 43 string str = "select * from biao where SJ_id="+ Convert.ToString(nd.Tag); 44 DataTable ta = s.getTableBySql(str); 45 for (int i = 0; i < ta.Rows.Count; i++) 46 { 47 TreeNode node = new TreeNode(); 48 node.Text = ta.Rows[i]["name"].ToString(); 49 node.Tag = ta.Rows[i]["id"].ToString(); 50 nd.Nodes.Add(node);//重点 51 BindNode(node); 52 } 53 } 54 55 private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) 56 { 57 if (treeView1.SelectedNode != null)//重点部分 58 { 59 txt_id.Text= treeView1.SelectedNode.Tag.ToString();//取值 60 txt_name.Text= treeView1.SelectedNode.Text; 61 62 string str = "select * from biao where id=" + int.Parse(txt_id.Text); 63 DataTable ta = s.getTableBySql(str); 64 txt_sj.Text = ta.Rows[0]["SJ_id"].ToString(); 65 } 66 } 67 //添加 68 private void buttonX1_Click(object sender, EventArgs e) 69 { 70 string sql_add =string.Format("insert into biao(name,SJ_id) values('{0}',{1})", txt_name.Text,int.Parse(txt_sj.Text)); 71 if (s.ExecuteIDUBySql(sql_add) > 0) 72 { 73 MessageBox.Show("添加成功!", "消息"); 74 } 75 else 76 { 77 MessageBox.Show("添加失败!", "消息"); 78 } 79 treeView1.Nodes.Clear(); 80 BindTree("0"); 81 } 82 } 83 }