In the MSDN is writen about TreeNode that:
"By default, a node is in selection mode."
"To put a node into selection mode, set the node's NavigateUrl property to an empty string."
"When a node is in selection mode, use the SelectAction property to specify which event or events are raised when a node is selected."
"Setting TreeNodeSelectAction value TreeNodeSelectAction.Select Raises the SelectedNodeChanged event when a node is selected."
Please see TreeNode
Here is the problem and possibly a bug in the control:
When I set the TreeNode object PopulateOnDemand value to true and call the Collapse() function on that node.
Then the TreeNodeExpanded event is raised in addition to the SelectedNodeChanged event.
This is in complate contradiction to what is writen in the MSDN.
According to the MSDN this sould happen only if TreeNodeSelectAction Property is set to
TreeNodeSelectAction.SelectExpand value.
Does some know whats the cause for that?
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);
}
}
//MSDN : Occurs when a node with its PopulateOnDemand property set to true is expanded in //the TreeView control.
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
LoadChildNode(e.Node);
}
private void PopulateTopNodes(string pathToRootFolder)
{
DirectoryInfo dirInfo = new DirectoryInfo(pathToRootFolder);
DirectoryInfo[] dirs = dirInfo.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
string relativePath = (dir.FullName).Replace(pathToRootFolderPrefix, "");
TreeNode folderNode = new TreeNode(dir.Name, relativePath);
if (dir.GetDirectories().Length > 0)
{
folderNode.PopulateOnDemand = true;
folderNode.Collapse();
}
folderNode.NavigateUrl = "";
folderNode.SelectAction = TreeNodeSelectAction.Select;
TreeView1.Nodes.Add(folderNode);
}
}
private void LoadChildNode(TreeNode treeNode)
{
string d = treeNode.NavigateUrl;
string action = treeNode.SelectAction.ToString();
string fullPath = Path.Combine(pathToRootFolderPrefix, treeNode.Value);
DirectoryInfo dirInfo = new DirectoryInfo(fullPath);
DirectoryInfo[] dirs = dirInfo.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
string relativePath = (dir.FullName).Replace(pathToRootFolderPrefix, "");
TreeNode folderNode = new TreeNode(dir.Name, relativePath);
if(dir.GetDirectories().Length>0){
folderNode.PopulateOnDemand = true;
folderNode.Collapse();
}
folderNode.NavigateUrl = "";
folderNode.SelectAction = TreeNodeSelectAction.Select;
treeNode.ChildNodes.Add(folderNode);
}
}
//MSDN:Occurs when a node is selected in the TreeView control.
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
}
Thanks
I'm don't know ASP.Net, but just reading your code you are setting it to SelectExpand but in your comments above it sounds like you think you're setting it to Select (or this just a typo in the sample code?). In both methods in your sample it's written as:
folderNode.SelectAction = TreeNodeSelectAction.SelectExpand;
Related
I use XtratreeList with fileExplorerAssistant. I have a problem when I want to get the path of the selected folder from treelist. Or I have a problem in getting the folder path from TreeListNode. Please help me.
My code is :
private void frmMovieAddAuto_Load(object sender, EventArgs e)
{
// Scan for all partitions
System.IO.DriveInfo[] driveList = System.IO.DriveInfo.GetDrives();
foreach (var drive in driveList)
{
// Select only logical fixed partitions
if (drive.DriveType == System.IO.DriveType.Fixed && drive.IsReady)
{
// Add each drive as a root node
treeListExtension1.RootNodes.Add(new PathNode(drive.RootDirectory.ToString()));
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
TreeListColumn columnname;
columnname = treeList1.Columns[0];
columnname.Caption = "Folder Name";
List<TreeListNode> nodes = treeList1.GetNodeList();
foreach (TreeListNode node in nodes)
{
if (node.Checked == true)
{
DirectoryInfo di = new DirectoryInfo(node.GetValue(columnname).ToString());
foreach (FileInfo fi in di.GetFiles("*.avi;*.mpg;*.mpeg;*.mp4;*.mkv;*.divx;*.AVI;*.MPG;*.MPEG;*.MP4;*.MKV;*.DIVX", SearchOption.AllDirectories))
{
//do something
}
}
}
}
In this code:
private void treeList1_AfterCheckNode(object sender, DevExpress.XtraTreeList.NodeEventArgs e)
{
// Get the node that is currently focused (selected) in the TreeList
TreeListNode focusedNode = treeList1.FocusedNode;
// Get the column that contains the folder path
TreeListColumn folderPathColumn = treeList1.Columns[0];
// Get the value of the folder path column from the focused node
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
if(focusedNode.Checked == true)
{
pathfolderList.Add(folderPath);
}
}
In this line code:
string folderPath = focusedNode.GetValue(folderPathColumn).ToString();
It gives this error:
'Object reference not set to an instance of an object.'
Your question is how to get the full path of a DevExpress.XtraTreeList.Nodes.TreeListNode. This requires traversing the DisplayText from the selected node up to its root, When this collection is reversed and combined, the result is the full path.
foreach (var node in treeList1.GetNodeList())
{
List<string> builder = new List<string>();
TreeListNode traverse = node;
// This adds the display text from the leaf to the root.
while(traverse != null)
{
builder.Add(traverse.GetDisplayText(0));
traverse = traverse.ParentNode;
}
// What we want is the root to the leaf, so reverse the list.
builder.Reverse();
// Now combine into a path.
var path = Path.Combine(builder.ToArray());
Debug.WriteLine(path);
}
You might also find the DevExpress documentation helpful (their approach is slightly different).
Here is code:
private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeNode(directoryInfo.Name + " (" + DirSize(new DirectoryInfo(directoryInfo.FullName)) + " bytes)" + " (" + directoryInfo.GetFileSystemInfos().Length + " files)"+ directoryInfo.CreationTime);
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Nodes.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Nodes.Add(new TreeNode(file.Name + " (" + file.Length + " bytes)"));
return directoryNode;
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string selectedNodeText = "a";
textBox1.Text = selectedNodeText;
}
I need to access directoryInfo.CreationTime from TreeNode and display it in treeView1_AfterSelect text.Box1 but I can't find right way.
You can use the Tag property of TreeNode to put the value there and then access it in the event :
directoryNode.Tag = directoryInfo;
and then in event you can access it :
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var directoryInfo = e.Node.Tag as DirectoryInfo;
var time = directoryinfo.CreationTime;
}
or:
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var directoryInfo = treeView1.SelectedNode.Tag as DirectoryInfo;
var creationTime = drInfo.CreationTime;
}
Hope it helps!
Tree nodes expose the Tag property that is used to store and retrieve a custom information under nodes. It can even hold a reference to a complex structure.
https://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag(v=vs.110).aspx
I have a button "Choose folder". When i choose folder, it shows all the directories and sub-directories in treeview. Everything is working fine.
What i need now is - when i click in the treeview on some directory in shows all files that is in that directory in the listbox.
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
if (directoryInfo.Exists)
{
VeidotKoku(directoryInfo, treeView1.Nodes);
}
}
}
private void VeidotKoku(DirectoryInfo directoryInfo, TreeNodeCollection Pievienot)
{
TreeNode tagadejaNode = Pievienot.Add(directoryInfo.Name);
foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
{
VeidotKoku(subdir, tagadejaNode.Nodes);
}
}
System.IO.Path.GetFileNameWithoutExtension(fileLocationPath);
Will get the extensionless path.
Else, if you just want to get the value you can split the path and get the last element.
foreach(string filePath in filePaths)
{
string[] brokenPath = filePath.Split('/');
listBox.Add(brokenPath.Last());
}
Top of my head.
I am populating a listbox with a file. This can be done by two methods, the open file dialog command initiated by a button press and a drag/drop action into the listbox. I want to pass on the file path (for the file in the listbox) to other areas of my code, for example the DataContext that reads the file in the listbox. Basically I want the file path to automatically update when the listbox is populated. I am new to C# so sorry if I haven't explained myself properly or provided enough information. The code for populating my listbox (named FilePathBox) and the 'Run' button is as follows:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.Multiselect = true;
openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog())
{
FilePathBox.Items.Clear();
foreach (string filename in openFileDialog.FileNames)
{
ListBoxItem selectedFile = new ListBoxItem();
selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
selectedFile.ToolTip = filename;
FilePathBox.Items.Add(selectedFile);
}
}
}
private void FilesDropped(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
FilePathBox.Items.Clear();
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
FilePathBox.Items.Add(fileItem);
}
}
}
private void RunButton_Click(object sender, RoutedEventArgs e)
{
DataContext = OldNewService.ReadFile(#"C:\Users\Documents\Lookup Table.csv");
}
I added a comment, but I think what you need a way to get the selected file path when the RunButton is clicked, so just add this to your RunButton_Click method,
private void RunButton_Click(object sender, RoutedEventArgs e)
{
string selection = (string)FilePathBox.SelectedItem;
DataContext = OldNewService.ReadFile(selection);
}
How can I hide the rootnode in this case the "temp" folder?
I want to do this whitout setting a CssClass on the rootnode.
TreeView TreeView1 = new TreeView();
protected void Page_Load(object sender, EventArgs e)
{
BuildTree(#"C:\temp");
form1.Controls.Add(TreeView1);
}
private void BuildTree(string root)
{
DirectoryInfo rootDir = new DirectoryInfo(root);
TreeNode rootNode = new TreeNode(rootDir.Name, rootDir.FullName);
TreeView1.Nodes.Add(rootNode);
TraverseTree(rootDir, rootNode);
}
private void TraverseTree(DirectoryInfo currentDir, TreeNode currentNode)
{
foreach (DirectoryInfo dir in currentDir.GetDirectories())
{
TreeNode node = new TreeNode(dir.Name, dir.FullName);
currentNode.ChildNodes.Add(node);
TraverseTree(dir, node);
}
foreach (FileInfo file in currentDir.GetFiles())
{
TreeNode nodeFile = new TreeNode(file.Name, file.FullName);
currentNode.ChildNodes.Add(nodeFile);
}
}
The code is complete and redy to run just change the path to your desktop.
Why not just not add the Root node in the first place, instead, set all the direct descendants as level 1 nodes:
TreeView TreeView1 = new TreeView();
protected void Page_Load(object sender, EventArgs e)
{
BuildTree(#"C:\temp");
form1.Controls.Add(TreeView1);
}
private void BuildTree(string root)
{
DirectoryInfo rootDir = new DirectoryInfo(root);
TreeNode rootNode = new TreeNode(rootDir.Name, rootDir.FullName);
TraverseTree(rootDir, TreeView1.Nodes);
}
private void TraverseTree(DirectoryInfo currentDir, TreeNodeCollection nodeCollection)
{
foreach (DirectoryInfo dir in currentDir.GetDirectories())
{
TreeNode node = new TreeNode(dir.Name, dir.FullName);
nodeCollection.Add(node);
TraverseTree(dir, node.ChildNodes);
}
foreach (FileInfo file in currentDir.GetFiles())
{
TreeNode nodeFile = new TreeNode(file.Name, file.FullName);
nodeCollection.Add(nodeFile);
}
}
Edit: I have amended the code above to remove the AddToNode Method I wrote. The previous method was checking to see if the currentNode object passed in was null, and if so adding it to the NodesCollection of TreeView1 (otherwise to the ChildNodes collection of the currentNode). Instead, rather than passing the node around, I'm passing the NodeCollection of the node around - this means that we can simplify the logic a fair bit).