开发者

Load data to treeview asp.net

If I have this [Terminal] table:

ID bigint
Description varchar(20)
TerminalLevel smallint //1 = Terminal, 2 = Sub Terminal, 3 = Sub-sub-Terminal
TerminalID             //0 = Main Terminal itself, else belong to parent terminal

For example, I have:

ID           Description           TerminalLevel         TerminalID
1            Terminal 1            1                     0
2            Terminal 1-1          2                     1
3            Terminal 1-1-1        3                     2
4            Terminal 2            1                     0
5            Terminal 2-1          1                     4

I expect to load the data to the tree like this:

Terminal 1
  |---> Terminal 1-1
           |---> Terminal 1-1-1
Terminal 2
  |--->开发者_JAVA百科; Terminal 2-1

Would it be possible to select only one query and load to a treeview in asp.net?


Get you query in a sqldatareader DReader but order by TerminalID to avoid child to be added before parent and use the following functions

SqlDataReader DReader = load from databse order by TerminalID ...
TreeNode nodeNew;
    if (DReader.HasRows)
    while (DReader.Read())
        {
            nodeNew = new TreeNode(DReader["Description"].ToString(), DReader["ID"].ToString());
            if(DReader["TerminalID"].ToString() == "0")
                 treeview.Nodes.Add(nodeNew);
            else
             treeview.FindNode(DReader["TerminalLevel"].ToString().Replace("-","/")).ChildNodes.Add(nodeNew);

        }

UPDATE

if you are using sqldatareader you only need to order by terminalid and with advance of terminallevel you can use my solution, if you are using datatable or store data in a collection, you can use the solution of two functions to bind treeview one have parentNode of tree ...

but here you have terminal level so you can search in node by path

My Regards


Well, you can just select * from Terminal and then build the tree out of that. Or you could do a recursive query and spit out the results as xml. But sql result sets do not have the notion of hierarchy.


Here's the pseudo code for what you can try

mainTerminals = select Terminals where TerminalId=0
  foreach (terminal in mainTerminals)
     Create treeNode and initialize with terminal details
     Add treeNode to Tree
     call AddChildTerminals(terminal, treeNode) 
  end foreach


function AddChildTerminals(terminal, parentTreenode)
   childTerminals = select terminals where TerminalId=terminal.ID
   foreach (childTerminal in childTerminals )
     Create treeNode and initialize with childTerminal  details
     Add treeNode to parentTreenode
     call AddChildTerminals(childTerminal, treeNode) 
   end foreach

The two loops look very similar. If you possibly refactor so it's just one loop but I'll leave that out for now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜