A1raa A1raa - 1 month ago 18
C# Question

Assign object to treeview child node in c# to identify parent

Hi I'm trying to attach a child node to a parent node depending on if their strings match.

I'm running into some problems because I'm not sure how to identify a parent by it's name alone. For example if "string a" == "string a" then I want to add the child nodes LoanName to the parent id where the string matches the parent name.

This works if I do:

tvTodoList.Nodes[0].Nodes.Add(activityResult.ActivityName);


But obviously this will attach the child node to the first parent node in the treeview. How do I get it to match the name of the variable loanresult.LoanName?

Below is the code for my FillTodoList method

private void FillTodoList()
{
var nol = NetworkOpsLayer.NetworkOpsLayer.CreateForDirectMongoConnection("mongodb://localhost", "test", "loans");
//demoSave(nol);

var loanList = nol.GetDocsWhichMatchGivenDocString("{ \"isActive\" : 1 }");

foreach (string s in loanList)
{
//System.Console.WriteLine(s);
var loanResult = JsonConvert.DeserializeObject<RootObject>(s);

tvTodoList.Nodes.Add("Loan Name: " + loanResult.LoanName);

//Add children to each Loan

var con = NetworkOpsLayer.NetworkOpsLayer.CreateForDirectMongoConnection("mongodb://localhost", "test", "activity");
//demoSave(con);
var activityList = con.GetDocsWhichMatchGivenDocString("{ \"isActive\" : 1 }");

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

Answer

The method TreeNodeCollection.Find(string, boolean) will help with this...

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