使用重复键填充树视图

Populate treeview with Duplicate Keys

我创建树视图时没有使用 Infragistics Framework 的 ID 或 PARENTID。效果很好。

但是有时子节点名称会变得相同。这对我来说没问题。

这是我填充树视图的代码。基本上分组依据 'Type'。哪些是根节点。然后使用 'Name'

为该根节点添加子节点
private void populateTreeview(DataTable dt)
{
    var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("Type"));

    foreach (var group in groups)
    {
        UltraTreeNode node = utObjects.Nodes.Add(group.Key);

        foreach (string name in group.Select(x => x.Field<string>("Name")))
        {
            node.Nodes.Add(name); // Throws an error here : 'Key Already Exist'
        }
    }
}

如何允许重复键?

您不能允许重复键。
根据 Key property documentation:

Keys must be unique throughout the UltraTree control.

Add 方法的文档显示了 5 个重载。
One 其中接受两个字符串 - 第一个是键,另一个是文本。
您应该使用此重载将节点添加到树中。
您可以选择您想要设置密钥的任何方法,我认为对您当前代码影响最小的最简单方法是使用 Guid.NewGuid().ToString() 作为密钥。指南实际上保证是唯一的:

private void populateTreeview(DataTable dt)
    {
        var groups = dt.AsEnumerable().GroupBy(x => x.Field<string>("Type"));

        foreach (var group in groups)
        {
            UltraTreeNode node = utObjects.Nodes.Add(group.Key);

            foreach (string name in group.Select(x => x.Field<string>("Name")))
            {
                // Generates a unique key for each node.
                node.Nodes.Add(Guid.NewGuid().ToString(), name); 
            }
        }
    }