父節點 Key = PO 號,子節點 Key = 產品號。TreeView 同層節點 Key 唯一,父子關係通過 Parent 屬性自動維護,無需拼接複合 Key。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt As New DataTable
dt.Columns.Add("PO_NO", GetType(String))
dt.Columns.Add("PRODUCT", GetType(String))
' 模擬數據
dt.Rows.Add("PO150601", "鉛筆")
dt.Rows.Add("PO150601", "橡皮擦")
dt.Rows.Add("PO150602", "筆記本")
dt.Rows.Add("PO150603", "") ' 空產品號
Dim ndPO As TreeNode = Nothing
For Each dr As DataRow In dt.Rows
Dim poNo = dr("PO_NO").ToString()
Dim prod = dr("PRODUCT").ToString()
' 新 PO 號創建父節點
If ndPO Is Nothing OrElse ndPO.Name <> poNo Then
ndPO = TreeView1.Nodes.Add(poNo, poNo.Substring(2)) ' Key=PO_NO, Text=後綴
End If
' 產品號非空添加子節點
If Not String.IsNullOrEmpty(prod) Then
ndPO.Nodes.Add(prod, prod) ' Key=PRODUCT, Text=PRODUCT
End If
Next
End Sub
| 屬性 | 用途 |
|---|---|
TreeNode.Name | 節點唯一 Key,同層不可重複,Nodes.Find(key, true) 可跨層查找 |
TreeNode.Text | 顯示文本 |
TreeNode.Parent | 父節點引用,無需通過 Key 查找 |
TreeNode.Nodes | 子節點集合,直接增刪改查 |
Dim parent = childNode.ParentTreeView1.ExpandAll()TreeView1_AfterSelect 中 e.Node 即當前節點。