▶ 窗体界面
▶ 源码
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace login_demo
{
public partial class Form2 : Form
{
String conn_str = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=E:\Desktop\C-Sharp\Month_11\day1115\login_demo\login_demo\Database1.mdf;Integrated Security=True";
public Form2()
{
InitializeComponent();
}
/// <summary>
/// 窗口加载时从数据库读取数据并填充
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form2_Load(object sender, EventArgs e)
{
addParent();
}
/// <summary>
/// 迭代填充父节点
/// </summary>
void addParent()
{
String sql = "SELECT * FROM organization WHERE org_parent_id=-1";
SqlConnection conn = new SqlConnection(conn_str);
SqlDataReader sql_reader = null;
//连接数据库
try
{
conn.Open();
SqlCommand command = new SqlCommand(sql, conn);
sql_reader = command.ExecuteReader();
while (sql_reader.Read())
{
//获取节点的org_id与org_name
var name = sql_reader["org_name"].ToString();
var id = Convert.ToInt32(sql_reader["org_id"]);
var node = new TreeNode(name);
//TreeView填充
treeView1.Nodes.Add(node);
//迭代填充子节点
AddChildren(node, id);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Warnning Info!");
}
finally
{
sql_reader.Close();
conn.Close();
}
}
/// <summary>
/// 添加子节点
/// </summary>
/// <param name="node"></param>
/// <param name="pid">pid = parent_id</param>
void AddChildren(TreeNode pnode,int pid)
{
String sql = $"SELECT * FROM organization WHERE org_parent_id={pid}";
SqlConnection conn = new SqlConnection(conn_str);
SqlDataReader sql_reader = null;
//连接数据库
try
{
conn.Open();
SqlCommand command = new SqlCommand(sql, conn);
sql_reader = command.ExecuteReader();
while (sql_reader.Read())
{
//获取节点的org_id与org_name
var name = sql_reader["org_name"].ToString();
var id = Convert.ToInt32(sql_reader["org_id"]);
var node = new TreeNode(name);
//TreeView填充
pnode.Nodes.Add(node);
//迭代填充子节点
AddChildren(node, id);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Warnning Info!");
}
finally
{
sql_reader.Close();
conn.Close();
}
}
}
}