本文用了2张表,结构如下:
表province: province_id province_name
表city: city_id city_name province_id
完整代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace test
{
public partial class TreeStruc : Form
{
public TreeStruc()
{
InitializeComponent();
}
SqlConnection conn = new SqlConnection("server=zhuzy;integrated security=sspi;database=library");
SqlDataAdapter da;
DataSet ds=new DataSet();
SqlCommand cmd;
/// <summary>
/// 自定义节点类,继承于系统的 TreeNode 类,给节点增加一个 IsFirstExpand 属性
/// </summary>
public class InheritTreeNode : TreeNode
{
private bool isFirstExpand = true;
public bool IsFirstExpand //属性
{
get { return isFirstExpand; }
set { isFirstExpand = value; }
}
public InheritTreeNode() : base() { }
public InheritTreeNode(string text) : base(text) { }
}
string id = "";
private void TreeStruc_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("select province_id,province_name from province", conn);
da.Fill(ds, "province");
for (int i = 0; i < ds.Tables["province"].Rows.Count; i++)
{
InheritTreeNode root = new InheritTreeNode(ds.Tables["province"].Rows[i][1].ToString().Trim());
id = ds.Tables["province"].Rows[i][0].ToString().Trim();
this.treeView1.Nodes.Add(root);
ReadChileNode(root);
id = "";//
}
this.treeView1.SelectedNode = treeView1.Nodes[0];
}
/// <summary>
/// 读取 node 的子节点
/// </summary>
private void ReadChileNode(TreeNode node)
{
da = new SqlDataAdapter("select city_name from city where province_id='" + id + "'", conn);
da.Fill(ds, "city");
try
{
for (int j = 0; j < ds.Tables["city"].Rows.Count; j++)
{
node.Nodes.Add(new InheritTreeNode(ds.Tables["city"].Rows[j][0].ToString().Trim()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
ds.Tables["city"].Clear();//
}
/// <summary>
/// 节点展开之前事件
/// </summary>
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
InheritTreeNode node = (InheritTreeNode)e.Node;//获取要选中、展开、折叠或选择的树节点e.Node
if (node != null)
{
// 判断该节点是否首次被展开
if (node.IsFirstExpand)
{
for (int i = 0; i < node.Nodes.Count; i++)
{
ReadChileNode(node.Nodes[i]); //为 e.Node 下的每个子节点,添加子节点
}
}
}
node.IsFirstExpand = false;
}
/// <summary>
/// 将文本框输入的内容添加为父节点
/// </summary>
private void btnAddParentNode_Click(object sender, EventArgs e)
{
try
{
string strParentNode = this.textBox1.Text.ToString().Trim();
da = new SqlDataAdapter("select province_name from province where province_name='" + strParentNode + "'", conn);
da.Fill(ds, "province_name");
int nCount = ds.Tables["province_name"].Rows.Count;
if (textBox1.Text.ToString().Trim() != "")
{
if (nCount == 0) //判断是否存在重复省份
{
da = new SqlDataAdapter("select max(province_id) from province", conn);
da.Fill(ds, "id");
string _max_province_id = ds.Tables["id"].Rows[0][0].ToString().Trim();
int nID = Convert.ToInt32(_max_province_id) + 1;
string strID = "00" + nID.ToString().Trim();
string _insertSQL = "insert into province values('" + strID + "','" + strParentNode + "')";
cmd = new SqlCommand(_insertSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
this.treeView1.Nodes.Add(strParentNode); //使新增的节点在TreeView里显示
textBox1.Clear();
textBox1.Focus();
}
else
{
MessageBox.Show("当前新增的省份已经存在,请重新输入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
textBox1.Focus();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 在选择了父节点后,将文本框中的内容添加为其子节点
/// </summary>
string str_insert_province_id = "";
string str_insert_city_id = "";
private void btnAddChildNode_Click(object sender, EventArgs e)
{
try
{
TreeNode node = this.treeView1.SelectedNode;
string strProvinceName = node.Text;
if (node != null)
{
retunParentNode_ID(strProvinceName);
insertChildNode(node);
textBox1.Clear();
textBox1.Focus();
}
else
{
MessageBox.Show("请先选择需要新增城市信息的省份!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
textBox1.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 返回当前选择的父节点的province_id
/// </summary>
/// <returns></returns>
private string retunParentNode_ID(string strName)
{
da = new SqlDataAdapter("select province_id from province where province_name='" + strName + "'", conn);
da.Fill(ds, "province_id");
str_insert_province_id = ds.Tables["province_id"].Rows[0][0].ToString().Trim();//即将新增的子节点的province_id
return str_insert_province_id;
}
/// <summary>
/// 在当前选择的父节点下新增子节点
/// </summary>
private void insertChildNode(TreeNode CurrentParentNode)
{
string strChildNode = this.textBox1.Text.ToString().Trim();
try
{
if (textBox1.Text.ToString().Trim() != "")
{
string strsql = "select * from city where province_id='" + str_insert_province_id + "'";
da = new SqlDataAdapter(strsql, conn);
da.Fill(ds, "tb");
int nCount1 = ds.Tables["tb"].Rows.Count;
if (nCount1 == 0) //父节点下没有子节点
{
string _city_id = "0" + "1";
string _insertSQL = "insert into city values('" + _city_id + "','" + strChildNode + "','" + str_insert_province_id + "')";
cmd = new SqlCommand(_insertSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
CurrentParentNode.Nodes.Add(strChildNode);
textBox1.Clear();
textBox1.Focus();
}
if (nCount1 != 0) //父节点下有子节点
{
da = new SqlDataAdapter("select city_name from city where city_name='" + strChildNode + "'", conn);
da.Fill(ds, "city_name");
int nCount2 = ds.Tables["city_name"].Rows.Count;
if (nCount2 == 0) //不存在相同的子节点
{
string _max_city_id = "select max(city_id) from city where province_id='" + str_insert_province_id + "'";
da = new SqlDataAdapter(_max_city_id, conn);
da.Fill(ds, "city_id");
str_insert_city_id = ds.Tables["city_id"].Rows[0][0].ToString().Trim();
int nID = Convert.ToInt32(str_insert_city_id) + 1;
str_insert_city_id = "0" + nID.ToString().Trim();
string _insertSQL = "insert into city values('" + str_insert_city_id + "','" + strChildNode + "','" + str_insert_province_id + "')";
cmd = new SqlCommand(_insertSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
CurrentParentNode.Nodes.Add(strChildNode);
textBox1.Clear();
textBox1.Focus();
}
if (nCount2 != 0) //存在相同的子节点
{
MessageBox.Show("已经存在此城市,请重新输入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
textBox1.Focus();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace test
{
public partial class TreeStruc : Form
{
public TreeStruc()
{
InitializeComponent();
}
SqlConnection conn = new SqlConnection("server=zhuzy;integrated security=sspi;database=library");
SqlDataAdapter da;
DataSet ds=new DataSet();
SqlCommand cmd;
/// <summary>
/// 自定义节点类,继承于系统的 TreeNode 类,给节点增加一个 IsFirstExpand 属性
/// </summary>
public class InheritTreeNode : TreeNode
{
private bool isFirstExpand = true;
public bool IsFirstExpand //属性
{
get { return isFirstExpand; }
set { isFirstExpand = value; }
}
public InheritTreeNode() : base() { }
public InheritTreeNode(string text) : base(text) { }
}
string id = "";
private void TreeStruc_Load(object sender, EventArgs e)
{
da = new SqlDataAdapter("select province_id,province_name from province", conn);
da.Fill(ds, "province");
for (int i = 0; i < ds.Tables["province"].Rows.Count; i++)
{
InheritTreeNode root = new InheritTreeNode(ds.Tables["province"].Rows[i][1].ToString().Trim());
id = ds.Tables["province"].Rows[i][0].ToString().Trim();
this.treeView1.Nodes.Add(root);
ReadChileNode(root);
id = "";//
}
this.treeView1.SelectedNode = treeView1.Nodes[0];
}
/// <summary>
/// 读取 node 的子节点
/// </summary>
private void ReadChileNode(TreeNode node)
{
da = new SqlDataAdapter("select city_name from city where province_id='" + id + "'", conn);
da.Fill(ds, "city");
try
{
for (int j = 0; j < ds.Tables["city"].Rows.Count; j++)
{
node.Nodes.Add(new InheritTreeNode(ds.Tables["city"].Rows[j][0].ToString().Trim()));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
ds.Tables["city"].Clear();//
}
/// <summary>
/// 节点展开之前事件
/// </summary>
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
InheritTreeNode node = (InheritTreeNode)e.Node;//获取要选中、展开、折叠或选择的树节点e.Node
if (node != null)
{
// 判断该节点是否首次被展开
if (node.IsFirstExpand)
{
for (int i = 0; i < node.Nodes.Count; i++)
{
ReadChileNode(node.Nodes[i]); //为 e.Node 下的每个子节点,添加子节点
}
}
}
node.IsFirstExpand = false;
}
/// <summary>
/// 将文本框输入的内容添加为父节点
/// </summary>
private void btnAddParentNode_Click(object sender, EventArgs e)
{
try
{
string strParentNode = this.textBox1.Text.ToString().Trim();
da = new SqlDataAdapter("select province_name from province where province_name='" + strParentNode + "'", conn);
da.Fill(ds, "province_name");
int nCount = ds.Tables["province_name"].Rows.Count;
if (textBox1.Text.ToString().Trim() != "")
{
if (nCount == 0) //判断是否存在重复省份
{
da = new SqlDataAdapter("select max(province_id) from province", conn);
da.Fill(ds, "id");
string _max_province_id = ds.Tables["id"].Rows[0][0].ToString().Trim();
int nID = Convert.ToInt32(_max_province_id) + 1;
string strID = "00" + nID.ToString().Trim();
string _insertSQL = "insert into province values('" + strID + "','" + strParentNode + "')";
cmd = new SqlCommand(_insertSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
this.treeView1.Nodes.Add(strParentNode); //使新增的节点在TreeView里显示
textBox1.Clear();
textBox1.Focus();
}
else
{
MessageBox.Show("当前新增的省份已经存在,请重新输入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
textBox1.Focus();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 在选择了父节点后,将文本框中的内容添加为其子节点
/// </summary>
string str_insert_province_id = "";
string str_insert_city_id = "";
private void btnAddChildNode_Click(object sender, EventArgs e)
{
try
{
TreeNode node = this.treeView1.SelectedNode;
string strProvinceName = node.Text;
if (node != null)
{
retunParentNode_ID(strProvinceName);
insertChildNode(node);
textBox1.Clear();
textBox1.Focus();
}
else
{
MessageBox.Show("请先选择需要新增城市信息的省份!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
textBox1.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 返回当前选择的父节点的province_id
/// </summary>
/// <returns></returns>
private string retunParentNode_ID(string strName)
{
da = new SqlDataAdapter("select province_id from province where province_name='" + strName + "'", conn);
da.Fill(ds, "province_id");
str_insert_province_id = ds.Tables["province_id"].Rows[0][0].ToString().Trim();//即将新增的子节点的province_id
return str_insert_province_id;
}
/// <summary>
/// 在当前选择的父节点下新增子节点
/// </summary>
private void insertChildNode(TreeNode CurrentParentNode)
{
string strChildNode = this.textBox1.Text.ToString().Trim();
try
{
if (textBox1.Text.ToString().Trim() != "")
{
string strsql = "select * from city where province_id='" + str_insert_province_id + "'";
da = new SqlDataAdapter(strsql, conn);
da.Fill(ds, "tb");
int nCount1 = ds.Tables["tb"].Rows.Count;
if (nCount1 == 0) //父节点下没有子节点
{
string _city_id = "0" + "1";
string _insertSQL = "insert into city values('" + _city_id + "','" + strChildNode + "','" + str_insert_province_id + "')";
cmd = new SqlCommand(_insertSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
CurrentParentNode.Nodes.Add(strChildNode);
textBox1.Clear();
textBox1.Focus();
}
if (nCount1 != 0) //父节点下有子节点
{
da = new SqlDataAdapter("select city_name from city where city_name='" + strChildNode + "'", conn);
da.Fill(ds, "city_name");
int nCount2 = ds.Tables["city_name"].Rows.Count;
if (nCount2 == 0) //不存在相同的子节点
{
string _max_city_id = "select max(city_id) from city where province_id='" + str_insert_province_id + "'";
da = new SqlDataAdapter(_max_city_id, conn);
da.Fill(ds, "city_id");
str_insert_city_id = ds.Tables["city_id"].Rows[0][0].ToString().Trim();
int nID = Convert.ToInt32(str_insert_city_id) + 1;
str_insert_city_id = "0" + nID.ToString().Trim();
string _insertSQL = "insert into city values('" + str_insert_city_id + "','" + strChildNode + "','" + str_insert_province_id + "')";
cmd = new SqlCommand(_insertSQL, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
CurrentParentNode.Nodes.Add(strChildNode);
textBox1.Clear();
textBox1.Focus();
}
if (nCount2 != 0) //存在相同的子节点
{
MessageBox.Show("已经存在此城市,请重新输入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Clear();
textBox1.Focus();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
备注:此树只实现2层结构