Populate TreeView from ListView

B

Beginner

Hi,

I'm trying to populate a TreeView from an existing and filled in
ListView (lvwBuild). lvwBuild is a basic two column listview which can
have any number of rows. I would like the first column of lvwBuild to
be a node and the second column to be a branch on the TreeView
(hopefully I have the syntax correct). I've been researching how to
do this but have come up empty. I'm guessing that you would fill an
array from lvwBuild and use it to populate the TreeView. However, I
have no idea how to do this in C#. Any help would be greatly
appreciated.

Thanks in advance,

Dan
 
D

David

Is this a Windows or Web application? Can you construct the TreeView first
and then set Text properties from ListView data?
 
B

Beginner

Sorry.. it is a Windows application.

Let me give a little more information... I want to fill the ListView
out first (which I have managed to do) and then click a button which
iterates through the listview and fills out the TreeView.

Thanks!

Dan
 
D

David

Is the problem with not knowing how to programmatically retrieve data from
the ListView, construct the TreeView and populate it? Nodes of the TreeView
are added using the Add method of the Nodes object.
 
B

Beginner

The problem is not knowing how to collect all the items from the
listview and transfer them to the treeview. I think I would use an
array.. but I'm not sure how to do it... or if that is the best way.

Thanks!

Dan
 
A

Anthony Brown

I think this may do what you need (the list view is lvwBuild, the
treeview is tbView):

Hashtable nodes = new Hashtable();

foreach (ListViewItem item in lvwBuild.Items)
{
string nodeName = item.Text;
string childName = "";
TreeNode newNode;

if (nodes[nodeName] == null)
{
newNode = new TreeNode(nodeName);
nodes[nodeName] = newNode;
tvView.Nodes.Add(newNode);
}
else
{
newNode = (TreeNode) nodes[nodeName];
}

if (item.SubItems.Count > 1)
{
childName = item.SubItems[1].Text;
TreeNode childNode = new TreeNode(childName);

if (nodes[childName] == null)
{
nodes[childName] = childNode;
newNode.Nodes.Add(childNode);
}
}

it's a long way from perfect but should give you an idea of what to do.
It's important that nodes in your listview are in the correct order, the
above code will assume that any node is hasn't seen before will be a top
level node of the treeview (tvView)

It uses a hashtable to record which tree node the listview nodes were
added to, this is the easiest way (pre .net 2.0 which has a findnode
method) to find a node, the alternative is to recurse through the whole
tree)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top