Developer
Developer

Reputation: 8646

How to add a child node to a dynamically added child node

I am having a treeview on my main form

I have my code from a from to main form is as follows

 Buttonclick

StrNode = string.Empty;
StrNode = "Batch" + Append.Batchcnt.ToString() + "(" + strSelectedClassCode + ")";
frmmain.loadFromForm(StrNode, true, strSelectedClassCode);

On my main form i have my code as follows

public void loadFromForm(string strNode, bool bResult, string strStandardClsCode)
    {
        if (Append.oldbatchcontrol != strNode)
        {
            if (tvwACH.SelectedNode.Text == "FileHeader")
            {
                tvwACH.SelectedNode.Nodes.Add(strNode);
            }
            if (tvwACH.SelectedNode.Text == "BatchHeader")
            {
                tvwACH.SelectedNode.Nodes.Add(strNode);// After this i have to add another node as a child to that added node and also if a node with particular name exists i would like to write the text with a count value appended
            }
  }
        }

So that my treeview should be as follows

ACH
|->Some.txt
  |->Fileheader
    |->BatchHeader
       |->Batch1
          |->Entry1
          |->Entry2 and so on // These two should be added dynamically after that Batch1

Upvotes: 0

Views: 1703

Answers (2)

WraithNath
WraithNath

Reputation: 18013

You usually need a recursive function to build a tree. For example:

private void AddNode(NodeParent, Data)
{
    Node oNode;

    //Check if this is the first node
    if (NodeParent ==null)
    {
         oNode = new Node(Data.Name);
    }

    //Step though each child item in the data
    foreach(DataItem in Data)
    {
        //Add the node
         this.AddNode(oNode, DataItem);
    }

    oNode.Nodes.Add(new Node(Data));
}

This code is a rough guide, but it should give you an idea.

Upvotes: 2

Amir
Amir

Reputation: 820

Use this instead :

public void loadFromForm(string strNode, bool bResult, string strStandardClsCode)
    {
        if (Append.oldbatchcontrol != strNode)
        {
            if (tvwACH.SelectedNode.Text == "FileHeader")
            {
                tvwACH.SelectedNode.Nodes.Add(strNode);
            }
            if (tvwACH.SelectedNode.Text == "BatchHeader")
            {
                TreeNode node = tvwACH.SelectedNode.Nodes.Add(strNode,strNode);// After this i have to add another node as a child to that added node and also if a node with particular name exists i would like to write the text with a count value appended
                node.Nodes.Add(...);
            }
  }
}

Upvotes: 2

Related Questions