I can't get the line that was read from the file added to my treeview. So here is what my code is doing. It reads through a file line by line and adds a line at a time into my treeview. My code runs through with no error.
+ tree
|___ node1
|___ line < line should be inserted here, but not working >
Any help or pointers is greatly appreciated.
|
theLizardPosted Oct 18, 2009, 6:01 PM
theLizard
wowPosted Oct 20, 2009, 8:13 PM
Thanks,
theLizardPosted Oct 20, 2009, 7:09 PM
put a treeview on your form then in form load
private void Form1_Load(object sender, EventArgs e)
{
TreeNode rootNode;
rootNode = TreeView1.Nodes.Add("Home"); //this adds a node with the TEXT being "Home"
rootNode.Nodes.Add("Child1"); //this adds a child node to the parent node with the TEXT being "Child"
rootNode.Nodes.Add("Child2"); //what is between the quotes (") is irrelevant,
//it is simply the text you want to see at that node level
rootNode.Nodes.Add("Child3");
}
If this does not work you have a problem.
wowPosted Oct 20, 2009, 6:36 PM
So I tried both solutions and it does not seem to be adding to my treeview1.
In the .Add() function, am I suppose to put the node name in quotes like if the parent node and the child of that parent if I wanted to add to that child.
I'm not quite sure on the above. I tried both and they did not work either. So I don't know what is going on. I put the MessageBox.Show() before it prints and it does show the box with the line content. When I go back to check the tree view, nothing is added. I've been struggling at this for so long now.
Any pointers to what I should do next?
wowPosted Oct 20, 2009, 5:26 PM
I didn't have the time to work it over the weekend. So I am working out the solutions you both provided to me. Thank you so much for your help. I will definitely come back to this ASAP when I have solved this and mark it solved.
jingePosted Oct 18, 2009, 9:52 PM
jingePosted Oct 17, 2009, 3:09 AM
There are some errors in your code.
So assume we have dragged a treeview to the form, and name it treeview1.
The File.txt contains the following data.
We can then use the following code to add the nodes to the treeview.
string line;
StreamReader sr = new StreamReader("File.txt");
treeView1.Nodes.Add("tree");
treeView1.Nodes[0].Nodes.Add("node1");
while((line = sr.ReadLine()) != null){
TreeNode tn = new TreeNode();
tn.Text = line;
MessageBox.Show(line);
// Test to see if it reaches here and what the node before adding.
treeView1.Nodes[0].Nodes[0].Nodes.Add(tn);}
The result is:
+tree
-Node
-ABC
-BCD
-DEF