2017-09-07 65 views
0

您好有一個數據表與3個領域,我的預期樹視圖將喜歡這下面的圖像。從DataTable的Treeview

Expected Result

我的數據表返回這樣的細節。

Data table result

,我嘗試下面的代碼。這裏的子節點沒有得到妥善上市

public void BuildTree(DataTable dt, TreeView trv, Boolean expandAll) 
    { 
     trv.Nodes.Clear(); 
     TreeNode node = default(TreeNode); 
     TreeNode subNode = default(TreeNode); 
     foreach (DataRow row in dt.Rows) 
     { 
      node = Searchnode(row[0].ToString(), trv); 
      if (node != null) 
      { 
       subNode = new TreeNode(row[1].ToString()); 
       node.Nodes.Add(subNode); 
      } 
      else 
      { 
       node = new TreeNode(row[0].ToString()); 
       subNode = new TreeNode(row[1].ToString()); 
       node.Nodes.Add(subNode); 
       trv.Nodes.Add(node); 
      } 
     } 
     if (expandAll) 
     { 
      trv.ExpandAll(); 
     } 
    } 
    private TreeNode Searchnode(string nodetext, TreeView trv) 
    { 
     foreach (TreeNode node in trv.Nodes) 
     { 
      if (node.Text == nodetext) 
      { 
       return node; 
      } 
     } 
     return null; 
    } 
+0

'這裏的子節點沒有正確上市'你有什麼想要的? **要做的代碼?它實際上**做了什麼? – mjwills

+0

我想基於我擁有的數據表填充樹形視圖。但我不能加第二個孩子 – Jzl

回答

1

我suposing該數據表上previosly由客戶名稱,DeliverySchedule,名稱下令

初始化的測試數據:從數據表中使用

private void InitializeDataTable() { 
     dt = new DataTable(); 
     dt.Columns.Add("DeliverySchedule"); 
     dt.Columns.Add("Name"); 
     dt.Columns.Add("CustomerName"); 

     AddRow("Daily", "Test", "Team Venkat"); 
     AddRow("Daily", "TestB", "Team Venkat"); 
     AddRow("Weekly", "OtherName", "Team Venkat"); 
     AddRow("Weekly", "OtherName2", "Team Venkat"); 
     AddRow("Daily", "Test", "Team2"); 
     AddRow("Weekly", "Test", "Team2"); 

    } 

    private void AddRow(string schedule, string name, string customer) { 
     DataRow row = dt.NewRow(); 
     row[0] = schedule; 
     row[1] = name; 
     row[2] = customer; 
     dt.Rows.Add(row); 
    } 

負荷樹三級迴路:

private void LoadBtn_Click(object sender, EventArgs e) { 
     int i = 0; 
     treeView1.Nodes.Clear(); 
     while (i < dt.Rows.Count) { 
      DataRow row = dt.Rows[i]; 
      string customer = row.Field<string>(2); 
      TreeNode customerNode = treeView1.Nodes.Add(customer); 
      while (i < dt.Rows.Count && row.Field<string>(2) == customer) { 
       string schedule = row.Field<string>(0); 
       TreeNode scheduleNode = customerNode.Nodes.Add(schedule); 
       while (i < dt.Rows.Count && row.Field<string>(2) == customer && schedule == row.Field<string>(0)) { 

        string report = row.Field<string>(1); 
        scheduleNode.Nodes.Add(report); 
        if (++i < dt.Rows.Count) 
         row = dt.Rows[i]; 
       } 
      } 
     } 
    } 
+0

很好的答案,工作很酷 – Jzl