部门树形结构。设计张部门表用于存储部门编码、名称、上级部门id,使用Treeview控件显示部门树,并实现部门增删改、移动、折叠等功能。特别提示,部门有层级关系,可用donetbar的adtree控件
代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; namespace 部门树形结构
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
BindTree("");
}
DBHelp s = new DBHelp();
private void BindTree(string pid)
{
string str = "select * from biao where SJ_id=" + int.Parse(pid);
DataTable ta = s.getTableBySql(str);
if (ta.Rows.Count > )
{
for (int i = ; i < ta.Rows.Count; i++)
{
TreeNode node = new TreeNode();
node.Text = ta.Rows[i]["name"].ToString();
node.Tag = ta.Rows[i]["id"].ToString();
this.treeView1.Nodes.Add(node);
BindNode(node);
}
}
}
private void BindNode(TreeNode nd)
{
string str = "select * from biao where SJ_id="+ Convert.ToString(nd.Tag);
DataTable ta = s.getTableBySql(str);
for (int i = ; i < ta.Rows.Count; i++)
{
TreeNode node = new TreeNode();
node.Text = ta.Rows[i]["name"].ToString();
node.Tag = ta.Rows[i]["id"].ToString();
nd.Nodes.Add(node);//重点
BindNode(node);
}
} private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (treeView1.SelectedNode != null)//重点部分
{
txt_id.Text= treeView1.SelectedNode.Tag.ToString();//取值
txt_name.Text= treeView1.SelectedNode.Text; string str = "select * from biao where id=" + int.Parse(txt_id.Text);
DataTable ta = s.getTableBySql(str);
txt_sj.Text = ta.Rows[]["SJ_id"].ToString();
}
}
//添加
private void buttonX1_Click(object sender, EventArgs e)
{
string sql_add =string.Format("insert into biao(name,SJ_id) values('{0}',{1})", txt_name.Text,int.Parse(txt_sj.Text));
if (s.ExecuteIDUBySql(sql_add) > )
{
MessageBox.Show("添加成功!", "消息");
}
else
{
MessageBox.Show("添加失败!", "消息");
}
treeView1.Nodes.Clear();
BindTree("");
}
}
}