Asked by:
Maintaining treeview state across your site in a master page, and no expandcollapse icons.

Question
-
User1613131222 posted
Finally, I got it! :-) No more limitations on navigation ever, ever, ever....
This code does the following:
Lets you expand and collapse nodes as you prefer.
Lets you navigate to whatever page (Also pages unlisted in the SiteMap or DB) across your site without no trouble.
Maintains the state of the treeview.
Lets you get rid of those ridiculous + and - expand/collapse icons.
I used the OnSelectedNodeChanged event, and ShowExpandCollapse attrib of the treeview to make this work.This is the treeview code for a master page:
<asp:TreeView ID="TreeView1" runat="server" DataSourceID="xmlDataSource" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged"
ExpandDepth="0" MaxDataBindDepth="10" PopulateNodesFromClient="False" ShowExpandCollapse="False"
OnDataBound="TreeView1_DataBound">
</asp:TreeView>Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
// Datastuff for binding the XML source or whatever here:
....
// Disable ExpandDepth if the TreeView's expand/collapse
// state is stored in session.
if (Session["TreeViewState"] != null)
TreeView1.ExpandDepth = -1;
}
public void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
//If the selected node is changed and we are working with the top node (If you want the ExpandCollapse func further dow, duplicate this part..)
if (TreeView1.SelectedNode.Depth == 0)
{
TreeView1.CollapseAll(); //Collapse all nodes
TreeView1.SelectedNode.Expand(); node//Expand the selected node
}
//Save the state of the treeview
if (IsPostBack)
{
List<string> list = new List<string>(16);
SaveTreeViewState(TreeView1.Nodes, list);
Session["TreeViewState"] = list;
}
//All done, lets redirect to the new page
if (IsPostBack)
{
// Here i use the "value" attribute of the treeview node, this must be used instead of the NavigateURL attribute whitch makes the
//OnSelectedNodeChange event break in the first place
string fw = string.Empty;
fw = TreeView1.SelectedValue.ToString();
Response.Redirect(fw.ToString());
}
}
//Save or reapply the state of the treeview
protected void TreeView1_DataBound(object sender, EventArgs e)
{
if (Session["TreeViewState"] == null)
{
// Record the TreeView's current expand/collapse state.
List<string> list = new List<string>(16);
SaveTreeViewState(TreeView1.Nodes, list);
Session["TreeViewState"] = list;
}
else
{
// Apply the recorded expand/collapse state to the TreeView.
List<string> list = (List<string>)Session["TreeViewState"];
RestoreTreeViewState(TreeView1.Nodes, list);
}
}
//The save state func...
private void SaveTreeViewState(TreeNodeCollection nodes, List<string> list)
{
// Recursivley record all expanded nodes in the List.
foreach (TreeNode node in nodes)
{
if (node.ChildNodes != null && node.ChildNodes.Count != 0)
{
if (node.Expanded.HasValue && node.Expanded == true && !String.IsNullOrEmpty(node.Text))
list.Add(node.Text);
SaveTreeViewState(node.ChildNodes, list);
}
}
}
//The restore state func...
private void RestoreTreeViewState(TreeNodeCollection nodes, List<string> list)
{
foreach (TreeNode node in nodes)
{
// Restore the state of one node.
if (list.Contains(node.Text))
{
if (node.ChildNodes != null && node.ChildNodes.Count != 0 && node.Expanded.HasValue && node.Expanded == false)
node.Expand();
}
else
{
if (node.ChildNodes != null && node.ChildNodes.Count != 0 && node.Expanded.HasValue && node.Expanded == true)
node.Collapse();
}
// If the node has child nodes, restore their state, too.
if (node.ChildNodes != null && node.ChildNodes.Count != 0)
RestoreTreeViewState(node.ChildNodes, list);
}
}
Credits:
Much of the code and ideas where borowed from Jeff Prosises MSDN Wicked Code article here:
http://msdn.microsoft.com/msdnmag/issues/06/06/WickedCode/default.aspx
(DotNET and Atlas example code included in article, worth a look@)
Happy coding! [cool]
For those of you that want the Data and xsl code, here it is:
Just as you know it, this way of doing it does not support breadcrumbs, so you might want to do a SiteMapDataSource thingey instead.
(I build my own custom breadcrumbs from the DataSource, but thats another chapter..)
Treeview DataBindings:
<DataBindings>
<asp:TreeNodeBinding DataMember="MenuItem" TextField="Text" ToolTipField="ToolTip" PopulateOnDemand="True" SelectAction="SelectExpand"
ValueField="MyVal" />
</DataBindings>
The Datasource build:
DataSet ds = new DataSet();
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"];
using (SqlConnection conn = new SqlConnection(cs.ConnectionString))
{
string sql = "Select MenuID, Text, Description, ParentID, Page from Menu";
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
da.Dispose();
}
ds.DataSetName = "Menus";
ds.Tables[0].TableName = "Menu";
DataRelation relation = new DataRelation("ParentChild",
ds.Tables["Menu"].Columns["MenuID"],
ds.Tables["Menu"].Columns["ParentID"],
true);
relation.Nested = true;
ds.Relations.Add(relation);
xmlDataSource.Data = ds.GetXml();
The xsl:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" encoding="utf-8"/>
<!-- Find the root node called Menus and call MenuListing for its children -->
<xsl:template match="/Menus">
<MenuItems>
<xsl:call-template name="MenuListing" />
</MenuItems>
</xsl:template>
<!-- Allow for recusive child node processing -->
<xsl:template name="MenuListing">
<xsl:apply-templates select="Menu" />
</xsl:template>
<xsl:template match="Menu">
<MenuItem>
<!-- Convert Menu child elements to MenuItem attributes -->
<xsl:attribute name="Text">
<xsl:value-of select="Text"/>
</xsl:attribute>
<xsl:attribute name="ToolTip">
<xsl:value-of select="Description"/>
</xsl:attribute>
<xsl:attribute name="MyVal">
<xsl:value-of select="Page"/>
<xsl:text>?Menu=</xsl:text>
<xsl:value-of select="MenuID"/>
</xsl:attribute>
<!-- Call MenuListing if there are child Menu nodes -->
<xsl:if test="count(Menu) > 0">
<xsl:call-template name="MenuListing" />
</xsl:if>
</MenuItem>
</xsl:template>
</xsl:stylesheet>Friday, September 1, 2006 3:09 PM
All replies
-
User-138510437 posted
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' Disable ExpandDepth if the TreeView's expand/collapse
' state is stored in session.
If ViewState("TreeViewState") IsNot Nothing Then
Me.MasterTreeView.ExpandDepth = -1
End If
End Sub
Protected Sub MasterTreeView_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs)
'If the selected node is changed and we are working with the top node (If you want the ExpandCollapse func further dow, duplicate this part..)
If MasterTreeView.SelectedNode.Depth = 0 Then
MasterTreeView.CollapseAll() ' Collapse all nodes
MasterTreeView.SelectedNode.Expand()
End If
' Save the state of the treeview
If IsPostBack Then
Dim list As ArrayList = New ArrayList
SaveTreeViewState(MasterTreeView.Nodes, list)
Session("TreeViewState") = list
End If
' All done, lets redirect to the new page
If IsPostBack Then
' Here i use the "value" attribute of the treeview node, this must be used instead of the NavigateURL attribute whitch makes the
' OnSelectedNodeChange event break in the first place
Dim fw As String = String.Empty
fw = MasterTreeView.SelectedValue.ToString
Response.Redirect(fw.ToString)
End If
End Sub
' Save or reapply the state of the treeview
Protected Sub MasterTreeView_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
If Session("TreeViewState") Is Nothing Then
' Record the TreeViews current expand/collapse state.
Dim list As ArrayList = New ArrayList
SaveTreeViewState(MasterTreeView.Nodes, list)
Session("TreeViewState") = list
Else
'Apply the recorded expand/collapse state to the TreeView.
Dim list As ArrayList = CType(Session("TreeViewState"), ArrayList)
RestoreTreeViewState(MasterTreeView.Nodes, list)
End If
End Sub
'The save state func...
Private Sub SaveTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList)
' Recursivley record all expanded nodes in the List.
For Each node As TreeNode In nodes
If (node.ChildNodes Is Nothing And node.ChildNodes.Count = 0) Then
If node.Expanded.HasValue Or CBool(node.Expanded) Or String.IsNullOrEmpty(node.Text) Then
list.Add(node.Text)
SaveTreeViewState(node.ChildNodes, list)
End If
End If
Next
End Sub
'The restore state func...
Private Sub RestoreTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList)
For Each node As TreeNode In nodes
If list.Contains(node.Text) Then
If (node.ChildNodes Is Nothing) Or (node.ChildNodes.Count = 0) Or node.Expanded.HasValue Or Not CBool(node.Expanded) Then
************Throws an exception on the line above saying the 'node.Expanded' must have a value*****
node.Expand()
End If
Else
If (node.ChildNodes Is Nothing) Or (node.ChildNodes.Count = 0) Or node.Expanded.HasValue Or CBool(node.Expanded) Then
node.Collapse()
End If
End If
If node.ChildNodes Is Nothing Or node.ChildNodes.Count = 0 Then
RestoreTreeViewState(node.ChildNodes, list)
End If
Next
End Sub
</script>
Hope you can help!!!
Cheers
Mark
Thursday, September 7, 2006 2:18 PM -
User1613131222 posted
Hi, it looks like you are trying to rewrite my code there.. I am no VB dude, but one error is obvious.. && does not mean "OR", but "AND"..
[8-|]
Friday, September 8, 2006 7:20 AM -
User-1148141394 posted
I tried your code and got a System.StackOverflowException on the line "node.Collapse()" in "RestoreTreeViewState()". My TreeView has lots of nodes (about 500). May that be the problem?Friday, September 8, 2006 10:10 AM -
User352454651 posted
I tried doing something similar to a Menu. My menuItems had NavigateUrl properties which I tried to removed and added an OnMenuItemClick handler. In this I used the same lines like Response.Redirect instead of using the NavigateUrl. My menu does not have any state other than the menuItem selected color change which I have ignored for now. I can see the postback happening and the Response.Redirect working but still the entire Master pageheader (menu resides here) reloads. I have the menu inside a table and the table is wrapped inside an UpdatePanel.
Any idea why it is not working?
Thanks,
Ghanshyam
Thursday, October 12, 2006 3:21 AM -
User-138510437 posted
Correct VB translation should be...
Hope this helps someone although It doesn't work if you use CSS adapters, well not yet anyway![:)]
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' Disable ExpandDepth if the TreeView's expand/collapse
' state is stored in session. If Session("TreeViewState") IsNot Nothing Then Me.MasterTreeView.ExpandDepth = 0 End If End SubSaveTreeViewState(MasterTreeView.Nodes, list)
Session(
"TreeViewState") = list Else 'Apply the recorded expand/collapse state to the TreeView. Dim list As ArrayList = CType(Session("TreeViewState"), ArrayList)RestoreTreeViewState(MasterTreeView.Nodes, list)
End If End SubSaveTreeViewState(MasterTreeView.Nodes, list)
Session(
"TreeViewState") = list End If End Sub Protected Sub MasterTreeView_TreeNodeExpanded(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) If IsPostBack Then Dim list As ArrayList = New ArrayListSaveTreeViewState(MasterTreeView.Nodes, list)
Session(
"TreeViewState") = list End If End Sublist.Add(node.Text)
SaveTreeViewState(node.ChildNodes, list)
End If End If Next End Sub Private Sub RestoreTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList) For Each node As TreeNode In nodes ' Restore the state of one node. If list.Contains(node.Text) Then If (node.ChildNodes IsNot Nothing AndAlso _(node.ChildNodes.Count <> 0)
AndAlso _node.Expanded.HasValue
AndAlso _node.Expanded.GetValueOrDefault(
False)) Thennode.Expand()
End If ElseIf (node.ChildNodes IsNot Nothing AndAlso _node.ChildNodes.Count <> 0
AndAlso _node.Expanded.HasValue
AndAlso _node.Expanded.GetValueOrDefault(
True)) Thennode.Collapse()
End If ' If the node has child nodes, restore their states, too. If (node.ChildNodes IsNot Nothing AndAlso node.ChildNodes.Count <> 0) ThenRestoreTreeViewState(node.ChildNodes, list)
End If NextFriday, November 17, 2006 12:28 PM -
User1613131222 posted
Ghanshyam; One trick i have used with menus is to simply append a unique node name to the navigate url, and then walk through the menu and mark the top parent selected.. That will apply your formatting through postbacks.Tuesday, November 21, 2006 10:16 AM -
User1613131222 posted
Ghanshyam; One trick i have used with menus is to simply append a unique node name to the navigate url, and then walk through the menu and mark the top parent selected.. That will apply your formatting through postbacks.Tuesday, November 21, 2006 10:16 AM -
User1613131222 posted
Ghanshyam; One trick i have used with menus is to simply append a unique node name to the navigate url, and then walk through the menu and mark the top parent selected.. That will apply your formatting through postbacks.Tuesday, November 21, 2006 10:17 AM -
User1613131222 posted
Mark Evans..
"Correct VB translation should be..."
Excellent!
"Hope this helps someone although It doesn't work if you use CSS adapters, well not yet anyway!
"
Right.. I am working on some adapterstuff now, so if i find a good workaround i will post it!
Thanks for the heads up!
Tuesday, November 21, 2006 10:20 AM -
User-869093755 posted
I have tried this code and it is not working. I noticed the corrected VB code did not include the MasterTreeView_SelectedNodeChanged sub so I included that but it is still not working.
I have my treeview bound to a sitemap.map. Is that the problem here?
I have the code in my masterpage but when I navigage to another page in my treeview, it is not keeping the state of the treeview, it is collapsing it again.
Friday, December 29, 2006 8:44 PM -
User623503027 posted
Did you found the solution KerrAVon, cause I have the same problem here ?
Or if someone else could help me (us) ?
Thanks !
Tuesday, January 9, 2007 9:14 AM -
User1613131222 posted
Do you get anything if you write the contents of the session to the page?
Tuesday, January 9, 2007 9:32 AM -
User623503027 posted
Sorry, no.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load lblTest.Text = Session("TreeViewState") End Sub
PS :
I didn't add a TreeViewGeneralMenu_SelectedNodeChanged. If I have to, what should I add exactly (just to be sure I don't make mistakes there...)
Tuesday, January 9, 2007 10:03 AM -
User1613131222 posted
"TreeViewGeneralMenu_SelectedNodeChanged"
I am no VB guy, but somewhere the SelectedNodeChanged have to be utilized to do two things;
#1: Save the treeviewstate
#2: Redirect
In that order.. (Look at the C# code on the top for explainations)So far it sounds like you have set the treeview to navigate instead of select, whitch could produce this result.
Tuesday, January 9, 2007 11:17 AM -
User-869093755 posted
Yes, I figured mine out. I did not set the PopulateNodesFromClient="False" therefore it did not keep the state.
If you are still having problems, I can post my entire VB code.
Tuesday, January 9, 2007 6:24 PM -
User623503027 posted
Yes, that was the problem !
I have one problem left... when I set the ShowExpandCollapse="False", I cann't expand my treeview anymore.
It just opens the page I set in my web.sitemap (f.e. : ExplanationEmployees.aspx).
<siteMapNode url="Default.aspx" title="$resources: Web.sitemap, Default" description=""> <siteMapNode url="SecureMembers/ExplanationPages/ExplanationEmployees.aspx" title="$resources: Web.sitemap, ExplanationEmployees" > <siteMapNode url="SecureMembers/Employees/Employees-Management.aspx" title="$resources: Web.sitemap, EmployeesManagement" /> <siteMapNode url="SecureMembers/Employees/Employees-GlobalFinance.aspx" title="$resources: Web.sitemap, EmployeesGlobalFinance" /> </siteMapNode> ... </siteMapNode>
Any idea ?
Wednesday, January 10, 2007 3:05 AM -
User-2035194016 posted
Could you also post the XML data file used to populate the tree. I find it awkward trying to come up with an XML test file when all I've got is the XLS file.
Also, I'm using VS.NET 2005 but I get an error everywhere where you have List<> in your code. I replaced it with ArrayList, like guy who posted the VB.NET code.
Do you also have a website I can view online that shows your code actually being used?
Thanks
Thursday, January 11, 2007 3:03 AM -
User1613131222 posted
"Could you also post the XML data file used to populate the tree."
I don't know if that Q was for me or not, but if so i must poit to the original post that describes a databasedriven solution. No XML there..
You can find the List in: System.Collections.Generic
A handy way to locate the component info in VS2005 is to use the Object Browser. Just enter "List" and voilá.. :-)Thursday, January 11, 2007 5:25 AM -
User623503027 posted
That's indead my problem.
What I did (and this works !) : I deleted everything of TreeViewGeneralMenu_SelectedNodeChanged and added next code :
Protected Sub TreeViewGeneralMenu_TreeNodeDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles TreeViewGeneralMenu.TreeNodeDataBound If Request.Url.PathAndQuery = e.Node.NavigateUrl Then e.Node.ExpandAll() End If End Sub
Do you see any problem with that ?
Thursday, January 11, 2007 7:29 AM -
User1613131222 posted
I am not sure how that will handle different QueryStrings on the same page in VB, but other than that i cant see any problem..
Also; You loose some functionality when you set the TreeView action to Navigate instead of Select, but hey.. if it works for you.. :-)
Thursday, January 11, 2007 7:50 AM -
User623503027 posted
Just out curiosity : where do you define the action of the Treeview (Navigate or Select) ?
Thursday, January 11, 2007 9:05 AM -
User1613131222 posted
In the databindingssection of the treeview..
Example:
<asp:TreeView ID="TreeViewMenu" runat="server" DataSourceID="xmlDataSource">
<DataBindings>
<asp:TreeNodeBinding DataMember="MenuItem" TextField="Text" ToolTipField="ToolTip"PopulateOnDemand="True" SelectAction="SelectExpand" ValueField="MyVal" />
</DataBindings>
<SelectedNodeStyle BackColor="#E7E7E5" ForeColor="Black" />
</asp:TreeView>Thursday, January 11, 2007 9:31 AM -
User1805008792 posted
I think selectaction is property of TreeNode, so you can asign selectaction to individual nodes
TreeNode.SelectAction =
TreeNodeSelectAction.Select;I think using this in <asp:TreeNodeBinding will also assign it to each node.
Thursday, January 11, 2007 10:11 AM -
User-1523261865 posted
On the last sub, after copying and pasting the text into my MasterPage.master.vb file, that is after posting this:
Private Sub RestoreTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList) For Each node As TreeNode In nodes ' Restore the state of one node. If list.Contains(node.Text) ThenIf
(node.ChildNodes IsNot Nothing AndAlso _(node.ChildNodes.Count <> 0)
AndAlso
_ node.Expanded.HasValueAndAlso
_ node.Expanded.GetValueOrDefault(False)) Then node.Expand() End IfElseIf
(node.ChildNodes IsNot Nothing AndAlso _node.ChildNodes.Count <> 0AndAlso
_ node.Expanded.HasValueAndAlso
_ node.Expanded.GetValueOrDefault(True)) Then node.Collapse() End If ' If the node has child nodes, restore their states, too. If (node.ChildNodes IsNot Nothing AndAlso node.ChildNodes.Count <> 0) ThenRestoreTreeViewState(node.ChildNodes, list)
End If Next End SubI get errors in Visual Web Developer Express Edition, that say this: (as shown below)... Why the syntax errors? Why the ) expected? Anyone know? Errors are in the LAST sub only, apparently.
1. ')' expected
2. Syntax error
3. Syntax error
4. Name '_node' is not declared
5. ')' expected
6. Syntax error
7. Syntax error
Wednesday, January 24, 2007 5:35 PM -
User623503027 posted
Try this :
node.Expand()
End If ElseIf (node.ChildNodes IsNot Nothing AndAlso node.ChildNodes.Count <> 0 AndAlso node.Expanded.HasValue AndAlso node.Expanded.GetValueOrDefault(True)) Thennode.Collapse()
End If ' If the node has child nodes, restore their states, too. If (node.ChildNodes IsNot Nothing AndAlso node.ChildNodes.Count <> 0) ThenRestoreTreeViewState(node.ChildNodes, list)
End If Next End SubThursday, January 25, 2007 6:24 AM -
User-1523261865 posted
very nice, that works perfectly. thank you.
However, now that that is cleared up, I have ONE remaining error:
Compiler Error Message: BC30456: 'TreeView1_SelectedNodeChanged' is not a member of 'ASP.masterpage_master'.
I really don't know what this means, but would love some help!
Thursday, January 25, 2007 9:47 AM -
User623503027 posted
Have a look at the properties window of your threeview, click on the events-button and delete this routine 'TreeView1_SelectedNodeChanged' on the SelectedNodeChanged event.Thursday, January 25, 2007 12:03 PM -
User-1428145980 posted
Hello,
I have been able to implement this with one exception. The selected node is not showing the style. When a node is selected the text should be bold as defined in my css file, but it does not work. I am using this with CSSAdapters. Can anyone shed some light on this? I've been debugging for hours and cannot find why the CSSAdapter is not recognizing the selected node.
Thank you in advance for your help!Heather
Friday, February 2, 2007 11:47 PM -
User1613131222 posted
One of two things could be the case.. Either you have not set your treeviews SelectAction to SelectExpand, you did not apply the <node>.Select(), or something weird is going on.
In some cases the treeview just doesnt format right, but you shoudl be able to get around it by using code! ie;TreeView1.ApplyStyle... or something like that..
Good luck!
Monday, February 5, 2007 2:10 PM -
User1613131222 posted
One of several things could be the case.. Either you have not set your treeviews SelectAction to SelectExpand, you did not apply the <node>.Select(), or something weird is going on.
In some cases the treeview just doesnt format right, but you shoudl be able to get around it by using code! ie;TreeView1.ApplyStyle... or something like that..
Good luck!
Monday, February 5, 2007 2:10 PM -
User-1428145980 posted
Thanks, I did end up getting around it by looping through all the nodes and manually selecting the one that matched the request.pathandquery. It's not ideal as I'd rather have the treeview "remember" which one is selected (selectaction is SelectExpand) than have to loop through all the nodes... If I don't redirect to the path in the ValueField, it applies the style correctly. It's only upon redirect that it loses it. I imagine its a bug with the CSSAdapters I'm using.Tuesday, February 6, 2007 11:54 AM -
User1007368040 posted
Mark's version of the code worked perfectly for me, except in the Page_load procedure Me.MasterTreeView.ExpandDepth needs to be set to "-1" as per the first version of the code and not "0" as indicated.
Additionally it works without the SelectedNode_Changed event.
Wednesday, February 7, 2007 4:49 PM -
User-1024136266 posted
hi,
am new to the site and asp.net. i have created a website in asp.net using c#. i have used treeview control. when a user click on a node , the corresponding child nodes should not get expanded. i have wriiten a code for it. but i have a problem, ie., when a user clicks on a node, the corresponding child nodes get collapsed and then get's expanded. i know it is bcos i hv given the property AutoPostBack is set to true. i have attached the code. can anyone please tell me on how to avoid that problem? i hv done the program in asp.net 1.1. i donot know VB so can u help me?
the properties that are set in the treeview controls are:
1) AutoPostBack =
true;2) AutoSelect =
false;3) SelectExpands =
false;4) ShowLines =
false;5) ShowPlus =
false;private
void Page_Load(object sender, System.EventArgs e){
{
TreeView1.TreeNodeSrc =
"Ensuite.xml";TreeView1.DataBind();
}}
private
void TreeView1_SelectedIndexChange(object sender, Microsoft.Web.UI.WebControls.TreeViewSelectEventArgs e){
string sel;sel = e.NewNode;
TreeSelLoadPage(sel);
}
private
void TreeSelLoadPage(string nodeID){
TreeNode node = TreeView1.GetNodeFromIndex(nodeID);
string strDir = node.NodeData.ToString();// code for viewing the content
}
private
void ExpandAllNodes(TreeNode pNode){
pNode.Expanded =
true; if(pNode.Nodes.Count >0){
foreach(TreeNode tn in pNode.Nodes){
ExpandAllNodes(tn);
}
}
}
// code for not expanding the child nodes
private void EnSuite_PreRender(object sender, System.EventArgs e){
foreach (TreeNode tn in TreeView1.Nodes){
ExpandAllNodes(tn);
}
}
Monday, April 23, 2007 11:05 AM -
User-1024136266 posted
hi,
can i have c# code instead of vb.net. i am creating a site on asp.net and c#. please help me out
Monday, April 30, 2007 9:07 AM -
User-39264480 posted
Hi, currently i facing the problem to maintain the treeview state. Once i click on the child node the page will refresh then all the child nodes will collapsed. Basically, your solution can be solve maintain treeview state problem but all my child nodes (page's url) is dynamic retrieve from database. I havent catch up how to apply you solution into my situation. Can you provided me the solution? Thanks you...Friday, June 29, 2007 3:06 AM -
User-1334042570 posted
Hi Everyone,
I posted a query about this subject here: http://forums.asp.net/p/1131971/1800669.aspx#1800669
I've just carefully read through this thread and commented on it in my own. For the reasons I've cited there (4th posting down) I firmly believe that without sophisticated Javascript, it's absolutely impossible to restore a tree to the PRECISE state it was in before the Postback. I hope someone can prove me wrong.
More importantly, it would be wonderful if someone could provide a solution that does what we're all looking for!
Robert W.
Vancouver, BCThursday, July 12, 2007 12:14 PM -
User-618956154 posted
I'm beginner in ASP.NET, I had came out with these with my own
1 2 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 3 If Not Page.IsPostBack Then 4 If Session("TreeState") IsNot Nothing Then 5 restoreTree() 6 End If 7 End If 8 End Sub 9 10 Protected Sub MyTree_TreeNodeCollapsed(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles MyTree.TreeNodeCollapsed 11 Dim arr As New ArrayList 12 Dim node As TreeNode 13 For Each node In MyTree.Nodes 14 If node.Expanded() Then 15 arr.Add("True") 16 Else 17 arr.Add("False") 18 End If 19 Next 20 Session("TreeState") = arr 21 End Sub 22 23 Private Sub restoreTree() 24 Dim lst As ArrayList = Session("TreeState") 25 Dim node As TreeNode 26 Dim looping As Integer = 0 27 For Each node In MyTree.Nodes 28 If lst(looping).ToString = "True" Then 29 node.Expand() 30 Else 31 node.Collapse() 32 End If 33 looping += 1 34 Next 35 End Sub 36 37 Protected Sub MyTree_TreeNodeExpanded(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) Handles MyTree.TreeNodeExpanded 38 Dim arr As New ArrayList 39 Dim node As TreeNode 40 For Each node In MyTree.Nodes 41 If node.Expanded() Then 42 arr.Add("True") 43 Else 44 arr.Add("False") 45 End If 46 Next 47 Session("TreeState") = arr 48 End Sub
Then put the TreeView inside an AJAX's UpdatePanel. But I noticed that I got some problem with the expand and collapse of Parent node, it seems not saving the state.
Sunday, July 15, 2007 9:46 PM -
User-1455795415 posted
I am trying to use your code but in a UserControl instead of a Master Page. Untill now the treeview state is not recover between pages. I noticed that in my RestoreTreeViewState the conditions node.Expanded.HasValue() and node.Expanded.GetValueOrDefault(False) keep returning false therefore it never expand any nodes. I don't get it . Why those conditions are always returning false if the SaveTreeVieState return true for the same conditions?
Maybe I have been looking at my code for too long :) Any help would be greatThanks,
Eric
1 2 3 4 5 '************************************************************************** 6 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) 7 '************************************************************************** 8 '************************************************************************** 9 ' Disable ExpandDepth if the TreeView's expand/collapse 10 ' state is stored in session. 11 If Session("TreeViewState") IsNot Nothing Then 12 myTree.ExpandDepth = 0 13 End If 14 End Sub 15 16 '************************************************************************** 17 Protected Sub myTree_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles myTree.SelectedNodeChanged 18 '************************************************************************** 19 '************************************************************************** 20 'If the selected node is changed and we are working with the top node (If you want the ExpandCollapse func further dow, duplicate this part..) 21 If myTree.SelectedNode.Depth = 0 Then 22 myTree.CollapseAll() 23 myTree.SelectedNode.Expand() 24 End If 25 26 'Save the state of the treeview 27 If IsPostBack Then 28 Dim list As ArrayList = New ArrayList 29 SaveTreeViewState(myTree.Nodes, list) 30 Session("TreeViewState") = list 31 End If 32 33 'All done, lets redirect to the new page 34 If IsPostBack Then 35 'Here i use the "value" attribute of the treeview node, this must be used instead of the NavigateURL attribute whitch makes the 36 'OnSelectedNodeChange event break in the first place 37 Dim strFw As String = String.Empty 38 strFw = myTree.SelectedValue.ToString 39 Response.Redirect(strFw.ToString()) 40 End If 41 End Sub 42 43 '************************************************************************** 44 ' Save or reapply the state of the treeview 45 Protected Sub myTree_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) 46 '************************************************************************** 47 '************************************************************************** 48 If Session("TreeViewState") Is Nothing Then 49 ' Record the TreeViews current expand/collapse state. 50 Dim list As ArrayList = New ArrayList 51 SaveTreeViewState(myTree.Nodes, list) 52 Session("TreeViewState") = list 53 Else 54 'Apply the recorded expand/collapse state to the TreeView. 55 Dim list As ArrayList = CType(Session("TreeViewState"), ArrayList) 56 RestoreTreeViewState(myTree.Nodes, list) 57 End If 58 End Sub 59 60 '************************************************************************** 61 Private Sub SaveTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList) 62 '************************************************************************** 63 '************************************************************************** 64 ' Recursivley record all expanded nodes in the List. 65 For Each node As TreeNode In nodes 66 If (node.ChildNodes IsNot Nothing And node.ChildNodes.Count <> 0) Then 67 If (node.Expanded.HasValue AndAlso CBool(node.Expanded) AndAlso Not String.IsNullOrEmpty(node.Text)) Then 68 list.Add(node.Text) 69 SaveTreeViewState(node.ChildNodes, list) 70 End If 71 End If 72 Next 73 End Sub 74 75 '************************************************************************** 76 Private Sub RestoreTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList) 77 '************************************************************************** 78 '************************************************************************** 79 For Each node As TreeNode In nodes 80 ' Restore the state of one node. 81 If list.Contains(node.Text) Then 82 If (node.ChildNodes IsNot Nothing AndAlso (node.ChildNodes.Count <> 0) AndAlso node.Expanded.HasValue() AndAlso node.Expanded.GetValueOrDefault(False)) Then 83 node.Expand() 84 End If 85 ElseIf (node.ChildNodes IsNot Nothing AndAlso node.ChildNodes.Count <> 0 AndAlso node.Expanded.HasValue() AndAlso node.Expanded.GetValueOrDefault(True)) Then 86 node.Collapse() 87 End If 88 89 ' If the node has child nodes, restore their states, too. 90 If (node.ChildNodes IsNot Nothing AndAlso node.ChildNodes.Count <> 0) Then 91 RestoreTreeViewState(node.ChildNodes, list) 92 End If 93 Next 94 95 End Sub 96 97 '************************************************************************** 98 Protected Sub myTree_TreeNodeCollapsed(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) 99 '************************************************************************** 100 '************************************************************************** 101 If IsPostBack Then 102 Dim list As ArrayList = New ArrayList 103 SaveTreeViewState(myTree.Nodes, list) 104 Session("TreeViewState") = list 105 End If 106 End Sub 107 108 '************************************************************************** 109 Protected Sub myTree_TreeNodeExpanded(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs) 110 '************************************************************************** 111 '************************************************************************** 112 If IsPostBack Then 113 Dim list As ArrayList = New ArrayList 114 SaveTreeViewState(myTree.Nodes, list) 115 Session("TreeViewState") = list 116 End If 117 118 End Sub 119 120 121 HTML 122 <asp:TreeView ID="myTree" 123 runat="server" 124 CssClass="SmallRegularFont" 125 SelectedNodeStyle-CssClass="SmallBoldRegularFont" 126 HoverNodeStyle-CssClass="SmallBoldRegularFont" 127 NodeStyle-CssClass="SmallRegularFont" 128 LineImagesFolder="~/TreeLineImages" 129 ShowLines="True" 130 OnDataBound="myTree_DataBound" 131 DataSourceID="XmlDataSource1" 132 OnSelectedNodeChanged="myTree_SelectedNodeChanged" 133 ExpandDepth="0" 134 MaxDataBindDepth="10" 135 NodeIndent="3" 136 OnTreeNodeExpanded="myTree_TreeNodeExpanded" 137 OnTreeNodeCollapsed="myTree_TreeNodeCollapsed" 138 PopulateNodesFromClient="False" 139 > 140 141 <HoverNodeStyle CssClass="SmallBoldRegularFont" /> 142 <SelectedNodeStyle CssClass="SmallBoldRegularFont" /> 143 <NodeStyle CssClass="SmallRegularFont" /> 144 145 <DataBindings> 146 <asp:TreeNodeBinding DataMember="treenode" TextField="text" PopulateOnDemand="true" NavigateUrlField="value" ValueField="value" SelectAction="selectExpand"/> 147 </DataBindings> 148 149 </asp:TreeView> 150 151 <asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="TreeViewEn.xml" XPath="TREENODES/treenode[@ID=1]"></asp:XmlDataSource>
Friday, September 28, 2007 3:52 PM -
User-1334042570 posted
There's nothing specific mentioned on this site. Have you just posted an ad?Wednesday, October 24, 2007 1:28 PM -
User1930729586 posted
I'm new to asp.net (i got some vb.net knowledge.)
It looks like the tree has some postback issues. (the treeview won't expand at all)
I'll post as much as information as possible.-----------------------------------------------------------------------------------------------------------------------------------
<
asp:TreeView ID="TreeView1" runat="server" DataSourceID="sitemapdatasource1" OnSelectedNodeChanged="TreeView1_SelectedNodeChanged"
ExpandDepth="0" MaxDataBindDepth="10" PopulateNodesFromClient="False" ShowExpandCollapse="False"
OnDataBound="TreeView1_DataBound" AutoGenerateDataBindings="False" EnableClientScript="False">
</asp:TreeView>-----------------------------------------------------------------------------------------------------------------------------------
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
'Found on: http://forums.asp.net/p/1022893/1387445.aspx#1387445
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
' Disable ExpandDepth if the TreeView's expand/collapse
' state is stored in session.
If Session("TreeViewState") IsNot Nothing Then
Me.TreeView1.ExpandDepth = 0
End If
End Sub ' Save or reapply the state of the treeview
Protected Sub TreeView1_DataBound(ByVal sender As Object, ByVal e As System.EventArgs)
If Session("TreeViewState") Is Nothing Then
' Record the TreeViews current expand/collapse state.
Dim list As ArrayList = New ArrayList
SaveTreeViewState(TreeView1.Nodes, list)
Session("TreeViewState") = list
Else
'Apply the recorded expand/collapse state to the TreeView.
Dim list As ArrayList = CType(Session("TreeViewState"), ArrayList)
RestoreTreeViewState(TreeView1.Nodes, list)
End If
End Sub Protected Sub TreeView1_TreeNodeCollapsed(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs)
If IsPostBack Then
Dim list As ArrayList = New ArrayList
SaveTreeViewState(TreeView1.Nodes, list)
Session("TreeViewState") = list
End If
End Sub Protected Sub TreeView1_TreeNodeExpanded(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.TreeNodeEventArgs)
If IsPostBack Then
Dim list As ArrayList = New ArrayList
SaveTreeViewState(TreeView1.Nodes, list)
Session("TreeViewState") = list
End If
End Sub Private Sub SaveTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList)
' Recursivley record all expanded nodes in the List.
For Each node As TreeNode In nodes
If (node.ChildNodes IsNot Nothing And node.ChildNodes.Count <> 0) Then
If (node.Expanded.HasValue AndAlso CBool(node.Expanded) AndAlso Not String.IsNullOrEmpty(node.Text)) Then
list.Add(node.Text)
SaveTreeViewState(node.ChildNodes, list)
End If
End If
Next
End Sub Private Sub RestoreTreeViewState(ByVal nodes As TreeNodeCollection, ByVal list As ArrayList)
For Each node As TreeNode In nodes
' Restore the state of one node.
If list.Contains(node.Text) Then
If (node.ChildNodes IsNot Nothing AndAlso (node.ChildNodes.Count <> 0)) Then
node.Expand()
End If
ElseIf (node.ChildNodes IsNot Nothing AndAlso (node.ChildNodes.Count <> 0)) Then
node.Collapse()
End If
' If the node has child nodes, restore their states, too.
If (node.ChildNodes IsNot Nothing AndAlso node.ChildNodes.Count <> 0) Then
RestoreTreeViewState(node.ChildNodes, list)
End If
Next
End Sub
End Class-----------------------------------------------------------------------------------------------------------------------------------
images of my property's
http://img90.imageshack.us/my.php?image=propert2rw1.jpg
http://img103.imageshack.us/my.php?image=propertmx4.jpghelp would be great...
Tuesday, October 30, 2007 12:03 PM -
User-1455795415 posted
Hum I think your problem is in the definition
of you treeviewHere is what I used
<asp:TreeView ID="myTree"
runat="server"
LineImagesFolder="~/TreeLineImages"
ShowLines="True"
OnDataBound="myTree_DataBound"
DataSourceID="XmlDataSource1"
ExpandDepth="-1"
MaxDataBindDepth="10"
OnTreeNodeExpanded="myTree_TreeNodeExpanded"
OnTreeNodeCollapsed="myTree_TreeNodeCollapsed"
PopulateNodesFromClient="False"
Tuesday, October 30, 2007 12:16 PM -
User1930729586 posted
nop, that's not it i guess.. I changed according to yours... still doesn't work :(
Tuesday, October 30, 2007 12:41 PM -
User-1583927053 posted
I have tried to make this work for 2days now (C#).. Do I have to populate the treeview from xml?! I have populated it from a dabase with the example asp.net got on (QuickStart). I do get all the info from the database in to the treeview but i cant keeping the treeview stats. If i have to use xml, pleas guide me in the right direction because i dont know how to do that from a database.
Friday, April 18, 2008 6:57 AM -
User-1334042570 posted
Perhaps others can discern what you're saying but your description seems so vague that I really don't know what you're saying. Just being honest.
Friday, April 18, 2008 3:27 PM -
User1535544631 posted
I used the exact code that you have but there is a small problem. On the click the state doesn't change .. I mean there is no expansion or collopse of nodes.
Thursday, May 1, 2008 10:14 AM -
User-1562013408 posted
Is there a way to do this in AJAX? Some AJAX control that is already created maybe? Redirecting makes my page flicker. :(
Anyone?
Thanks!
Friday, August 1, 2008 3:40 PM -
User-1412983413 posted
Is there a way to do this in AJAX? Some AJAX control that is already created maybe? Redirecting makes my page flicker. :(No. Not in ajax. Been there for two days...
This seems to be the only thing that works.
Thursday, October 9, 2008 3:35 PM -
User1336893087 posted
Hi Everyone,
I need your prompt response. Thanks in Advance.
I have follwoing details:-
1) Login Page
2) Master Page
-
3) Treeview ----- My tree enabled by database sql server
4) Home Page.aspx 5) Page1.aspx 6) Page3.aspx ........
My problem is same , but could not get which pages should I placed Save Session and Retriev from Session. Please help.. Should I retieve Session each page like Page1.aspx,page2.aspx...?if yes then how?I am attaching my code below which is in masterpage.cs
/******************************************************************************
using
System;using
System.Data;using
System.Configuration;using
System.Collections;using
System.Collections.Generic ;using
System.Web;using
System.Web.Security;using
System.Web.UI;using
System.Web.UI.WebControls;using
System.Web.UI.WebControls.WebParts;using
System.Web.UI.HtmlControls;using
System.Data.SqlClient;public
partial class MasterPage : System.Web.UI.MasterPage{
//string uri = "?"; const string constAEVProject = "default.aspx"; const string constAEVAuditorAndAssessor = "htdocs\\AuditorDetails.aspx"; const string constVRolling = "htdocs\\IQARollingPlan.aspx"; const string constCMonthlyIQA = "htdocs\\CreateMonthlyIQAPlan.aspx"; const string constVMonthlyIQA = "htdocs\\ViewMonthlyIQAPlan.aspx"; const string constCProjectIQA = "htdocs\\IQAPlanCreate.aspx"; const string constVProjectIQA = "htdocs\\IQAPlanView.aspx";protected void Page_Load(object sender, EventArgs e){
string i = "Master PageLoad"; //Label1.Text = Session["AccountName"].ToString(); if (!Page.IsPostBack){
PopulateRootLevel();
}
}
private void PopulateRootLevel(){
int n1 = 25; SqlConnection objConn = new SqlConnection(@"Data Source=aa;Persist Security Info=True;User ID=llk;Password=ss"); SqlCommand objCommand = new SqlCommand(@"select id,title,(select count(*) FROM SampleCategories WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID IS NULL and sc.id != 23 and sc.id != " + n1, objConn); SqlDataAdapter da = new SqlDataAdapter(objCommand); DataTable dt = new DataTable();da.Fill(dt);
PopulateNodes(dt, TreeView1.Nodes);
}
private void PopulateSubLevel(int parentid, TreeNode parentNode){
SqlConnection objConn = new SqlConnection(@"Data Source=aa;Persist Security Info=True;User ID=llk;Password=ss") SqlCommand objCommand = new SqlCommand(@"select id,title,(select count(*) FROM SampleCategories WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID=@parentID and sc.id != 17 and sc.id != 18", objConn); objCommand.Parameters.Add("@parentID", SqlDbType.Int).Value = parentid; SqlDataAdapter da = new SqlDataAdapter(objCommand); DataTable dt = new DataTable();da.Fill(dt);
PopulateNodes(dt, parentNode.ChildNodes);
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e){
PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);}
private void PopulateNodes(DataTable dt, TreeNodeCollection nodes){
foreach (DataRow dr in dt.Rows){
TreeNode tn = new TreeNode();tn.Text = dr[
"title"].ToString(); tn.Value = dr["id"].ToString();nodes.Add(tn);
//If node has child nodes, then enable on-demand populating tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){
if (TreeView1.SelectedNode.Value != string.Empty){
string actualpath = GetURLPath(Convert.ToInt16(TreeView1.SelectedNode.Value)); string pathNavigation = actualpath;// +uri;Response.Redirect(pathNavigation);
}
}
#region
/// <summary> /// This function is used get the url path based on the node type which is determined by the nodedepth /// </summary> /// <param name="nodeDepth"></param> /// <returns></returns> public string GetURLPath(Int16 nodeDepth){
string navigationPath = null; /// Add/Edit/View Project ASPX Page if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMAEVPROJECT)){
navigationPath = constAEVProject;
}
/// Add/Edit/View Auditor aand Assessor ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMAEVAUDITORASSESSOR)){
navigationPath = constAEVAuditorAndAssessor;
}
/// View Rolling IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMVROLLINGIQAPLAN)){
navigationPath = constVRolling;
}
/// Create Monthly IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMCMONTHLYIQAPLAN)){
navigationPath = constCMonthlyIQA;
}
/// View Monthly IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMVMONTHLYIQAPLAN)){
navigationPath = constVMonthlyIQA;
}
/// Create Project IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMCPROJECTIQAPLAN)){
navigationPath = constCProjectIQA;
}
/// View Project IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMVPROJECTIQAPLAN)){
navigationPath = constVProjectIQA;
}
return navigationPath;}
#endregion
protected void TreeView1_Unload(object sender, EventArgs e){
}
protected void Page_Unload(object sender, EventArgs e){
string i = "Master Page UnLoad";if ((Page.IsPostBack) && TreeView1.SelectedNode != null){
if (TreeView1.SelectedNode.Depth > 1){
StoreTreeViewStateToSession(TreeView1);
}
}
}
public static void StoreTreeViewStateToSession(TreeView tvIn){
// Takes the TreeView's state and saves it in a Session variable // Call this method before leaving the page if we expect to be back string strVarName;string strList = "";strVarName =
"tv_" + HttpContext.Current.Request.ServerVariables["path_info"]; if (HttpContext.Current.Session[strVarName] + "" != ""){
HttpContext.Current.Session.Remove(strVarName);}
StoreTreeViewStateToSession_Recurse(tvIn.Nodes[1], ref strList);strList = tvIn.SelectedNode.ValuePath + strList;
HttpContext.Current.Session.Add(strVarName, strList);}
{
if (tnIn.Expanded == true){
strList = "," + tnIn.ValuePath + strList;}
foreach (TreeNode tnCurrent in tnIn.ChildNodes){
StoreTreeViewStateToSession_Recurse(tnCurrent, ref strList);}
}
protected void TreeView1_load(object sender, EventArgs e){
//new TreeViewState().RestoreTreeView(TreeView1, this.GetType().ToString());}
}
Friday, November 7, 2008 10:59 AM -
-
User1336893087 posted
Hi Everyone,
I need your prompt response. Thanks in Advance.
I have follwoing details:-
1) Login Page
2) Master Page
-
3) Treeview ----- My tree enabled by database sql server
4) Home Page.aspx 5) Page1.aspx 6) Page3.aspx ........
My problem is same , but could not get which pages should I placed Save Session and Retriev from Session. Please help.. Should I retieve Session each page like Page1.aspx,page2.aspx...?if yes then how?I am attaching my code below which is in masterpage.cs
/******************************************************************************
using
System;using
System.Data;using
System.Configuration;using
System.Collections;using
System.Collections.Generic ;using
System.Web;using
System.Web.Security;using
System.Web.UI;using
System.Web.UI.WebControls;using
System.Web.UI.WebControls.WebParts;using
System.Web.UI.HtmlControls;using
System.Data.SqlClient;public
partial class MasterPage : System.Web.UI.MasterPage{
//string uri = "?"; const string constAEVProject = "default.aspx"; const string constAEVAuditorAndAssessor = "htdocs\\AuditorDetails.aspx"; const string constVRolling = "htdocs\\IQARollingPlan.aspx"; const string constCMonthlyIQA = "htdocs\\CreateMonthlyIQAPlan.aspx"; const string constVMonthlyIQA = "htdocs\\ViewMonthlyIQAPlan.aspx"; const string constCProjectIQA = "htdocs\\IQAPlanCreate.aspx"; const string constVProjectIQA = "htdocs\\IQAPlanView.aspx";protected void Page_Load(object sender, EventArgs e){
string i = "Master PageLoad"; //Label1.Text = Session["AccountName"].ToString(); if (!Page.IsPostBack){
PopulateRootLevel();
}
}
private void PopulateRootLevel(){
int n1 = 25; SqlConnection objConn = new SqlConnection(@"Data Source=aa;Persist Security Info=True;User ID=llk;Password=ss"); SqlCommand objCommand = new SqlCommand(@"select id,title,(select count(*) FROM SampleCategories WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID IS NULL and sc.id != 23 and sc.id != " + n1, objConn); SqlDataAdapter da = new SqlDataAdapter(objCommand); DataTable dt = new DataTable();da.Fill(dt);
PopulateNodes(dt, TreeView1.Nodes);
}
private void PopulateSubLevel(int parentid, TreeNode parentNode){
SqlConnection objConn = new SqlConnection(@"Data Source=aa;Persist Security Info=True;User ID=llk;Password=ss") SqlCommand objCommand = new SqlCommand(@"select id,title,(select count(*) FROM SampleCategories WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID=@parentID and sc.id != 17 and sc.id != 18", objConn); objCommand.Parameters.Add("@parentID", SqlDbType.Int).Value = parentid; SqlDataAdapter da = new SqlDataAdapter(objCommand); DataTable dt = new DataTable();da.Fill(dt);
PopulateNodes(dt, parentNode.ChildNodes);
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e){
PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);}
private void PopulateNodes(DataTable dt, TreeNodeCollection nodes){
foreach (DataRow dr in dt.Rows){
TreeNode tn = new TreeNode();tn.Text = dr[
"title"].ToString(); tn.Value = dr["id"].ToString();nodes.Add(tn);
//If node has child nodes, then enable on-demand populating tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e){
if (TreeView1.SelectedNode.Value != string.Empty){
string actualpath = GetURLPath(Convert.ToInt16(TreeView1.SelectedNode.Value)); string pathNavigation = actualpath;// +uri;Response.Redirect(pathNavigation);
}
}
#region
/// <summary> /// This function is used get the url path based on the node type which is determined by the nodedepth /// </summary> /// <param name="nodeDepth"></param> /// <returns></returns> public string GetURLPath(Int16 nodeDepth){
string navigationPath = null; /// Add/Edit/View Project ASPX Page if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMAEVPROJECT)){
navigationPath = constAEVProject;
}
/// Add/Edit/View Auditor aand Assessor ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMAEVAUDITORASSESSOR)){
navigationPath = constAEVAuditorAndAssessor;
}
/// View Rolling IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMVROLLINGIQAPLAN)){
navigationPath = constVRolling;
}
/// Create Monthly IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMCMONTHLYIQAPLAN)){
navigationPath = constCMonthlyIQA;
}
/// View Monthly IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMVMONTHLYIQAPLAN)){
navigationPath = constVMonthlyIQA;
}
/// Create Project IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMCPROJECTIQAPLAN)){
navigationPath = constCProjectIQA;
}
/// View Project IQA Plan ASPX Page else if (nodeDepth == Convert.ToInt16(EnumWebPage.ENUMVPROJECTIQAPLAN)){
navigationPath = constVProjectIQA;
}
return navigationPath;}
#endregion
protected void TreeView1_Unload(object sender, EventArgs e){
}
protected void Page_Unload(object sender, EventArgs e){
string i = "Master Page UnLoad";if ((Page.IsPostBack) && TreeView1.SelectedNode != null){
if (TreeView1.SelectedNode.Depth > 1){
StoreTreeViewStateToSession(TreeView1);
}
}
}
public static void StoreTreeViewStateToSession(TreeView tvIn){
// Takes the TreeView's state and saves it in a Session variable // Call this method before leaving the page if we expect to be back string strVarName;string strList = "";strVarName =
"tv_" + HttpContext.Current.Request.ServerVariables["path_info"]; if (HttpContext.Current.Session[strVarName] + "" != ""){
HttpContext.Current.Session.Remove(strVarName);}
StoreTreeViewStateToSession_Recurse(tvIn.Nodes[1], ref strList);strList = tvIn.SelectedNode.ValuePath + strList;
HttpContext.Current.Session.Add(strVarName, strList);}
{
if (tnIn.Expanded == true){
strList = "," + tnIn.ValuePath + strList;}
foreach (TreeNode tnCurrent in tnIn.ChildNodes){
StoreTreeViewStateToSession_Recurse(tnCurrent, ref strList);}
}
protected void TreeView1_load(object sender, EventArgs e){
//new TreeViewState().RestoreTreeView(TreeView1, this.GetType().ToString());}
}
Friday, November 7, 2008 10:59 AM -
-
User-1334042570 posted
I, for one, do not understand what you're asking for. Please rephrase your questions more carefully and succinctly.
Thank you,
Robert W.
Friday, November 7, 2008 1:41 PM -
User1336893087 posted
HI ,
It would be great if you can provide us menu control coding.
Thanks in advance
Monday, November 10, 2008 12:09 AM -
User-146107756 posted
Hi,
I tried ur code.
But its not working for..
Here I could see that u have used xml to bind the data..
Is it compulsary to do so...
As I am binding the Treeview in master page from the database...
This is my code how I bind the treeview.
Dim
intNLU = Request.QueryString(
intFlag = Request.QueryString(
GetCBTId = Session(
intRolid = Session(
LangId = Session(
intUserid = Session(
TreeView2 =
TreeNode =
clsMyClass.OpenConn()
strQuery =
strQuery =
strQuery =
strQuery =
strTQuery =
"Select * from cbttitle where CBT_ID =" & GetCBTId & " and CBTTitle.Status_Flg<>'E' "strTQuery =
"Select * from cbttitle where CBT_ID =" & GetCBTId & " and CBTTitle.Status_Flg<>'E' "strTQuery =
"Select * from cbttitle where CBT_ID =" & GetCBTId & " and CBTTitle.Status_Flg<>'E' "strTQuery =
objCmd =
objCmd.Connection = clsMyClass.conn
objCmd.CommandText = strTQuery &
objAdapt =
objAdapt.Fill(objDS)
objDS.Tables(0).TableName =
New OleDbCommand()" " & strQueryNew OleDbDataAdapter(objCmd)"dtTitle"objDS.Tables(1).TableName =
"dtSubject"objAdapt.Dispose()
objAdapt =
NothingTreeView2.Visible =
FalseResponse.Write(
qs = Request.QueryString(
qs = Request.QueryString(
qsSubjid = Split(qs,
level = qsSubjid(0)
NodeVal.Value = qsSubjid(1)
nodetitle =
nodetitle.Text =
nodetitle.ToolTip =
nodetitle.ImageUrl =
Dim rowTitle, rowSubj, rowChap, rowTopic, rowBlock As DataRowFor Each rowTitle In objDS.Tables(0).RowsNew TreeNode"Course: " & rowTitle("CBT_TitleName")"Course: " & rowTitle("CBT_TitleName")"../content/images/folder.gif"nodetitle.NavigateUrl =
"../content/frmCourseDetails.aspx?param=1"TreeView2.Nodes.Add(nodetitle)
nodeSubject =
nodeSubject.Expanded =
FalsenodeSubject.Text = StrTopic &
nodeSubject.ToolTip = StrTopic &
nodeSubject.NavigateUrl =
":" & rowSubj("CBTSub_SrNo") & " " & rowSubj("subj_name")":" & rowSubj("CBTSub_SrNo") & " " & rowSubj("subj_name")"../content/frmLearningDetails.aspx" '?allocated=" & IsAllocated(2, rowSubj("subj_id")) & "¶m=1" & "&subjid=" & "2~^" & rowSubj("subj_id") & " ~^ " & rowSubj("subj_id") & " ~^ " & intNLU & " ~^ " & intFlag & "~^ " & rowSubj("CBTSub_SrNo") ' by shweta for treeview (specific loading)nodetitle.ChildNodes.Add(nodeSubject)
nodeSubject.Expanded =
FalsenodeSubject.Selected =
TruenodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Swf Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Jpg Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Gif Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Html Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Doc Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Pdf Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Wmv Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Mpeg Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Mpg Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"Ppt Image Attached"nodeSubject.ImageUrl =
"../content/images/image.png"nodeSubject.ImageToolTip =
"xls Image Attached"nodeSubject.ImageUrl =
"../content/images/noimage.png"nodeSubject.ImageToolTip =
"No Image Attached"Session.Add(
strQuery =
strQuery =
strQuery =
strQuery =
objCmd.CommandText = strQuery
objAdapt =
objAdapt.Fill(objChap,
objAdapt.Dispose()
objAdapt =
Dim objChap As New DataSetNew OleDbDataAdapter(objCmd)"dtChapter")NothingnodeChapter =
nodeChapter.Text = strLab &
nodeChapter.ToolTip = strLab &
nodeChapter.NavigateUrl =
For Each rowChap In objChap.Tables(0).RowsNew TreeNode":" & rowChap("SuCh_SrNo") & " " & rowChap("Chap_name")":" & rowChap("SuCh_SrNo") & " " & rowChap("Chap_name")"../content/frmLearningDetails.aspx" '?allocated=" & IsAllocated(3, rowChap("chap_id")) & "¶m=1&subjid=" & "3~^" & rowChap("chap_id") & " ~^ " & rowChap("chap_id") & " ~^ " & intNLU & " ~^ " & intFlag & " ~^ " & rowChap("SuCh_SrNo") & "&sid=" & rowSubj("subj_id")nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Swf Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Jpg Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Gif Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Html Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Doc Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Pdf Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Wmv Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Mpeg Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Mpg Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"Ppt Image Attached"nodeChapter.ImageUrl =
"../content/images/image.png"nodeChapter.ImageToolTip =
"xls Image Attached"nodeChapter.ImageUrl =
"../content/images/noimage.png"nodeChapter.ImageToolTip =
"No Image Attached"nodeChapter.Expanded =
FalsenodeSubject.ChildNodes.Add(nodeChapter)
nodeChapter.Selected =
TruenodeChapter.Selected =
FalseSession.Add(
strQuery =
strQuery =
strQuery =
strQuery =
objCmd.CommandText = strQuery
objAdapt =
objAdapt.Fill(objTop,
objAdapt.Dispose()
objAdapt =
New OleDbDataAdapter(objCmd)Dim objTop As New DataSet"dtTopic")NothingnodeTopic =
nodeTopic.Text = StrAssg &
nodeTopic.ToolTip = StrAssg &
nodeTopic.NavigateUrl =
For Each rowTopic In objTop.Tables(0).RowsNew TreeNode":" & rowTopic("ChTo_SrNo") & " " & rowTopic("Topi_Name")":" & rowTopic("ChTo_SrNo") & " " & rowTopic("Topi_Name")"../content/frmLearningDetails.aspx" 'allocated=" & IsAllocated(4, rowTopic("Topi_Id")) & "¶m=1&subjid=" & "4~^" & rowTopic("Topi_Id") & "~^" & rowTopic("Topi_Id") & " ~^ " & intNLU & " ~^ " & intFlag & "~^" & rowTopic("ChTo_SrNo") & "&sid=" & rowSubj("subj_id") & "&cid=" & rowChap("chap_id")nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Swf Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Jpg Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Gif Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Html Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Doc Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Pdf Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Wmv Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Mpeg Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Mpg Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"Ppt Image Attached"nodeTopic.ImageUrl =
"../content/images/image.png"nodeTopic.ImageToolTip =
"xls Image Attached"nodeTopic.ImageUrl =
"../content/images/noimage.png"nodeTopic.ImageToolTip =
"No Image Attached"nodeChapter.ChildNodes.Add(nodeTopic)
nodeTopic.Selected =
TruestrQuery =
strQuery =
strQuery =
strQuery =
objCmd.CommandText = strQuery
objAdapt =
objAdapt.Fill(objBlock,
objAdapt.Dispose()
objAdapt =
New OleDbDataAdapter(objCmd)Dim objBlock As New DataSet"dtBlock")NothingnodeBlock =
nodeBlock.Expanded =
New TreeNodeFalsenodeBlock.Value = rowBlock(
nodeBlock.Text = StrFrame &
nodeBlock.Text = StrFrame &
nodeBlock.Text = StrFrame &
nodeBlock.NavigateUrl =
strQuery =
objCmd.CommandText = strQuery
imgId = 0
imgId = objCmd.ExecuteScalar
nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Swf Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Jpg Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Gif Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Html Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Doc Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Pdf Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Wmv Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Mpeg Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Mpg Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"Ppt Image Attached"nodeBlock.ImageUrl =
"../content/images/image.png"nodeBlock.ImageToolTip =
"xls Image Attached"nodeBlock.ImageUrl =
"../content/images/noimage.png"nodeBlock.ImageToolTip =
"No Image Attached"nodeBlock.Target =
"main"nodeTopic.ChildNodes.Add(nodeBlock)
nodeBlock.Selected =
TrueAllocated = Session(
Allocated =
FalseAllocated = Request.QueryString(
Response.Write(
Response.Write(
Response.Write(
Response.Write(
Response.Write(obje.ToString)
clsMyClass.CloseConn()
clsMyClass.dispose()
clsMyClass =
NothingobjCmd.Dispose()
objCmd =
NothingPlz Help...
Thanks in Advance..
Wednesday, February 24, 2010 5:48 AM -
User-1596001782 posted
Thanks for providing the following link
http://msdn.microsoft.com/msdnmag/issues/06/06/WickedCode/default.aspx
It helped me preserving the tree view state across multiple pages
Madhu
Friday, August 6, 2010 4:24 PM -
User-1120145944 posted
Thank you so much for the excellent post! It's been of great help!
Tuesday, November 16, 2010 11:04 PM -
User-1231836060 posted
Try this code in the code behind form load event.
< Tree Node ID >.SelectAction = TreeNodeSelectAction.SelectExpand;
I hope this will work
Wednesday, November 17, 2010 12:52 AM -
User-1290511927 posted
I know this is an old thread but I was hoping one of the original posters may be able to help. I have a treeview which is created dynamically from a database. I have tried the code here to retain the state of the treeview but when I click one of my nodes the method to populate my treeview is being executed. I am using the navigateURL of the node. Should I be doing something different?
If Not Page.IsPostBack Then MasterTreeView.Nodes.Clear() BindRoots() End If
Thursday, July 26, 2012 7:10 AM