Below is my code
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\Shahul\Documents\Visual Studio 2010\Projects\TreeView\TreeView\bin\FileExplorer");
private void Form1_Load(object sender, EventArgs e)
{
if (Directory.Exists("FileExplorer"))
{
try
{
DirectoryInfo[] directories = directoryInfo.GetDirectories();
foreach (FileInfo file in directoryInfo.GetFiles())
{
if (file.Exists)
{
TreeNode nodes = treeView.Nodes[0].Nodes.Add(file.Name);
}
}
if (directories.Length > 0)
{
foreach (DirectoryInfo directory in directories)
{
TreeNode node = treeView.Nodes[0].Nodes.Add(directory.Name);
node.ImageIndex = node.SelectedImageIndex = 0;
foreach (FileInfo file in directory.GetFiles())
{
if (file.Exists)
{
TreeNode nodes = treeView.Nodes[0].Nodes[node.Index].Nodes.Add(file.Name);
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
When I run I just get a blank treeview form? Unable to figure out what is the error?
Btw this my first post in Stack Overflow.
WinForms TreeView Control has in-built support for printing. To print the content of treeview, convert the treeview into the printable document using TreeViewPrintDocument.
To search for a node in TreeView, you can use Search or SearchAll method of C1TreeView class. The Search method takes string as a value, searches for the nodes using depth-first search and returns the node containing the searched string.
To add nodes programmatically Use the Add method of the tree view's Nodes property.
The Nodes property holds a collection of TreeNode objects, each of which has a Nodes property that can contain its own TreeNodeCollection.
This should solve your problem, I tried on WinForm though:
public Form1()
{
InitializeComponent();
DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\Users\hikuma\Documents\IR");
if (directoryInfo.Exists)
{
treeView1.AfterSelect += treeView1_AfterSelect;
BuildTree(directoryInfo, treeView1.Nodes);
}
}
private void BuildTree(DirectoryInfo directoryInfo, TreeNodeCollection addInMe)
{
TreeNode curNode = addInMe.Add(directoryInfo.Name);
foreach (FileInfo file in directoryInfo.GetFiles())
{
curNode.Nodes.Add(file.FullName, file.Name);
}
foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
{
BuildTree(subdir, curNode.Nodes);
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if(e.Node.Name.EndsWith("txt"))
{
this.richTextBox1.Clear();
StreamReader reader = new StreamReader(e.Node.Name);
this.richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
It is a simple example of how you can open file in rich text box, it can be improved a lot :). You might want to mark as answer or vote up if it helped :) !!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With