Sql – How to only display a TreeView expand sign [+] if children exist

databaselazy-loadingsqltreeview

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…

Best Answer

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.

Related Topic