Francesco
Francesco

Reputation: 121

Populate TreeView with DataRow

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
        }
    }

Upvotes: 0

Views: 1323

Answers (2)

Kai Thoma
Kai Thoma

Reputation: 572

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.

Upvotes: 0

Steve
Steve

Reputation: 216313

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"));
    ....
}

Upvotes: 0

Related Questions