2011-07-19 46 views
6

我有像下面的SQL表。我必須表明它在樹視圖從sql表樹視圖

id parentid  name 
1  NULL  outlook 
2  1  overcast 
3  1  rainy 
4  1  sunny 
5  2  yes 
6  3  wind 
7  4  humidity 
8  6  strong 
9  6  weak 
10 7  high 
11 8   no 
12 9   yes 
13 10   no 
14 15   yes 
15 7  normal 

我想輸出

-Outlook

- overcast 

     - yes 

- rainy 
    - wind 
     - strong 
       - no 
     - weak 
       - yes 
-sunny 
    - humidity 

     -high 
       -no 
     -normal 
       -yes 

只有一個根節點「展望」 here.then來自子節點和子像這樣的子節點。

+0

樹視圖的目的是當用戶展開父節點時僅顯示子節點**。換句話說,你應該簡單地加載父代擴展後的直接子代。試圖在啓動時加載所有樹是一個糟糕的設計理念。這張桌子很小,所以這裏不是一個大問題,但想象它是巨大的。爲什麼你會強迫你的用戶等待整個樹加載? –

+0

@Jose Rui Santos先生,我是asp.net的初學者,當它被選中時我們可以進行節點擴展....但我不知道該怎麼做... – dhanya

+0

@Dhany;請將此行更改爲此ds.Relations.Add(「Children」,dtbl1.Columns [「Id」],dtbl1.Columns [「ParentId」]); –

回答

2
WITH q AS 
     (
     SELECT * 
     FROM mytable 
     WHERE ParentID IS NULL -- this condition defines the ultimate ancestors in your chain, change it as appropriate 
     UNION ALL 
     SELECT m.* 
     FROM mytable m 
     JOIN q 
     ON  m.parentID = q.ID 
     ) 
SELECT * 
FROM q 
0

試試下面的代碼在你的ASPX或ASCX文件:

<asp:Treeview ID="TreeView1" runat="server" /> 

而在隱藏代碼來填充它:

private void PopulateTreeView() 
{ 
    DataSet ds = new DataSet(); //(populate the dataset with the table) 

    //Use LINQ to filter out items without a parent 
    DataTable parents = ds.Tables[0].AsEnumerable() 
     .Where(i => i.Field<object>("parentid") == DBNull.Value) 
     .CopyToDataTable(); 

    //Use LINQ to filter out items with parent 
    DataTable children = ds.Tables[0].AsEnumerable() 
     .Where(i => i.Field<object>("parentid") != DBNull.Value) 
     .OrderBy(i => i.Field<int>("parentid")) 
     .CopyToDataTable(); 

    //Add the parents to the treeview 
    foreach(DataRow dr in parents) 
    { 
     TreeNode node = new TreeNode(); 
     node.Text = dr["name"].ToString(); 
     node.Value = dr["id"].ToString(); 
     TreeView1.Nodes.Add(node); 
    } 

    //Add the children to the parents 
    foreach(DataRow dr in children) 
    { 
     TreeNode node = new TreeNode(); 
     node.Text = dr["name"].ToString(); 
     node.Value = dr["id"].ToString(); 
     TreeNode parentNode = FindNodeByValue(dr["parentid"].ToString()); 
     if(parentNode != null) 
      parentNode.ChildNodes.Add(node); 
    } 
} 

private TreeNode FindNodeByValue(string value) 
{ 
    foreach(TreeNode node in TreeView1.Nodes) 
    { 
     if(node.Value = value) return node; 
     TreeNode pnode = FindNodeRecursion(node, value); 
     if(pnode != null) return pnode; 
    } 
    return null; 
} 

private TreeNode FindNodeRecursion(TreeNode parentNode, string value) 
{ 
    foreach(TreeNode node in parentNode.ChildNodes) 
    { 
     if(node.Value = value) return node; 
     TreeNode pnode = FindNodeRecursion(node, value); 
     if(pnode != null) return pnode; 
    } 
    return null; 
} 

有可能是一個更好的辦法來做到這一點,我沒有測試它,但它應該工作。或者你總是可以嘗試使用Telerik或另一個第三方工具,使這些類型的控件的數據綁定變得非常容易。