1

I have a linq object that i'm trying to fill a treeview from using c# winforms.

Sample

Column 1   Column 2   Column 3        
Test 1     Item A     Sub Item 1      
Test 1     Item A     Sub Item 2      
Test 1     Item A     Sub Item 3      
Test 1     Item B     Sub Item 1      
Test 1     Item B     Sub Item 2     
Test 1     Item B     Sub Item 3  

And fill the treeview like

Test 1 (CheckBox)
------Item A (CheckBox)
-------------Sub Item 1  (CheckBox)
-------------Sub Item 2  (CheckBox)
-------------Sub Item 3  (CheckBox)
------Item B (CheckBox)
-------------Sub Item 1  (CheckBox)
-------------Sub Item 2  (CheckBox)
-------------Sub Item 3  (CheckBox)

What is the easiest way to achieve this?

Thanks Sp

Steven
  • 2,148
  • 8
  • 33
  • 50
  • I see a lot of text that appears to be formatted for DOS. Can you please post some C# (the LINQ you said you wrote). Have you tried the winforms treeview control? – P.Brian.Mackey Aug 17 '12 at 13:43
  • i am using a winforms control but am unable to get the object to show properly – Steven Aug 17 '12 at 13:46
  • Better design to have table with ID, ParentID, Name fields and use recursion to fill treeview. Examples [here](http://stackoverflow.com/questions/3184115/how-to-populate-treeview?rq=1), [here](http://stackoverflow.com/questions/10814466/how-to-dynamically-populate-treeview-c?lq=1) and so on. – Renatas M. Aug 17 '12 at 13:47

1 Answers1

2

Well, if you perform the following query:

var query = data.GroupBy(item => item.Column1)
                .Select(group => group.GroupBy(item => item.Column2))
                .Select(group => group.Select(innerGroup => 
                    innerGroup.GroupBy(item => item.Column3)));

You will have all of the items grouped first by column1, then 2 and 3, so It's already in a tree structure. Now you just need to have 3 nested for loops to add the items to the treeview.

foreach (var outermostGroup in query)
{
    //add node for outermostGroup's key
    foreach (var middleGroup in outermostGroup)
    {
        //add child node of the above node for middleGroup key
        foreach (var innerGroup in middleGroup)
        {
            //add child node of the above node for innerGroup key
        }
    }
}

Clearly this code only works if there are a fixed number of columns with a fixed (max) depth. If you don't know the number of columns and can have an arbitrary depth then you'd need a fairly radically different approach.

Servy
  • 202,030
  • 26
  • 332
  • 449