c# treeView 动态添加子节点的问题

2024-12-25 10:01:51
推荐回答(1个)
回答1:

Load里面添加:

int i = 0;
while (i < 7)
{
switch(Convert.ToString(i))
{
case "0":
{
treeView1.Nodes.Clear();
TreeNode myTreeNode = new TreeNode("AAA");
treeView1.Nodes.Add(myTreeNode);
CreateChildTree(myTreeNode, "AAA", "AAA");
}
break;
case "1":
{
TreeNode myTreeNode = new TreeNode("BBB");
treeView1.Nodes.Add(myTreeNode);
CreateChildTree(myTreeNode, "BBB", "BBB");
}
break;
case "2":
{
TreeNode myTreeNode = new TreeNode("CCC");
treeView1.Nodes.Add(myTreeNode);
CreateChildTree(myTreeNode, "CCC", "CCC");
}
break;
}

i++;
后面加:
public void CreateChildTree(TreeNode ParentNode, string NodeId, string ParentNodeText)
{
OleDbDataAdapter mycommand = new OleDbDataAdapter("select * from table where ParentTree='" + NodeId + "'", conn);//conn为数据库链接
conn.Open();
DataSet ds = new DataSet();
mycommand.Fill(ds, "table");
int i;
for (i = 0; i < ds.Tables["table"].Rows.Count; i++)
{
TreeNode myTreeNode = new TreeNode();
myTreeNode.Text = ds.Tables["table"].Rows[i].ItemArray[1].ToString();

string myTreeNodeText = myTreeNode.Text;
string ParentNodeTextS = ParentNodeText;
ParentNode.Nodes.Add(myTreeNode);
}
ds.Tables["table"].Clear();
conn.Close();
}

嘎嘎,感觉好复杂,不过我就是这样做出来了。一会儿再看看高人的做法,也学习学习