0

How can I fetch data from the database into treeveiw and display it tree-like in the way of father and son I tried the code below and got an inaccurate result 100%

    id     name        parent_id
--------------------------------------
    1      Banks        0
    2      Cars         0
    11     Bank1        1
    12     Bank2        1
    111    Acoount1     11
    112    Account2     11
    113    Account3     11
    21     Car1         2
    22     Car2         2
    23     Car3         2

I hope the data be like this

-Banks
   -Bank1
      -Account1
      -Account2
      -Account3
   -Bank2
-Cars
   -Car1
   -Car2
   -Car3

I get data from database by stored procedure to DataTable this is the code

ALTER PROC [dbo].[GET_ALL_ACCOUNTS]

AS


SELECT * FROM ACCOUNTS

I want to use the data from datatable

DataTable dt = new DataTable();
dt = account.GET_ALL_ACCOUNTS();
foreach (DataRow dr in dt.Rows)
{

   TreeNode node = new TreeNode(dr["id"].ToString());

   node.Nodes.Add(dr["name"].ToString());
   node.Nodes.Add(dr["parent_id"].ToString());

   treeView1.Nodes.Add(node);

}

I hope someone can help me

1 Answers1

0

Your foreach doesn't have any tree-related logic. You have to construct a valid Tree based on the id and parent_id returned from the DataTable. Have a look at this logic for instance and modify it to serve your needs.

yazanpro
  • 4,512
  • 6
  • 44
  • 66