0
votes

How to add items in tree view? For one DataRow, it contains parent item as one column and the rest columns are child nodes. Row structure is as follow.

Table - Person

column1 - SSN (text)

column2 - Name (text)

column3 - Age (int)

column4 - country (text)

column5 - height (double)

When you click/expand Name, it looks like below.

(-) Name

- Age

- Country

- Height

Each row will be displayed like above TreeView. How to populate this in TreeView? 3 columns in the row are child node of Name column (parent node). I am using C# and .Net 4.5 and Winform application only. I managed to connect to database already. Only need to populate TreeView with DataRowCollection.

Here is sample code trying to achieve the above idea.

private void FillDataInTree(DataRowCollection rows)
    {
        foreach(DataRow r in rows)
        {
            TreeNode[] cNodes = new TreeNode[3];
            for(int i=0; i<3; i++)
            {
                cNodes[i].Text = r[i + 1].ToString();
            }
            TreeNode node = new TreeNode(r["pName"].ToString(), cNodes);
            playerTreeView.Nodes.Add(node);
            //playerTreeView.Nodes
        }
    }
2
Can you show us what you have tried? - Alexei - check Codidact
And the SSN column? - Steve
SSN column is primary key, not showing in TreeView data. - Francesco

2 Answers

0
votes

The loop should be something like this

foreach (DataRow row in rows)
{
    TreeNode node = playerTreeView.Nodes.Add(row.Field<string>("SSN"), row.Field<string>("Name"));
    node.Nodes.Add(row.Field<int>("Age").ToString());
    node.Nodes.Add(row.Field<string>("Country"));
    ....
}
0
votes

Use .Nodes.Add() to create subnodes of your name-Node:

private void FillDataInTree( DataRowCollection rows )
{
    foreach( DataRow r in rows )
    {
        TreeNode node = new TreeNode( r["pName"].ToString() );
        playerTreeView.Nodes.Add( node );

        for( int i = 0; i < 3; i++ )
            node.Nodes.Add( r[i + 1].ToString() );
    }
}

And I agree with @Steve that retrieving fields by name was better than by index.