Qusyaire Ezwan
Qusyaire Ezwan

Reputation: 279

Get the data from treeview in C#

Explanation:

Coding :

       for (int i = 0; i < d.Count; i++) //loop for Product
            {
                TreeNode node = new TreeNode(((string[])d[i])[0]);
                thisForm.NewBKMTreeView.Nodes.Add(node); //add Product as Parent Node

                for (int j = 0; j < b.Count; j++) //loop for Item
                {
                    if (((string[])d[i])[1] == ((string[])b[j])[0]) //compare if ProductID from arrayList d same with ProductID from arrayList b
                    {
                        node.Nodes.Add(((string[])b[j])[2]); //add Item as Child Node
                    }
                }
            }

from the code above.

d is arraylist that hold 2 string.

string[0]       string[1]
ProductName     ProductID
-----------    -----------
  Food             001
  NotFood          002

b also arraylist that hold 3 string

string[0]      string[1]      string[2]
ProductID      itemID          itemName
  001            X101            Soup
  001            X102            Bread
  002            G111            Pen
  002            G212            Book
  002            G222            Ruler

Code to add ProductName as Parent Node :

TreeNode node = new TreeNode(((string[])d[i])[0]);

(((string[])d[i])[0]) hold the ProductName

Code to add itemName as Child Node :

node.Nodes.Add(((string[])b[j])[2]);

(((string[])b[j])[2]) hold the itemName

After run the coding above. the object in arrayList will show in Treeview

+Food
 - Soup
 - Bread
+NotFood
 - Pen
 - Book
 - Ruler

Question :

the treeview is Treeview with Checkboxes. So user can check the item that he want. And copy the item another place. I've some problems here. How can i get itemID when user check at nodes?

I want the itemID for get the item that user check to get the data from database and copy it into another place refering to itemID.

Upvotes: 0

Views: 2271

Answers (2)

Michael Schnerring
Michael Schnerring

Reputation: 3661

You should convert your DB data into objects:

public class MyNode
{
    public MyNode Parent { get; set; }
    public ObservableCollection<MyNode> Children { get; set; }
    public string ItemId { get; set; }
    // ...
}

If you want to change the parent, just assign and new parent to the chilrends parent property. Update the childrens list of the parent and the new parent.

Upvotes: 0

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

I think you should store the item id or any other information you require from the item in the tag property of tree node.

Upvotes: 1

Related Questions