asp.net中的错误树视图

时间:2015-06-03 10:04:41

标签: asp.net treeview

救救我! 这段代码有什么问题 TreeNode中的错误ParentNode = new TreeNode(children);

public partial class ViewTree : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String[] nodeStr = { "Puasa", "Puasa Sunah", "Ramadhan", "Puasa Kamis", "Puasa Senin" };
        List<TreeNode> childs = new List<TreeNode>();
        foreach (String s in nodeStr)
        {
            childs.Add(new TreeNode(s));
        }
        TreeNode[] children = childs.ToArray();
        TreeNode ParentNode = new TreeNode(children);
        TreeViewMenu.Nodes.Add(ParentNode);
    }
}

1 个答案:

答案 0 :(得分:0)

基于MSDN TreeNode构造函数没有TreeNode[]参数,所以我假设您在尝试使用不存在的功能时出现了并发错误。如果要为该节点指定子节点,则需要执行以下操作:

String[] nodeStr = { "Puasa", "Puasa Sunah", "Ramadhan", "Puasa Kamis", "Puasa Senin" };
TreeNode ParentNode = new TreeNode();
foreach (String s in nodeStr)
{
    TreeNode childNode = new TreeNode(s);
    // sample of adding child nodes
    string[] valuee = new string[] { "aaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbb", "cccccccccccccccccc", "dddddddddddddddddd", "eeeeeeeeeeeeeeeeee" }; 

    foreach(string c in valuee)
    {
        childNode.ChildNodes.Add(new TreeNode(c));
    }

    ParentNode.ChildNodes.Add(childNode);
}
TreeViewMenu.Nodes.Add(ParentNode);

<强>更新

我添加了为父节点

中的每个子节点添加相同值的示例

<强> UPDATE2

以下是用户点击展开节点后如何在运行时添加项目的示例。

ASPX内容:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<asp:TreeView ID="TreeViewMenu" runat="server" OnTreeNodePopulate="TreeViewMenu_OnTreeNodePopulate" ExpandDepth="1">

</asp:TreeView>

CS内容:

public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            String[] nodeStr = { "Puasa", "Puasa Sunah", "Ramadhan", "Puasa Kamis", "Puasa Senin" };
            TreeNode ParentNode = new TreeNode();
            foreach (String s in nodeStr)
            {
                TreeNode node = new TreeNode(s);
                node.PopulateOnDemand = true;
                ParentNode.ChildNodes.Add(node);
            }
            TreeViewMenu.Nodes.Add(ParentNode);
        }
    }

    protected void TreeViewMenu_OnTreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        string[] value = new string[] { "aaaaaaaaaaaaaaaaaa", "bbbbbbbbbbbbbbbbbb", "cccccccccccccccccc", "dddddddddddddddddd", "eeeeeeeeeeeeeeeeee" };

        foreach (var v in value)
        {
            e.Node.ChildNodes.Add(new TreeNode(v));
        }
    }
}