TreeView Control Problem
I have a public folder on the server that contains recursively nested sub开发者_JAVA技巧 folders. In the various Leaf folders contains Images. I wanted to create a server side file browser that will display the Images to the user. I am using the ASP.NET TreeView Control. I create the tree nodes using PopulateOnDemand. If the user click on a leaf directory I want the images in that folder to be displayed in a DataList Control.
The problem is that when I click on a sub tree node (after I expanded it parent node) All the expanded sub tree disappears and only the parent node is showed with no + sign next to it !!
( I have set the TreeView's PopulateNodesFromClient property to true )
Can someone tell me what is the problem ??
Thanks
Here is the code :
<asp:TreeView ID="TreeView1" runat="server" AutoGenerateDataBindings="False"
onselectednodechanged="TreeView1_SelectedNodeChanged"
ontreenodepopulate="TreeView1_TreeNodePopulate">
</asp:TreeView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string path = Server.MapPath(".");
PopulateTopNodes(path);
}
}
private void PopulateTopNodes(string pathToRootFolder)
{
DirectoryInfo dirInfo = new DirectoryInfo(pathToRootFolder);
DirectoryInfo[] dirs = dirInfo.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
TreeNode folderNode = new TreeNode(dir.Name,dir.FullName);
if (dir.GetDirectories().Length > 0)
{
folderNode.PopulateOnDemand = true;
folderNode.Collapse();
}
TreeView1.Nodes.Add(folderNode);
}
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
if (IsCallback == true)
{
if (e.Node.ChildNodes.Count == 0)
{
LoadChildNode(e.Node);
}
}
}
private void LoadChildNode(TreeNode treeNode)
{
DirectoryInfo dirInfo = new DirectoryInfo(treeNode.Value);
DirectoryInfo[] dirs = dirInfo.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
TreeNode folderNode = new TreeNode(dir.Name, dir.FullName);
if(dir.GetDirectories().Length>0){
folderNode.PopulateOnDemand = true;
folderNode.Collapse();
}
treeNode.ChildNodes.Add(folderNode);
}
}
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
// Retrieve the images here
}
I don't have a straight answer for you, but you are doing something wrong since you are only loading the nodes in Page_Load, and even only on the first load. That means that you rely on the ViewState to save all the nodes between postbacks and well, that's just not the correct way to do it.
It seems to me that you're pretty close, though. I would remove the Page_Load and then take a look at the last example of this page: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.treeview(VS.80).aspx.
I had the same exact problem and setting the property PopulateNodesFromClient="false" solved it.
edit: the property of the TreeView Control.
精彩评论