Search code examples
c#winformsnhibernatetreeviewbackgroundworker

How do I add Nodes through Backgroundworker to a TreeView from a Database and reload Children while expanding a Node in Windows Forms C#?


I have a Nhibernate Database which provide the Data as hierarchical List<>. I have a TreeView in my Windows Forms GUI and a Backgroundworker which populate the TreeView with all Root Nodes and their Children (nothing more because of Lazy loading exception from NHibernate but this is okay because I expect that the user will have many Nodes in the TreeView).

The process to add the Root nodes and their children to the TreeView works pretty well but when I click on a Node to expand it all children of the children should be loaded from the Database and added to the TreeView. The Nodes are requested successfully from the Database and are stored in the buffer list (when Click on the node to expand it).

After that I tried a few ideas like rebuild the TreeView and repopulate it completely but with this solution I got the Problem that all expanded Nodes are collapsed so I tried to store the node that is expanded and it worked. But I am not quite happy with this solution, I got the feeling it can be done easier, because I don't want to repopulate the TreeView every time the User is expanding a Node.

How can I reload the Children of a TreeNode from the Database and display it in the TreeView without repopulating the whole TreeView?


Solution

  • This SO Question should provide some help on the lazy loading.

    It uses a threadpool instead of a background worker which you can find arguments for/against on google, but in my opinion its not a bad choice to use the threadpool in Winforms.

    With the above post to guide you, pass the node that is being expanded through to worker. Once you have the data required to populate the node, use the standard If ##.InvokeRequired Pattern to do the actual work on the node.

    Hope that helps.