0

I'm trying to add a child node to a parent node in a treeview. I'm finding the loan name by specific key loanresult.LoanName to the node text. Both show as "TestOne" however the child is not being added to the parent tree node.

Matches then throws the error matches[0].Nodes = 'matches[0].Nodes' threw an exception of type 'System.IndexOutOfRangeException' due to no matches being found.

foreach (string st in activityList)
{
    var activityResult = JsonConvert.DeserializeObject<Activity>(st);
    if (loanResult.LoanName == activityResult.ParentLoanName)
    {
        TreeNode[] matches = tvTodoList.Nodes.Find(loanResult.LoanName, false);
        if (matches.Length > 0) matches[0].Nodes.Add(activityResult.ActivityName);
    }
}

Text

enter image description here

Key

enter image description here

I must be missing something obvious here?

A1raa
  • 605
  • 1
  • 7
  • 22
  • 2
    You should assign the key to `Name` property. The `Text` property is for showing text, `Name` will be used as a key, so you can find the node by its key. Also when finding, if you want to find in all nodes including descendants, pass `true` as second parameter: `var node = treeView1.Nodes.Find("some key", true).FirstOrDefault();` then check `if(node!=null)` then do something. See *Find By Name* example in [this post](http://stackoverflow.com/a/34228733/3110834). – Reza Aghaei Oct 31 '16 at 12:42

1 Answers1

1

Instead using single parameter constructor, use an overload with two parameters as following

//matches[0].Nodes.Add ("Your Key", "Node Text to display")
matches[0].Nodes.Add(loanResult.LoanName,activityResult.ActivityName);

Because you are not specifying any key while adding new node hence, it is not able to search any node by key.

Munawar
  • 2,588
  • 2
  • 26
  • 29
  • Turns out I wasn't giving each node a key and text. I had `tvTodoList.Nodes.Add(loanResult.LoanName);` which was only assigning the text to each node with the name being an empty string `""`. By adding `tvTodoList.Nodes.Add(loanResult.LoanName, loanResult.LoanName);` gave me the desired results. – A1raa Oct 31 '16 at 14:29