If you must use code like this, filtering the datawindow or datastore whilst trying to read from it as you are is just going to create pain.
Why not use the query from your existing datawindow as the datasource for a treeview datawindow? If your front end can't access the database then get the data from a datastore and load it into the treeview datawindow (as you're already trying to do).