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).
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).
i want to fetch elements through search pattern like if i type "an" then i want all elements which have "an" example =man, animal, fan, pant
this is my code here i use foreach loop to display all search elements but i don't want to use foreach loop just i want to fetch all the list directly form xpath query please help me out its very impotent for me
private void Search2_Click_1(object sender, EventArgs e)
{
XmlNodeList nodes = myxml.DocumentElement.SelectNodes("/students/student/s_name" );
string ha = search.Text;
if (listbox11.Text == "Name")
foreach(XmlNode node in nodes)
{
if(System.Text.RegularExpressions.Regex.IsMatch(node.InnerText,ha))
{
listBox1.Text += node.InnerText + "\r\n";
}
}
}
Use this
private void Search2_Click_1(object sender, EventArgs e)
{
string ha = search.Text;
XmlNodeList nodes = myxml.DocumentElement.SelectNodes("/students/student/[contains(s_name,ha)]");
}
**The code which i write is simple, xpath query will fetch only related elements nodes but if you want to print then use foreach loop **
private void Search2_Click_1(object sender, EventArgs e)
{
string ha = search.Text;
if (listbox11.Text == "Name")
{
listBox1.Text = "";
XmlNodeList nodes = myxml.DocumentElement.SelectNodes("//s_name[descendant-or-self::*[contains(.,'" + ha + "')]]");
foreach (XmlNode node in nodes)
{
listBox1.Text += node.InnerText + "\r\n";
}
}
}
I have winForms project , my button_click 1 is add in elements of my one of documents chapters and sections. I want to save my configurations in configurations file test.json (it is written by JSON format) . I am saving everything what is chosen by checking check boxes. And later I want to load what check boxes are checked. But how to wait till button_click1 event will be clicked and my check boxes will appear. My load files looks like:
private void SaveConfig(string path)
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
foreach (TreeNode node in treeView1.Nodes)
{
{
config.Parts.Add(new DocPart { NodeTitle = node.Text, NodeChecked = node.Checked });
}
{
foreach (TreeNode child in node.Nodes)
{
config.Parts.Add(new DocPart { ChildTitle = child.Text, ChildChecked = child.Checked });
}
}
var configString = config.SaveToString();
File.WriteAllText(path, configString);
}
}
private void LoadConfig(string path)
{
var cfgString = File.ReadAllText(path);
var cfg = DocConfig.LoadFromString(cfgString);
foreach (var part in cfg.Parts)
{
foreach (TreeNode node in treeView1.Nodes)
{
if (part.NodeTitle == "chap1")
{
node.Checked = part.NodeChecked;
}
if (part.NodeTitle == "chap2")
{
node.Checked = part.NodeChecked;
}
if (part.NodeTitle == "chap3")
{
node.Checked = part.NodeChecked;
}
}
}
}
}
}
Removed button1_click() and added this class
private void Initializetreeview();
treeView1.Nodes.Add(new TreeNode("chapter1") { Tag = #"\include {chapter1}" }); ;
treeView1.Nodes.Add(new TreeNode("chapter2") { Tag = #"\include {chapter2}" });
treeView1.Nodes.Add(new TreeNode("chapter3") { Tag = #"\include {chapter3}" });
treeView1.Nodes[0].Nodes.Add(new TreeNode("section1") { Tag = #"\input {sec1}" });
treeView1.Nodes[1].Nodes.Add(new TreeNode("section2") { Tag = #"\input {sec2}" });
treeView1.Nodes[2].Nodes.Add(new TreeNode("section3") { Tag = #"\input {sec3}" });
Removing from added list button2_Click:
private void button2_Click(object sender, EventArgs e)
{
RemoveChecked(treeView1.Nodes);
}
void RemoveChecked(TreeNodeCollection nodes)
{
foreach (TreeNode checkedNode in FindCheckedNodes(nodes))
{
nodes.Remove(checkedNode);
}
}
private List<TreeNode> FindCheckedNodes(TreeNodeCollection nodes)
{
List<TreeNode> checkedNodes = new List<TreeNode>();
foreach (TreeNode node in nodes)
{
if (node.Checked)
{
checkedNodes.Add(node);
}
else
{
// find checked childs
checkedNodes.AddRange(FindCheckedNodes(node.Nodes));
}
}
return checkedNodes;
}
Here is my load event handler, where I call my LoadConfig:
private void Form1_Load(object sender, EventArgs e)
{
Initializetreeview();
var cmdArgs = Environment.GetCommandLineArgs();
if (cmdArgs.Length == 1)
{
//MessageBox.Show("None file loaded as parameter");
}
if (cmdArgs.Length == 2)
{
//MessageBox.Show("JSON file is not loaded as parameter");
var dconfFilename = cmdArgs[1];
LoadConfig(dconfFilename);
}
}
Because LoadConfig method assume that TreeView control already has nodes with names, you need initialize TreeView before executing LoadConfig method
//Create method which initialize treeview control with your nodes
private void InitializeTreeView()
{
this.treeView1.Nodes.Add(new TreeNode("chapter1") { Tag = #"\include {chapter1}" });
this.treeView1.Nodes.Add(new TreeNode("chapter2") { Tag = #"\include {chapter2}" });
this.treeView1.Nodes.Add(new TreeNode("chapter3") { Tag = #"\include {chapter3}" });
this.treeView1.Nodes[0].Nodes.Add(new TreeNode("section1") { Tag = #"\input {sec1}" });
this.treeView1.Nodes[1].Nodes.Add(new TreeNode("section2") { Tag = #"\input {sec2}" });
this.treeView1.Nodes[2].Nodes.Add(new TreeNode("section3") { Tag = #"\input {sec3}" });
}
private void Form_Load(Object sender, EventArgs e)
{
this.InitializeTreeView();
//Now you can load your config
var cmdArgs = Environment.GetCommandLineArgs();
if (cmdArgs.Length == 1)
{
//MessageBox.Show("None file loaded as parameter");
}
if (cmdArgs.Length == 2)
{
//MessageBox.Show("JSON file is not loaded as parameter");
var dconfFilename = cmdArgs[1];
LoadConfig(dconfFilename);
}
}
once again i have a problem that i can't quite seem to come up with a solution to. so here it is, I have a ListView displaying the directories of Image files,i want the listview to display these images for these files, the problem is I also need the images to be modified by the program at a per-pixel level so i have this done on a separate thread, so what i want to do is take my already existing PictureBox list of the modified Images and match up the names of the files with the corresponding image. Any ideas on how to do this?
here is what i have so far
public static List<PictureBox> ContentItems = new List<PictureBox>();
...
public static string ContentDirectory = "";
private void FileTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
FileList.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
item = new ListViewItem(file.Name);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
FileList.Items.Add(item);
}
FileList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
I Did have to use an image list after all Heres how i got it to work:
void FileTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
TreeNode newSelected = e.Node;
FileList.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
ContentImg.Images.Clear();
int CurrentImg = 0;
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
string fileName = file.Name;
foreach (PictureBox PB in ContentItems)
{
if (fileName == PB.Name)
{
//Get Image
ContentImg.Images.Add(PB.Image);
item = new ListViewItem(file.Name, CurrentImg);
subItems = new ListViewItem.ListViewSubItem[]
{ new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item,
file.LastAccessTime.ToShortDateString())};
item.SubItems.AddRange(subItems);
FileList.Items.Add(item);
CurrentImg += 1;
}
}
}
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;