动态加载数据代码,采用递归的方式遍历节点:
private void Form_Load(object sender, EventArgs e)
{
//加载数据,把数据加载到控件treeview1中
setTreeView(treeView1, 0);
}
//调用的时候parentId以0值开始 setTreeView(treeView1, 0);
private void setTreeView(TreeView tr1, int parentId)
{
string sql = "select * from TreeTest where parentId=" + parentId;
DataTable ds = sqlHelper.ExecuteDataTable(sql);
if (ds.Rows.Count > 0)
{
int pId = -1;
foreach (DataRow row in ds.Rows)
{
TreeNode node = new TreeNode();
node.Text = row["nodeName"].ToString();
node.Tag = (int) row["id"];
pId = (int) row["parentId"];
if (pId == 0)
{
//添加根节点
tr1.Nodes.Add(node);
}
else
{
//添加根节点之外的其他节点
RefreshChildNode(tr1, node, pId);
}
//查找以node为父节点的子节点
setTreeView(tr1, (int)node.Tag);
}
}
}
//处理根节点的子节点
private void RefreshChildNode(TreeView tr1, TreeNode treeNode, int parentId)
{
foreach (TreeNode node in tr1.Nodes)
{
if ((int)node.Tag == parentId)
{
node.Nodes.Add(treeNode);
return;
}else if (node.Nodes.Count > 0)
{
FindChildNode(node, treeNode, parentId);
}
}
}
//处理根节点的子节点的子节点
private void FindChildNode(TreeNode tNode, TreeNode treeNode, int parentId)
{
foreach (TreeNode node in tNode.Nodes)
{
if ((int)node.Tag == parentId)
{
node.Nodes.Add(treeNode);
return;
}else if (node.Nodes.Count > 0)
{
FindChildNode(node, treeNode, parentId);
}
}
}