2016-10-20 37 views
-1

我想用DataGridView中的數據填充TreeView,但我不能。從c中的DataGridView填充TreeView與數據#

DataGridView的是以下信息:

Table

TreeView控件必須象下面這樣:

enter image description here]

OBS:我創建了一個TreeView手動試圖解釋我是如何希望它是。

我試着這樣做:

public void CarregaTreeView() { 
     string pai = ""; 
     string filho = ""; 
     string noPrincipal = ""; 

     Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>(); 

     noPrincipal = dgv.Rows[0].Cells["COD_PAI"].Value.ToString(); 

     foreach (DataGridViewRow row in dgv.Rows) { 
      pai = (string)row.Cells[0].Value; 
      filho = (string)row.Cells[3].Value; 

      if (dict.ContainsKey(pai)) { 
       dict[pai].Add(filho); 
      } 
      else { 
       dict.Add(pai, new List<string>()); 
       dict[pai].Add(filho); 
      } 

     } 
     //adicionar nó principal 
     TreeNode objTopNode = new TreeNode(noPrincipal + " - DESCRICAO - [QTDE]"); 
     tv.Nodes.Add(objTopNode); 
     objTopNode.Tag = noPrincipal; 

     MontaTreeView(dict, objTopNode); 
    } 

    private void MontaTreeView(Dictionary<string, List<string>> dict, TreeNode objparentNode) { 

     foreach (var kvp in dict) { 

      objcurrentNode = new TreeNode(kvp.Key + " - DESCRICAO - [QTDE]"); 
      objparentNode.Nodes.Add(objcurrentNode); 
      objcurrentNode.Tag = kvp.Key; 
      objcurrentNode.Expand(); 

      if (kvp.Key.Contains("T")) { 
       Dictionary<string, List<string>> dict1 = new Dictionary<string, List<string>>(); 
       dict1.Add(kvp.Key, new List<string>()); 
       dict1[kvp.Key].Add(dict[kvp.Key][0]); 
       MontaTreeView(dict1, objcurrentNode); 
      } 
     } 

    } 
+1

這是贏的形式嗎? –

+0

@Marcelo對不起,但在目前的形式中,這個問題很難回答。您是否可以移除不相關代碼的額外部分,將您的數據顯示爲文本,而不是圖像,並向我們展示您從代碼輸出的結果,以及哪些部分在那裏不起作用? – trailmax

+0

@Marcelo很多時候,當你試圖簡化問題時,你自己實際得到你的答案。所以這是值得的 – trailmax

回答

0

基本上,你需要遍歷網格視圖。對於每一行,在樹中找到其父節點,然後將該行添加到節點子節點。

TreeNode findParent(string txt, TreeNode parent = null) 
{ 
    if (parent == null) 
    parent = treeView1.Nodes[0]; 
    if (parent.Text == txt) return parent; 
    foreach (TreeNode node in parent.Children) 
    { 
     var res = findParent(txt, node); //recursion 
     if (res != null) return res; 
    } 
    return null; 
} 

foreach (DataGridViewRow row in dataGrid.Rows) 
{ 
    TreeNode parent = findParent(row.Cells[2].Value as string); 
    var newNode = new TreeNode() { Text = row.Cells[0].Value as Text }; 
    if (parent != null) 
     parent.Children.Add(newNode); 
    else 
     treeView1.Nodes.Add(newNode); 
} 
+0

感謝您的回答,Kilanny! – Marcelo

+0

@Marcelo很高興幫助。如果解決了您的問題,請將答案標記爲您的「最佳」答案。謝謝! –