简体   繁体   中英

Populating TreeView from database C#

I have two tables in database in relation 1:N and I want to populate treeview with data. The problem is how to add childs to each parent. This is my code:

 private void PopulateTreeView()
    {
        try
        {
        DataTable dtProjekti = objDB.dbGetTable("SELECT * FROM tblProjekti");
        DataTable dtAktivnosti = objDB.dbGetTable("SELECT * FROM tblprojektakt");
        DataSet ds = new DataSet();
        ds.Tables.Add(dtProjekti);
        ds.Tables.Add(dtAktivnosti);
        ds.Relations.Add("childrens", dtProjekti.Columns["OznakaProjekta"], dtAktivnosti.Columns["OznakaProjekta"]);

        if (ds.Tables[0].Rows.Count > 0)
        {
            treeView1.Nodes.Clear();

             foreach (DataRow masterRow in ds.Tables[0].Rows)
            {
                //TreeNode masterNode = new TreeNode((string)masterRow["ParentName"], Convert.ToString(masterRow["ParentId"]));
                TreeNode masterNode = new TreeNode(masterRow["OznakaProjekta"].ToString());
                treeView1.Nodes.Add(masterNode);

                foreach (DataRow childRow in masterRow.GetChildRows("Children"))
                {
                       // missing code for adding childs to each parent     
                }
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Unable to populate treeview" + ex.Message);
    }

    }

    }

The childs are values from field Description.

I know how to manually add child to each parent but i stucked whan it should be dynamically.

The childs are values from field Description.

If you mean column Description . It should be something like this:

foreach (DataRow childRow in masterRow.GetChildRows("Children"))
{
    masterNode.Nodes.Add(new TreeNode(childRow["Description"].ToString()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM