views:

712

answers:

3

I've developed an application that populates a treeview from hierachical data in a database.

I've designed it to use lazy-loading so it only gets the child nodes when a node is expanded.

My problem is that obviously I don't know if a node has children unless I make a call to the database and look. Currently I have implemented a dummy child node, so that the [+] icon appears for all nodes, I then remove this dummy node and get the real child nodes in the BeforeExpand event.

This means I get a [+] icon for nodes that don't have child nodes, so the user clicks the expand icon and there's nothing show which looks a bit shoddy.

What is the preffrred method for handling child nodes in a lazy-load treeview? If I make a call to the database to see if there are child nodes then I might as well just load the child nodes and forget about lazy loading right?

One thought I had was to store a 'HasChildren' flag in the database, so I can selectively create my dummy child node only for the nodes that actually do have child nodes.

Sorry for rambling on, I'm very interested to see what other people think...

+1  A: 

change your initial query to return all the same data, but also a count of children. when the children count is not zero show the [+]. post your schema and query for help getting the count

KM
+3  A: 

When you make a call, check for children along with the node data:

SELECT  tp.*, 
        (
        SELECT  1
        FROM    table tc
        WHERE   tc.parent = tp.id
        LIMIT 1
        ) AS has_children
FROM    table tp

You don't have to count, it may be long.

Just check that at least one child exists.

Quassnoi
+1  A: 

My preferred solution to this problem is to implement pre-ordered tree traversal on your set of hierarchical data. See http://dev.mysql.com/tech-resources/articles/hierarchical-data.html for an example implementation.

The point is that if you maintain a left and right value for each node, then if the left value and right value differ by more than one, that node has children.

The only notable downside of this approach is that you have to actively maintain those left and right values when altering the structure of the nodes.

Kazar