每当我在现有的TreeView中添加一个新节点时,我的代码似乎就无法检测到它的名称。请有人解释。
所有其他数据在加载表单之前都是通过TreeView设计进行编码的。
请参阅屏幕截图以供参考。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim newNode As TreeNode = New TreeNode(TextBox1.Text)
TreeView1.SelectedNode.Nodes.Add(newNode)
transfer_dgv1()
End Sub
Private Sub transfer_dgv1()
Dim TreeViewRW As New TreeViewrw
TreeView1.Refresh()
Me.DataGridView1.DataSource = TreeViewRW.ToTable(Me.TreeView1)
End Sub
这是我使用的功能:
Public Class TreeViewrw
Public Function ToTable(ByVal tv As TreeView) As DataTable
Dim dt As New DataTable("TreeNodes")
Dim id As Integer = 1
dt.Columns.Add("ParentID", GetType(Integer))
dt.Columns.Add("NodeID", GetType(Integer))
dt.Columns.Add("Name", GetType(String))
For Each pn As TreeNode In tv.Nodes
dt.Rows.Add(0, id, pn.Name)
Me.GetAllNodes(dt, pn, id, id)
id += 1
Next
Return dt
End Function
Public Function FromTable(ByVal dt As DataTable, ByVal parent As String, ByVal node As String, ByVal name As String) As TreeNode()
Dim tnodes As New List(Of TreeNode)()
Dim columns As String() = New String(2) {parent, node, name}
If dt.Columns.Contains(parent) AndAlso dt.Columns.Contains(node) AndAlso dt.Columns.Contains(name) Then
dt.DefaultView.RowFilter = "[" & parent & "] = 0"
For Each r As DataRowView In dt.DefaultView
tnodes.Add(Me.ReadNodes(columns, r, dt))
Next
Return tnodes.ToArray()
Else
Return tnodes.ToArray()
End If
End Function
Private Function ReadNodes(ByVal columns As String(), ByVal r As DataRowView, ByVal dt As DataTable) As TreeNode
Dim cn As New TreeNode()
cn.Name = r(columns(2)).ToString()
cn.Text = cn.Name
Me.GetAllNodes(columns, cn, dt, CInt(r(columns(1))))
Return cn
End Function
Private Sub GetAllNodes(ByRef dt As DataTable, ByVal pn As TreeNode, ByVal parentid As Integer, ByRef id As Integer)
For Each cn As TreeNode In pn.Nodes
id += 1
dt.Rows.Add(parentid, id, cn.Name)
Me.GetAllNodes(dt, cn, id, id)
Next
End Sub
Private Sub GetAllNodes(ByVal columns As String(), ByRef pn As TreeNode, ByVal dt As DataTable, ByVal nodeid As Integer)
dt.DefaultView.RowFilter = ("[" & columns(0).ToString() & "] = ") + nodeid.ToString()
For Each r As DataRowView In dt.DefaultView
Dim cn As New TreeNode()
cn.Name = r(columns(2)).ToString()
cn.Text = cn.Name
pn.Nodes.Add(cn)
Me.GetAllNodes(columns, cn, dt, CInt(r(columns(1))))
Next
End Sub
End Class
答案 0 :(得分:0)
我似乎您没有设置Name属性。
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim newNode As TreeNode = New TreeNode(TextBox1.Text)
newNode.Name = TextBox1.Text
TreeView1.SelectedNode.Nodes.Add(newNode)
transfer_dgv1()
End Sub