无法从“字符串”转换为“ System.Web.UI.WebControls.TreeNode”

0 .net c# treeview tree sharepoint

邓诺(Dunno)为什么会变得愚蠢或更像是感觉更少的错误,通常我们将字符串添加到treeNode,然后为什么不在此代码中,

groupNode.ChildNodes.Add(UserPair.Value);   
Run Code Online (Sandbox Code Playgroud)

(为什么不 ?)

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        try
        {
            int Index = 0;
            TreeView tree = new TreeView();
            TreeNode groupNode; 
            Dictionary<int, string> GroupList = new Dictionary<int, string>();
            Dictionary<int, string> UserList = new Dictionary<int, string>();
            List<string> IndividualUserList = new List<string>();

            foreach (SPUser user in SPContext.Current.Web.Users)
            {
                string groupName = FormatUserLogin(user.Name);

                if (groupName != "" && groupName != "System Account")
                    IndividualUserList.Add(groupName);
                else if (user.IsDomainGroup && !string.IsNullOrEmpty(groupName) && 
                    Directory.DoesGroupExist(groupName))
                {
                    Index++;
                    GroupList.Add(Index, groupName);
                    List<ADUser> adUsers = Directory.GetUsersFromGroup(groupName);

                    foreach (ADUser member in adUsers)
                    {
                        if (member != null && !string.IsNullOrEmpty(member.DisplayName))
                            UserList.Add(Index, member.DisplayName);
                    }
                }
            }

            IndividualUserList.Sort();

            foreach (string Item in IndividualUserList)
            {
                groupNode = new TreeNode(Item);
            }

            foreach (KeyValuePair<int, string> GroupPair in GroupList)
            {
                groupNode = new TreeNode(GroupPair.Value);
                foreach (KeyValuePair<int, string> UserPair in UserList)
                {
                    if (UserPair.Key == GroupPair.Key)
                        groupNode.ChildNodes.Add(UserPair.Value);
                }
            }

            tree.Nodes.Add(groupNode);

            this.Controls.Add(tree);
        }
        catch (Exception)
        {
            //loggingit
        }
    }
Run Code Online (Sandbox Code Playgroud)

我以为treeNodes可以向它们添加字符串值,如果我的代码中有逻辑错误或错误,请让我知道。

干杯

回答

if (UserPair.Key == GroupPair.Key)
                    {
                        TreeNode userNode = new TreeNode(UserPair.Value);
                        groupNode.ChildNodes.Add(userNode);
                    }
Run Code Online (Sandbox Code Playgroud)

Tun*_*ung 5

groupNode.ChildNodesTreeNodeCollection。您只能将类型的对象添加TreeNode到集合中。更改此行:

groupNode.ChildNodes.Add(UserPair.Value);
Run Code Online (Sandbox Code Playgroud)

至:

groupNode.ChildNodes.Add(new TreeNode(UserPair.Value));
Run Code Online (Sandbox Code Playgroud)