Is there a way of populating a treeview including the parent's sub folder? My code only can only view files on its parent folder but once it in a sub folder it won't open.
Main problem: I can't open a file when it's inside a sub folder of my MapPath
Here's mine, so far it only gets the parent node it doesn't get the parent's sub folder:
protected void Page_Load(object sender, EventArgs e)
{
TreeView1.Nodes[0].Value = Server.MapPath("~/Files");
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
if (e.Node.ChildNodes.Count == 0)
{
DirectoryInfo directory = null;
directory = new DirectoryInfo(e.Node.Value);
foreach (DirectoryInfo subtree in directory.GetDirectories())
{
TreeNode subNode = new TreeNode(subtree.Name);
subNode.Value = subtree.FullName;
try
{
if (subtree.GetDirectories().Length == 0 | subtree.GetFiles().Length == 0)
{
subNode.SelectAction = TreeNodeSelectAction.SelectExpand;
subNode.PopulateOnDemand = true;
subNode.NavigateUrl = "";
}
}
catch
{
}
e.Node.ChildNodes.Add(subNode);
}
foreach (FileInfo fi in directory.GetFiles())
{
TreeNode subNode = new TreeNode(fi.Name);
e.Node.ChildNodes.Add(subNode);
subNode.NavigateUrl = "Files/" + fi.Name;
}
}
}
There's absolutely nothing wrong with your code. I've run a test it works like a charm. So, a few things to point out which are NOT exactly clear in your question.
1.
You need to hook the TreeView1_TreeNodePopulate to your TreeView control. You can do that declaratively from the markup...
<asp:TreeView ID="TreeView1" runat="server" OnTreeNodePopulate="TreeView1_TreeNodePopulate">
or, imperatively from code behind...
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
TreeView1.TreeNodePopulate += TreeView1_TreeNodePopulate;
}
otherwise this event handler will never get hit
2.
In addition to hooking up the OnTreeNodePopulate event you need to add at least one node from the markup and set its PopulateOnDemand property to true...
<Nodes>
<asp:TreeNode PopulateOnDemand="true" Text="Root"></asp:TreeNode>
</Nodes>
if you don't set this property this event will never get triggered. Another reason to add this "root" node is to avoid an IndexOutOfRangeException or NullReference exception here...
TreeView1.Nodes[0].Value = Server.MapPath("~/Files");
Keeping all that in mind, it should work just fine
Edit based on comment
I didn't noticed the bit where you said you want to open the files when the tree node is clicked. And that happens because you are passing the url when creating and adding the nodes. Basically I'd recommend not using Server.MapPath on page load, add the virtual server path only...
TreeView1.Nodes[0].Value = "~/Files";
then use Server.MapPath when creating the DirectoryInfo object...
directory = new DirectoryInfo(Server.MapPath(e.Node.Value));
and set the value of the tree node (inside the "directories" iteration) by appending a parent value's...
subNode.Value = string.Format("{0}/{1}", e.Node.Value, subtree.Name);
and finally, within the "files" iteration, set the NavigateUrl's property of the node like below...
subNode.NavigateUrl = string.Format("{0}/{1}", e.Node.Value, fi.Name);
That should give you a proper link in your file nodes. Notice, that this is similar to issuing an http request using a web browser and the request will be handled by IIS and the ASP.NET pipeline...which means that you will only be able to see files that can be handled by IIS by default (e.g. images, etc)
Related
I have currently the following problem. I have a directory structure like
root
- level 1
- level 1.1
- level 1.2
- level 2
- level 2.1
- level 3
- level 4
- level 4.1
from this I want to build a menu. so root will be the menu item to click on and all the level will be needed to drill down to the information you want to get.
As I'm pretty new to C# (not programming) I wanted to know if there is any help from .NET for this task. I don't want to start to fiddel around with code that is already there...
Thanks for any input!
You can use the DirectoryInfo class to obtain a list of all sub-directories for a given root folder. You should the perform a recursive search on sub-directories and build your menu using that data.
Here is some code that will do the job for you, it assumes you already have a MenuStrip called menuStrip1:
public void BuildMenu()
{
//first we get the DirectoryInfo for your root folder, this will be used to find the first set of sub-directories
DirectoryInfo dir = new DirectoryInfo(#"C:\MyRootFolder\");//Change this
//next we create the first MenuItem to represent the root folder, this is created using the GetMenuItem function
ToolStripMenuItem root = GetMenuItem(dir);
//we add our new root MenuItem to our MenuStrip control, at this point all sub-menu items will have been added using our recursive function
menuStrip1.Items.Add(root);
}
public ToolStripMenuItem GetMenuItem(DirectoryInfo directory)
{
//first we create the MenuItem that will be return for this directory
ToolStripMenuItem item = new ToolStripMenuItem(directory.Name);
//next we loop all sub-directory of the current to build all child menu items
foreach (DirectoryInfo dir in directory.GetDirectories())
{
item.DropDownItems.Add(GetMenuItem(dir));
}
//finally we return the populated menu item
return item;
}
Dont forget to change the root folder path!
NOTE: Yorye Nathan has made a good point about short-cut folders. If any of your folders is a short-cut to a parent folder this will cause an endless loop. The easiest way to solve this is to make sure your structure doesn't contain any short-cuts. This may be an easy option for you assuming you have a specifically built structure for this application. If however, you are running this on a user-defined root folder you will want to check for these.
You could modify the GetMenuItem function as below to account for this, assuming .Net 3.5 or higher (LINQ + optional parameters):
public ToolStripMenuItem GetMenuItem(DirectoryInfo directory, List<DirectoryInfo> currentFolders = null)
{
if (currentFolders == null)
currentFolders = new List<DirectoryInfo>();
currentFolders.Add(directory);
ToolStripMenuItem item = new ToolStripMenuItem(directory.Name);
foreach (DirectoryInfo dir in directory.GetDirectories())
{
if (!currentFolders.Any(x => x.FullName == dir.FullName))//check to see if we already processed this folder (i.e. a unwanted shortcut)
{
item.DropDownItems.Add(GetMenuItem(dir, currentFolders));
}
}
return item;
}
EDITED Now supporting recursive folders (ignore to prevent endless loop)
public static MenuStrip CreateMenu(string rootDirectoryPath)
{
var dir = new DirectoryInfo(rootDirectoryPath);
var menu = new MenuStrip();
var root = new ToolStripMenuItem(dir.Name);
var includedDirs = new List<string> {dir};
menu.Items.Add(root);
AddItems(root, dir, includedDirs);
return menu;
}
private static void AddItems(ToolStripDropDownItem parent, DirectoryInfo dir, ICollection<string> includedDirs)
{
foreach (var subDir in dir.GetDirectories().Where(subDir => !includedDirs.Contains(subDir.FullName)))
{
includedDirs.Add(subDir.FullName);
AddItems((ToolStripMenuItem)parent.DropDownItems.Add(subDir.Name), subDir, includedDirs);
}
}
http://msdn.microsoft.com/en-us/library/bb513869.aspx
http://www.stillhq.com/dotnet/000003.html
http://www.codeproject.com/Articles/11599/Recursive-function-to-read-a-directory-structure
Here is the application on codeplex all i did is created a new text box and trying to get path of current node selected into this text box, but i am getting extra things which i dont need at all,
Link to application,
Codeplex app
Code Line i am using is ,
TextBox1.Text = nodeCurrent.FullPath;
and output i am getting is something like this,
My Computer\C:\\Documents and Settings\Administrator\Desktop
My Computer here is Root Node, which i dont need, all i want is
C:\Documents and Settings\Administrator\Desktop
Picture added
Here is the function i am using it
private void tvFolders_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
//Populate folders and files when a folder is selected
this.Cursor = Cursors.WaitCursor;
//get current selected drive or folder
TreeNode nodeCurrent = e.Node;
string newPath = getFullPath(nodeCurrent.FullPath);
tbDirectory.Text = newPath;
//clear all sub-folders
nodeCurrent.Nodes.Clear();
if (nodeCurrent.SelectedImageIndex == 0)
{
//Selected My Computer - repopulate drive list
PopulateDriveList();
}
else
{
//populate sub-folders and folder files
PopulateDirectory(nodeCurrent, nodeCurrent.Nodes);
}
this.Cursor = Cursors.Default;
}
It looks to me like the getFullPath method in that code will do exactly what you want. It strips the MyComputer\ string and returns the rest. Write:
string newPath = getFullPath(nodeCurrent.FullPath);
add the following line in the code and it will remove recurring "\" in the path
newPath = newPath.Replace("\\\\", "\\");
I am using the following code to get the contents of a folder into a TreeView. But the current code always adds the contents to the root of the TreeView. It does not add them as child nodes of their parent folder's node.
Can you help me?
void Recurse(string path)
{
DirectoryInfo info = new DirectoryInfo(path);
TreeNode root = new TreeNode(info.Name);
string[] sub = Directory.GetDirectories(info.FullName);
TreeNode node = new TreeNode();
MailTree.Nodes.Add(root);
if (sub.Length == 0) {
}
else
{
foreach(string i in sub)
{
DirectoryInfo subinfo = new DirectoryInfo(i);
root.Nodes.Add(subinfo.Name);
Recurse(i);
}
//MailTree.Nodes.Add(root);
}
}
You should be passing a root node as part of your Rescure method, something like Rescure(string path, TreeNode currentRoot).
Now, you can call currentRoot.Nodes.Add(root) in place of MailTree.Nodes.Add(root), which will ensure that the brances are added only to the current level. You also need to change your call in the loop to Rescure(i, root).
Finally, your initial call to Rescure should include a reference to a pre-created root node, so something like Rescure(initialDirectory, initialRootNode).
One thing I would add is that your method and variable names should be changed to reflect their meaning. Yes, you are recursing, but why? A better name for the method might be TraverseDirectory. Similarly, rather than foreach(string i in sub), why not foreach(string directoryName in sub)? Having clear code is almost as important as having correct code.
The recursive part of your function is always adding the child nodes to the root. You need to add in the "parent node" as a parameter of your recursive function. Something like this:
void Recurse(string path, TreeNode parentNode)
{
DirectoryInfo info = new DirectoryInfo(path);
TreeNode node = new TreeNode(info.Name);
if (parentNode == null)
MailTree.Nodes.Add(node);
else
parentNode.Nodes.Add(node);
string[] sub = Directory.GetDirectories(path);
if (sub.Length != 0)
{
foreach(string i in sub)
{
Recurse(i, node);
}
}
}
I can't se any error in the code at a first glance, but I can suggesto to take another approach: the one you show is too expensive. Just fill a level on the tree, and put some dummy item as a leaf in each nodes you add. Then intercept the NodeExpanding event, remove the dummy node, and add the subnodes ( applying recursively the same strategy of adding the dummy child nodes )
How can I highlight the selected TreeNode (UI.WebControls) in ASP.NET? The purpose is to let the user see which category he or she is viewing at the time.
My thought was that on each TreeNode, check if its property Selected was true and then change it's font or something to another color. I've read about setting the "ForeColor", but it doesn't seem to exist for this type of TreeNode.
Another thought was to add some sort of JavaScript to each Node.
Just as an example, this is what the code looks like today:
private void BuildTree()
{
TreeNode nodeNew = new TreeNode("Unread", MessageFolder.New.ToString());
TreeNode nodeProcessed = new TreeNode("Read", MessageFolder.Processed.ToString());
TreeViewFolders.Nodes.Add(nodeNew);
TreeViewFolders.Nodes.Add(nodeProcessed);
}
You have to work with the Server Control on the ASPX Page, you can specify the
<asp:TreeView id="LinksTreeView"
Font-Names= "Arial"
ForeColor="Blue"
SelectedNodeStyle-ForeColor="Green"
SelectedNodeStyle-VerticalPadding="0"
OnSelectedNodeChanged="Select_Change"
runat="server">
Try this and for more info check this page
What follows is one way to solve the problem in ASP.NET 4.0 with web forms, in a master page.
In the presentation page you could have a TreeView such as the following:
<asp:TreeView
ID="tv"
runat="server"
SelectedNodeStyle-BorderStyle="Solid"
SelectedNodeStyle-HorizontalPadding="5"
SelectedNodeStyle-VerticalPadding="5"
onselectednodechanged="tv_SelectedNodeChanged">
<Nodes>
<asp:TreeNode Text="Contact" Value="~/General/Contact.aspx"></asp:TreeNode>
<asp:TreeNode Text="Change login name" Value="~/General/ChangeLoginName.aspx"></asp:TreeNode>
<asp:TreeNode Text="Change password" Value="~/General/ChangePassword.aspx"></asp:TreeNode>
<asp:TreeNode Text="Terms and Policies" Value="~/General/TermsOfUse.aspx"></asp:TreeNode>
</Nodes>
</asp:TreeView></td>
Important things to note here are:
(1) The URLs for navigation are assigned to the "Value" property, not to the "NavigateUrl" property of the TreeNode class.
(2) We have defined styles for the selected node.
(3) We have defined an event, "onselectednodechanged." A simple way to do that is to double-click on the TreeView in Design View. This also creates an event handler stub in the code-behind file, which we will be using in just a moment.
In the code-behind file, the following three functions are all that is needed:
protected void HighlightSelectedLink(TreeNodeCollection nodes, string treeViewSelectedValue)
{
if (!string.IsNullOrEmpty(treeViewSelectedValue))
{
foreach (TreeNode tn in nodes)
{
if (tn.Value == treeViewSelectedValue)
{
tn.Selected = true;
}
else
{
tn.Selected = false;
}
HighlightSelectedLink(tn.ChildNodes, treeViewSelectedValue);
}
}
}
protected void tv_SelectedNodeChanged(object sender, EventArgs e)
{
string treeViewSelectedValue = tv.SelectedValue;
if (treeViewSelectedValue.EndsWith(".aspx"))
{
Response.BufferOutput = true;
Response.Redirect(tv.SelectedValue);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
string treeViewSelectedValue = Request.AppRelativeCurrentExecutionFilePath;
if (!string.IsNullOrEmpty(treeViewSelectedValue))
{
TreeNodeCollection nodes = tv.Nodes;
HighlightSelectedLink(nodes, treeViewSelectedValue);
}
}
The second function is the handler mentioned above.
In code behind c# :
protected void tv_SelectedNodeChanged(object sender, EventArgs e)
{
TreeView tv = (TreeView)sender;
tv.SelectedNodeStyle.ForeColor = System.Drawing.Color.MidnightBlue;
tv.SelectedNodeStyle.BackColor = System.Drawing.Color.PowderBlue;
tv.SelectedNodeStyle.Font.Bold = true;
}
I am trying to dynamically populate a treeview object on a sharepoint webpart. For some reason, the node population is triggered automatically and without user input. Below is a sample of how I set up the tree and webpart.
Any suggestions on how to prevent the automatic populate would be appreciated.
The following is in the createchildcontrols method:
this.Tree = new TreeView();
this.Tree.EnableClientScript = false;
this.Tree.PopulateNodesFromClient = true;
this.Tree.Nodes.Add(this.FetchTreeNode());
this.Tree.TreeNodePopulate += new TreeNodeEventHandler(Tree_TreeNodePopulate);
The handler looks like this:
void Tree_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
List<MyNode> children = this.FetchChildren(e.Node.Value);
foreach (MyNode child in children)
{
TreeNode node = new TreeNode(child.Name, child.UniqueId, child.IconPath);
node.PopulateOnDemand = true;
node.SelectAction = TreeNodeSelectAction.Expand;
e.Node.ChildNodes.Add(node);
}
}
I've been banging my head on this one for a long time, any suggestions would be appreciated.
So I finally figured this out... for some reason, the default behavior of the treeview was to be expanded, so it would call the treenode populate function right off the bat. I was able to get this to work by calling the treeview.collapseall() method.