This is a common enough problem that is automatically handled by ASP.NET if you use a SiteMapDataSource control as the datasource for your TreeView. In this case, you haven't mentioned what the Datasource of your TreeView is.
You also haven't mentioned if the TreeView contains links (the NavigateUrl
property is set) or Text items that postback for each click. If it is the former, then as far as I know, you are out of luck! This is because none of the Selection events are raised for TreeNodes which have their NavigateUrl
set. They just function as regular hyperlinks.
If however, it is the latter, then you can try out the following steps :
a. Handle the SelectedNodeChanged
event of the TreeView. In this event handler, retrieve the current value of the SelectedNode.ValuePath
property and store it in ViewState/Session. Use the Value
of the of the SelectedNode to conditionally redirect the page to URL mapped to it.
Something like the following:
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
TreeNode selNode = TreeView1.SelectedNode;
string pathToNode = selNode.ValuePath;
Session.Add("SelPath", pathToNode);
switch (selNode.Value)
{
//Redirect to URL accordingly.
}
}
b. On subsequent load of the Master page (the page to which you redirected), retrieve the value of the ValuePath
set earlier and find the previously Selected node and Expand
it.
Something like the following:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
string pathToNode = (string)Session("SelPath");
Session.Remove("SelPath");
TreeNode selNode = TreeView1.FindNode(pathToNode);
if (selNode != null)
{
selNode.Expand();
}
}
}
Note that I haven't had an opportunity to test the code so this is mostly hypothetical.