来自数据库的TreeView,带null

时间:2014-05-28 12:13:29

标签: c# treeview

我在c#中从数据库中填充树视图时遇到了问题。该表如下所示:

| code    | description | attached to | 
---------------------------------------
| P001    | TEST001     | NULL        |
| P0001   | TEST002     | P001        |
| P002    | TEST003     | NULL        |
| P00201  | TESTXXX     | P002        |
| P00222  | TESTXXX     | P002        |
| P002020 | TESTSSS     | P00222      |

这不起作用。

protected void PopulateTreeView(TreeNodeCollection parentNode, string parentID, DataTable folders)
    {

        foreach (DataRow folder in folders.Rows)
        {
            // if (Convert.ToInt32(folder["Attached to"]) == parentID)
            if (string.IsNullOrEmpty(folder["Attached to"].ToString()))
            {

                String key = folder["code"].ToString();
                String text = folder["description"].ToString();
                TreeNodeCollection newParentNode = parentNode.Add(key, text).Nodes;
                //PopulateTreeView(newParentNode, Convert.ToInt32(folder["code"]), folders);
                PopulateTreeView(newParentNode, folder["code"].ToString(), folders);
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

问题出在你的If条件上。您应该搜索附加到parentID的行。这是修正后的测试方法:

    public void Test_PopulateTreeViews()
    {
        var rootNode = new TreeNode();
        var folders = new DataTable();

        folders.Columns.Add("code");
        folders.Columns.Add("description");
        folders.Columns.Add("Attached to");
        folders.Rows.Add("P001", "TEST001", string.Empty);
        folders.Rows.Add("P0001", "TEST002", "P001");
        folders.Rows.Add("P002", "TEST003", null);
        folders.Rows.Add("P00201", "TEST003", "P002");
        folders.Rows.Add("P00222", "TESTXXX", "P002");
        folders.Rows.Add("P002020", "TESTSSS", "P00222");

        PopulateTreeView(rootNode, string.Empty, folders);
    }

    private void PopulateTreeView(TreeNode parentNode, string parentID, DataTable folders)
    {
        foreach (DataRow folder in folders.Rows)
        {
            if (folder["Attached to"].ToString() == parentID)
            {
                String key = folder["code"].ToString();
                String text = folder["description"].ToString();

                var newParentNode = new TreeNode(key, text);
                parentNode.ChildNodes.Add(newParentNode);
                PopulateTreeView(newParentNode, folder["code"].ToString(), folders);
            }
        }
    }
});