代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Sign_plate_management_system
{
public static class BindTVData
{
private static DataTable dt = null;
//获取数据库所有数据
public static DataTable InitDataTable()
{
SqlConnection conn = new SqlConnection($"Server={ MyDBControls.Server };database={ MyDBControls.Dbase};uid={ MyDBControls.Uid };pwd={ MyDBControls.Pwd}");
SqlDataAdapter sda = new SqlDataAdapter("select * from TVNodesInfo", conn);
dt = new DataTable();
sda.Fill(dt);
return dt;
}
//绑定根节点
public static void BindRootNode(TreeView trv)
{
DataRow[] rows = InitDataTable().Select("NodeTagID=0");
//取根
foreach (DataRow dRow in rows)
{
TreeNode rootNode = new TreeNode
{
Tag = (int)dRow["ID"],
Text = dRow["NodeText"].ToString(),
Name= dRow["NodeName"].ToString()
};
trv.Nodes.Add(rootNode);
BindChildNode(rootNode);
}
}
//递归绑定子区域
private static void BindChildNode(TreeNode FNode)
{
//父节点数据关联的数据行
int nodetagId = (int)FNode.Tag;
//父节点ID
DataRow[] rows = dt.Select($"NodeTagID={nodetagId}");
//子区域
if (rows.Length == 0)//递归终止,区域不包含子区域时
{
return;
}
foreach (DataRow dRow in rows)
{
TreeNode node = new TreeNode
{
Tag = (int)dRow["ID"],
Text = dRow["NodeText"].ToString(),
Name = dRow["NodeName"].ToString()
};
//添加子节点
FNode.Nodes.Add(node);
//递归
BindChildNode(node);
}
}
}
}