[c#] adding child nodes in treeview

I'm new to C# and don't have any programming experience. But I've finish a C# basics. Now I would like to design a simple tree view by adding parent node and child node.

I would like to add a second child for the Second node, I'm quite stuck here and don't know what's next.

Any ideas?

Here is the code:

    private void addParentNode_Click(object sender, EventArgs e)
    {
        string yourParentNode;
        yourParentNode = textBox1.Text.Trim();
        treeView2.Nodes.Add(yourParentNode);
    }

    private void addChildNode_Click(object sender, EventArgs e)
    {
        string yourChildNode;
        yourChildNode = textBox1.Text.Trim();
        treeView2.Nodes[0].Nodes.Add(yourChildNode);
    }

Sorry I wasn't clear, I'm not sure if I really need this one here:

  //treeView1.BeginUpdate(); 
  //treeView1.Nodes.Clear();

What I'm trying to do, is to add Parent Nodes and child node. In my code, I can add several Parent Nodes, but if I want to add a child node, it only add in the first parent node. I want that if I add a child node, I want to add it to the second parent or third parent.

In my code I only use one treeview here which names as treeview2 Here is the screenshot

this is how my final code looks like: Before I put the else, I'm getting an error if I don't select anything. So I made it that way that if there is nothing selected it will add the "child node" to the "default node" or (parent1 node). It seems to work good. Thanks guys;-)

    //This is for adding a parent node
    private void addParentNode_Click(object sender, EventArgs e)
    {
        treeView2.BeginUpdate();

        string yourParentNode;
        yourParentNode = textBox1.Text.Trim();
        treeView2.Nodes.Add(yourParentNode);
        treeView2.EndUpdate();
    }

    //This is for adding child node
    private void addChildNode_Click(object sender, EventArgs e)
    {
        if (treeView2.SelectedNode != null)
        {
            string yourChildNode;
            yourChildNode = textBox1.Text.Trim();

            treeView2.SelectedNode.Nodes.Add(yourChildNode);
            treeView2.ExpandAll();
        }
        //This is for adding the child node to the default node(parent 1 node)
        else
        {
            string yourChildNode;
            yourChildNode = textBox1.Text.Trim();
            treeView2.Nodes[0].Nodes.Add(yourChildNode);
        }

Additional question: Are there any other ways on how the code be better? Because here, I declare the string "yourChildNode" twice. One in the if and other one in the else, are there any simplification?

This question is related to c# treeview

The answer is


Guys use this code for adding nodes and childnodes for TreeView from C# code. *

KISS (Keep It Simple & Stupid :)*

protected void Button1_Click(object sender, EventArgs e)

{

        TreeNode a1 = new TreeNode("Apple");

        TreeNode b1 = new TreeNode("Banana");
        TreeNode a2 = new TreeNode("gree apple");
        TreeView2.Nodes.Add(a1);
        TreeView2.Nodes.Add(b1);
        a1.ChildNodes.Add(a2);

}


Example of adding child nodes:

private void AddExampleNodes()
        {
            TreeNode node;

            node = treeView1.Nodes.Add("Master node");
            node.Nodes.Add("Child node");
            node.Nodes.Add("Child node 2");

            node = treeView1.Nodes.Add("Master node 2");
            node.Nodes.Add("mychild");
            node.Nodes.Add("mychild");
        }

May i add to Stormenet example some KISS (Keep It Simple & Stupid):

If you already have a treeView or just created an instance of it: Let's populate with some data - Ex. One parent two child's :

            treeView1.Nodes.Add("ParentKey","Parent Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey"].Nodes.Add("Child-2 Text");

Another Ex. two parent's first have two child's second one child:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes.Add("ParentKey2","Parent-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-2 Text");
            treeView1.Nodes["ParentKey2"].Nodes.Add("Child-3 Text");

Take if farther - sub child of child 2:

            treeView1.Nodes.Add("ParentKey1","Parent-1  Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("Child-1 Text");
            treeView1.Nodes["ParentKey1"].Nodes.Add("ChildKey2","Child-2 Text");
            treeView1.Nodes["ParentKey1"].Nodes["ChildKey2"].Nodes.Add("Child-3 Text");

As you see you can have as many child's and parent's as you want and those can have sub child's of child's and so on.... Hope i help!


void treeView(string [] LineString)
    {
        int line = LineString.Length;
        string AssmMark = "";
        string PartMark = "";
        TreeNode aNode;
        TreeNode pNode;
        for ( int i=0 ; i<line ; i++){
            string sLine = LineString[i];
            if ( sLine.StartsWith("ASSEMBLY:") ){
                sLine  = sLine.Replace("ASSEMBLY:","");
                string[] aData = sLine.Split(new char[] {','});
                AssmMark  = aData[0].Trim();
                //TreeNode aNode;
                //aNode = new TreeNode(AssmMark);
                treeView1.Nodes.Add(AssmMark,AssmMark);
            }
            if( sLine.Trim().StartsWith("PART:") ){
                sLine  = sLine.Replace("PART:","");
                string[] pData = sLine.Split(new char[] {','});
                PartMark = pData[0].Trim();
                pNode = new TreeNode(PartMark);
                treeView1.Nodes[AssmMark].Nodes.Add(pNode);
            }
        }

I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.

It's actually really easy to reference the correct node to receive the new child node.

private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
   //show dialogbox to let user name the new node
   frmDialogInput f = new frmDialogInput();
   f.ShowDialog();

    //find the node that was selected
    TreeNode myNode = TreeView1.SelectedNode;
    //create the new node to add
    TreeNode newNode = new TreeNode(f.EnteredText);
    //add the new child to the selected node
    myNode.Nodes.Add(newNode);
}

You may do as follows to Populate treeView with parent and child node. And also with display and value member of parent and child nodes:

   arrayRoot = taskData.GetRocordForRoot();  // iterate through database table
    for (int j = 0; j <arrayRoot.length; j++) { 
                TreeNode root = new TreeNode();  // Creating new root node
                root.Text = "displayString";
                root.Tag = "valueString";
                treeView1.Nodes.Add(root); //Adding the root node

             arrayChild = taskData.GetRocordForChild();// iterate through database table
                for (int i = 0; i < arrayChild.length; i++) {
                    TreeNode child = new TreeNode(); // creating child node
                    child.Text = "displayString"
                    child.Tag = "valueString";
                    root.Nodes.Add(child); // adding child node
                }

            }

It looks like you are only adding children to the first parent treeView2.Nodes[0].Nodes.Add(yourChildNode)
Depending on how you want it to behave, you need to be explicit about the parent node you wish to add the child to.
For Example, from your screenshot, if you wanted to add the child to the second node you would need:
treeView2.Nodes[1].Nodes.Add(yourChildNode)
If you want to add the children to the currently selected node, get the TreeView.SelectedNode and add the children to it.

Try TreeView to get an idea of how the class operates. Unfortunately the msdn documentation is pretty light on the code samples...

I'm missing a whole lot of safety checks here!

Something like (untested):

private void addChildNode_Click(object sender, EventArgs e) {
  TreeNode ParentNode = treeView2.SelectedNode;  // for ease of debugging!
  if (ParentNode != null) {
    ParentNode.Nodes.Add("Name Of Node");
    treeView2.ExpandAll();   // so you can see what's been added              
    treeView2.Invalidate();  // requests a redraw
  }
}

You can improve that code

 private void Form1_Load(object sender, EventArgs e)
    {
        /*
         D:\root\Project1\A\A.pdf
         D:\root\Project1\B\t.pdf
         D:\root\Project2\c.pdf
         */
        List<string> n = new List<string>();
        List<string> kn = new List<string>();
        n = Directory.GetFiles(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        kn = Directory.GetDirectories(@"D:\root\", "*.*", SearchOption.AllDirectories).ToList();
        foreach (var item in kn)
        {
            treeView1.Nodes.Add(item.ToString());
        }
        for (int i = 0; i < treeView1.Nodes.Count; i++)
        {
            n = Directory.GetFiles(treeView1.Nodes[i].Text, "*.*", SearchOption.AllDirectories).ToList();
            for (int zik = 0; zik < n.Count; zik++)
            {
                treeView1.Nodes[i].Nodes.Add(n[zik].ToString());
            }
        }        
    }

SqlConnection con = new SqlConnection(@"Data Source=NIKOLAY;Initial Catalog=PlanZadanie;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();
        DataTable dt = new DataTable();
        public void loadTree(TreeView tree)
        {
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT [RAZDEL_ID],[NAME_RAZDEL] FROM [tbl_RAZDEL]";
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    tree.Nodes.Add(reader.GetString(1));
                    tree.Nodes[0].Nodes.Add("yourChildNode");
                    tree.ExpandAll();

                }

                con.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("?????? ? ??????????: " + ex.Message);
            }


        }