Thursday, March 22, 2012

Maintaining TreeView state across postbacks

Hello, all,

Is it possible to maintain treeview state across postbacks? I want my users to have a positive experience. I have a treeview on a masterpage. I want the treeview to maintain its expand/colapse state when the user navigates to different pages. An this be done? I'm using ASP.NET 2.0 with VB 2005.

Thanks!

StrickIf you're using ASP.NET 2.0, read this:
http://blog.binaryocean.com/PermaLink,guid,23808645-43b5-4e2a-afb1-53dc8da35636.aspx
I had a similar issue, but my treeview was on my master page and so when I visited another page the treeview got wiped...as you would expect.

The above code just records which nodes were expanded, and not the nodes themselves.

I played with the code and then simply tried to store the treeview's nodes collection in session. This seemed to work a treat. the code I came up with was:

Public Class TreeViewState

Public Shared Function IsTreeViewStateSaved(ByVal treeView As TreeView, ByVal key As String) As Boolean
Dim isSaved As Boolean = (HttpContext.Current.Session(key + treeView.ID) IsNot Nothing)

Return isSaved
End Function

Public Shared Sub SaveTreeView(ByVal treeView As TreeView, ByVal key As String)
HttpContext.Current.Session(key + treeView.ID) = treeView.Nodes
End Sub

Public Shared Sub RestoreTreeView(ByVal treeView As TreeView, ByVal key As String)
If IsTreeViewStateSaved(treeView, key) Then
treeView.Nodes.Clear()

Dim nodes As TreeNodeCollection = CType(HttpContext.Current.Session(key + treeView.ID), TreeNodeCollection)
For index As Integer = nodes.Count - 1 To 0 Step -1
treeView.Nodes.AddAt(0, nodes.Item(index))
Next index

HttpContext.Current.Session(key + treeView.ID) = Nothing
End If
End Sub

End Class

In the unload event of the treeview on the materpage use:

TreeViewState.SaveTreeview(tvwUsers, "Woka")

and in the master page load use:

If TreeViewState.IsTreeViewStateSaved(tvwUsers, "Woka") Then
TreeViewState.RestoreTreeViewState(tvwUsers, "Woka")
End If

Hope that helps.

Have I missed something with this code? I have made loads of daft errors today and no doubt, knowing my luck, one will be in the above.

Anyways, from what I can see it works a treat. The nodes, their properties and their expanded state gets restored.

Woof

0 comments:

Post a Comment