我有以下代码:
TreeNode parentNode1 = new TreeNode("CONNECTING RODS");
TreeViewNav.Nodes.Add(parentNode1);
string[] subNodes =
{
"STOCK", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"
};
foreach (var node in subNodes)
{
parentNode1.ChildNodes.Add(node);
}
所以我基本上试图以更简洁的方式做到这一点:
TreeNode childNodeA = new TreeNode("A");
TreeNode childNodeB = new TreeNode("B");
TreeNode childNodeC = new TreeNode("C");
TreeNode childNodeD = new TreeNode("D");
TreeNode childNodeE = new TreeNode("E");
TreeNode childNodeF = new TreeNode("F");
parentNode1.ChildNodes.Add(childNodeA);
parentNode1.ChildNodes.Add(childNodeB);
parentNode1.ChildNodes.Add(childNodeC);
parentNode1.ChildNodes.Add(childNodeD);
parentNode1.ChildNodes.Add(childNodeE);
parentNode1.ChildNodes.Add(childNodeF);
我在parentNode1.ChildNodes.Add(node);
行上收到错误。
错误是
'串'不能分配给参数类型 ' System.Web.UI.WebControls.TreeNode'
我知道它,因为我已经使数组成为一个字符串数组,但我不知道如何做到这一点任何帮助将非常感激:)
答案 0 :(得分:1)
ChildNodes.Add
期待TreeNode
个对象,但您传递的是string
。你应该:
foreach (var node in subNodes)
{
parentNode1.ChildNodes.Add(new TreeNode(node));
}
关于添加子子节点:
foreach (var node in subNodes)
{
var treeNode = new TreeNode(node);
//Call function that returns all the sub-sub nodes
//Assign those nodes to 'treeNode' using another foreach - or better still have this as a recursive function
parentNode1.ChildNodes.Add(treeNode);
}
答案 1 :(得分:1)
你应该使用TreeNode类型的字符串试试这个,
foreach (var node in subNodes)
{
parentNode1.ChildNodes.Add(new TreeNode(node));
}