Search code examples
c#treeviewdevexpressnodes

C# TreeView duplicate nodes and child


I have created a treeview but i have a problem.

In my code nodes was added duplicately like this;

treeview

treeview

How can i solve and code this issue?

My data is;

Column1     Column2
category      subcategory
category      subcategory2
category      subcategory3 
test          subtest
test          subtest2

My code;

SqlConnection con = new SqlConnection("Data Source=test;Initial Catalog=test;Integrated Security=True;");

DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from mytable", con);
da.Fill(dt);

treeView1.Nodes.Add("Documents");

foreach (DataRow dr in dt.Rows)
{            
     TreeNode nod = new TreeNode(dr["kategori"].ToString());
     nod.Nodes.Add(dr["altkategori"].ToString());
     treeView1.Nodes.Add(nod);
}

Solution

  • The fact is that you create another category and test node respectively for each subcategory and subtest.

    Using LINQ GroupBy method will group your altkategori inside the same kategori node:

    treeView1.Nodes.Add("Documents");
    
    foreach (IGrouping<string, string> kategori in dt.Rows.Cast<DataRow>().GroupBy(dr => dr["kategori"].ToString(), dr => dr["altkategori"].ToString()))
    {
        TreeNode nod = new TreeNode(kategori.Key); // node with kategori text
    
        foreach (string altkategori in kategori)   // foreach subnode in kategori
            nod.Nodes.Add(altkategori);            // add another altkategori node in
    
        treeView1.Nodes.Add(nod);                  // add your final kategori node
    }
    

    Tell me if you are not confident about LINQ, and/or if you need more explanation.