Question Deleting Dynamically Populated Treeview Nodes using a loop


New member
Feb 2, 2012
Programming Experience
I have a Treeview that is populated from a Sql Db. The Db table that holds the Treeview data has a column for 'id' and a column for 'parent'. The Treeview executes and populates flawlessly using a For Each loop. I want to offer Content Management for the Treeview which requires the user to be able to add and/or remove root and/or child nodes. And here is my specific problem: when a user deletes a node there needs to be a loop that deletes all of the child nodes 'downstream' that are children of the node that was deleted.

I know most of the gurus on here like to see posted code so I will post what I have but it's not correct. What the code below does is it selects the children of the node that is being deleted and then populates those items to GridView2. This is where the loop needs to occur in order to then check for the children of the items that were just retrieved when the initial node was selected and so on until there are no more items. I've not included the RunQuery function as it just opens a connection string and executes a Sql statement. The Sub is attached to the RowDeleting event of a GridView which may be the wrong approach to this problem in and of itself but I'm posting to get feedback so there it is. Finally, I think I either need a For Each loop like I used to populate the TreeView on the user side or a While loop. Thanks to all in advance and forgive me if I have posted this in the wrong place. Also this is my first post ever and I'm mostly self-taught so thanks for the patience.

Protected Sub GridView1_RowDeleting _
(ByVal sender As [Object], _
ByVal e As GridViewDeleteEventArgs)

Dim Selected_Cell As TableCell                                     [COLOR=#696969]' Create a table cell[/COLOR]
Selected_Cell = Gridview1.Rows(e.RowIndex).Cells(1)     [COLOR=#696969]' Assign the value from the selected Gridview1 item[/COLOR]

Dim sqlQuery As New SqlCommand( _
"SELECT id From faq_Tree Where parent =" & Selected_Cell.Text & " AND owner =" & Session("ORGA") & " ")   [COLOR=#696969]' Sql Select statement that gets children of Selected_Cell[/COLOR]

Dim ResultSet As DataSet = RunQuery(sqlQuery)     [COLOR=#696969]' Executes the Sql command and populates result to DataSet[/COLOR]

Gridview2.DataSource = ResultSet

End Sub


Well-known member
Jul 18, 2006
Programming Experience
Best way to handle this is a recursive function that takes a single node (the one you want to delete) as it's input and, from there, the function will attempt to get the collection of child nodes from the passed nodes and then step through those nodes one at a time, passing them to the same function (hence the recursion). If the function doesn't manage to find any child nodes for the given node, it's safe to delete it.
Top Bottom