将所选数据从树视图传递到 vb.net 中的文本框

Pass selected data from a treeview to a textbox in vb.net

我有一个 treeview 显示 SQL 服务器中 1 table 的记录,到目前为止一切都很好地附加树,

我为显示从 sql 到 TREEVIEW 的数据而执行的查询如下:

Dim sqlConsulta As String = "SELECT DESCRIPCION AS nodeText,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeKey,'' AS nodeParentKey " +
"FROM DEPARTAMENTO UNION ALL SELECT DESCRIPCION AS nodeText,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeKey,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeParentKey " +
"FROM PROVINCIA UNION ALL SELECT DESCRIPCION AS nodeText,'DIST' + CAST(IDUBIGEO AS VARCHAR) AS nodeKey,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeParentKey FROM ubigeo "

我在 TreeView1_AfterSelect 事件中有以下代码,它只显示我从最后一个节点 select 而不是其他节点的内容,反过来我想带来地区 ID

Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
    'obtem o item selecionado
    Dim itemSelecionado As String = TreeView1.SelectedNode.ToString
    'remove a string TreeNode
    itemSelecionado = itemSelecionado.Replace("TreeNode: ", "")

    'verifica se o item é nulo
    If (e.Node.Parent IsNot Nothing) Then
        'verifica o tipo do no
        If (e.Node.Parent.GetType() Is GetType(TreeNode)) Then
            If e.Node.Parent.Text = nomeArquivo Then
                'mostra o nome da tabela e da coluna selecionada
                txtdistrito.Text = (e.Node.Parent.Text + "." + itemSelecionado)
            Else
                'mostra so o nome da tabela
                txtdistrito.Text = (itemSelecionado)
            End If
        End If
    End If
End Sub

用于填写树视图的代码

 Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim conexaoSQLServer As SqlConnection = Nothing
        Dim cmd As SqlCommand
        Dim da As New SqlDataAdapter
        Dim ds As New DataSet
        DBSQLServer = "prueba"

        Dim strCon As String = "Data Source = DESKTOP-2IM88ST\SQLEXPRESS; Initial Catalog = " & DBSQLServer & "; Integrated Security = True"

        'define a consulta para obter as tabelas e suas colunas
        Dim sqlConsulta As String = "SELECT DESCRIPCION AS nodeText,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeKey,'' AS nodeParentKey " +
"FROM DEPARTAMENTO UNION ALL SELECT DESCRIPCION AS nodeText,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeKey,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeParentKey " +
"FROM PROVINCIA UNION ALL SELECT DESCRIPCION AS nodeText,'DIST' + CAST(IDUBIGEO AS VARCHAR) AS nodeKey,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeParentKey FROM ubigeo "


        Try
            'define e abre a conexão com o SQL Server
            conexaoSQLServer = New SqlConnection(strCon)
            conexaoSQLServer.Open()

            'atribui o comando usado na conexão
            cmd = New SqlCommand(sqlConsulta, conexaoSQLServer)
            da.SelectCommand = cmd

            'preenche o dataset
            da.Fill(ds, "DATOS_SISTEMAS")

            'Helper dictionaries
            Dim nodes As New Dictionary(Of String, TreeNode) 'Holds the nodes based on their key values
            Dim nodeParents As New Dictionary(Of String, String) 'Holds the parent keys of child nodes

            'Create nodes from data
            For Each row As DataRow In ds.Tables("DATOS_SISTEMAS").Rows
                Dim nodeText As String = row.Field(Of String)("nodeText") 
                Dim nodeKey As String = row.Field(Of String)("nodeKey")
                Dim nodeParentKey As String = row.Field(Of String)("nodeParentKey")

                nodes.Add(nodeKey, New TreeNode(nodeText))

                If Not String.IsNullOrEmpty(nodeParentKey) Then
                    nodeParents.Add(nodeKey, nodeParentKey)
                End If
            Next

            'Add nodes to treeview (and resolve parents)
            For Each kvp In nodes
                Dim node As TreeNode = kvp.Value
                Dim nodeKeys As String = kvp.Key
                Dim nodeParentKeys As String = Nothing

                If nodeParents.TryGetValue(nodeKeys, nodeParentKeys) Then
                    'Child node
                    Dim parentNode As TreeNode = nodes(nodeParentKeys)
                    parentNode.Nodes.Add(node)
                Else
                    'Root node
                    TreeView1.Nodes.Add(node)

                End If
            Next
        Catch ex As Exception
            MessageBox.Show("error when performing this operation:  " & ex.Message)
            Exit Sub
        Finally
            'libera os recursos da conexão usada
            conexaoSQLServer.Close()
            conexaoSQLServer.Dispose()
            conexaoSQLServer = Nothing
        End Try

    End Sub

当你创建每个 TreeNode 时,将 nodeKey 存储在 TreeNode.Tag 属性

Dim node as New TreeNode(data.nodeText) With { .Tag = data.nodeKey }

然后在您的 AfterSelect 处理程序中,您可能会做这样的事情

tDepartment.Text = String.Empty
tProvince.Text = String.Empty
tUbigeo.Text = String.Empty
tDistrictCode.Text = String.Empty

Dim nodeKey As String = DirectCast(e.Node.Tag, String);

If nodeKey.StartsWith("DEP") Then
    tDepartment.Text = e.Node.Text
End If
If nodeKey.StartsWith("PRO") Then            
    tProvince.Text = e.Node.Text
    tDepartment.Text = e.Node.Parent.Text
End If
If nodeKey.StartsWith("DIS") Then            
    tUbigeo.Text = e.Node.Text;
    tDistrictCode.Text = nodeKey;
    tProvince.Text = e.Node.Parent.Text;
    tDepartment.Text = e.Node.Parent.Parent.Text;
End If

首先,我建议您在树视图填充期间使用相应的 nodeKey 值设置节点的 Tag 属性。

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  Dim conexaoSQLServer As SqlConnection = Nothing
  Dim cmd As SqlCommand
  Dim da As New SqlDataAdapter
  Dim ds As New DataSet
  DBSQLServer = "prueba"

  Dim strCon As String = "Data Source = DESKTOP-2IM88ST\SQLEXPRESS; Initial Catalog = " & DBSQLServer & "; Integrated Security = True"

  'define a consulta para obter as tabelas e suas colunas
  Dim sqlConsulta As String = "SELECT DESCRIPCION AS nodeText,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeKey,'' AS nodeParentKey " +
"FROM DEPARTAMENTO UNION ALL SELECT DESCRIPCION AS nodeText,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeKey,'DEPA' + CAST(IDDEPARTAMENTO AS VARCHAR) AS nodeParentKey " +
"FROM PROVINCIA UNION ALL SELECT DESCRIPCION AS nodeText,'DIST' + CAST(IDUBIGEO AS VARCHAR) AS nodeKey,'PROV' + CAST(IDPROVINCIA AS VARCHAR) AS nodeParentKey FROM ubigeo "


  Try
    'define e abre a conexão com o SQL Server
    conexaoSQLServer = New SqlConnection(strCon)
    conexaoSQLServer.Open()

    'atribui o comando usado na conexão
    cmd = New SqlCommand(sqlConsulta, conexaoSQLServer)
    da.SelectCommand = cmd

    'preenche o dataset
    da.Fill(ds, "DATOS_SISTEMAS")

    'Helper dictionaries
    Dim nodes As New Dictionary(Of String, TreeNode) 'Holds the nodes based on their key values
    Dim nodeParents As New Dictionary(Of String, String) 'Holds the parent keys of child nodes

    'Create nodes from data
    For Each row As DataRow In ds.Tables("DATOS_SISTEMAS").Rows
      Dim nodeText As String = row.Field(Of String)("nodeText")
      Dim nodeKey As String = row.Field(Of String)("nodeKey")
      Dim nodeParentKey As String = row.Field(Of String)("nodeParentKey")

      ''UPDATED CODE START
      Dim node As New TreeNode(nodeText)
      node.Tag = nodeKey
      nodes.Add(nodeKey, node)
      ''UPDATED CODE END

      If Not String.IsNullOrEmpty(nodeParentKey) Then
        nodeParents.Add(nodeKey, nodeParentKey)
      End If
    Next

    'Add nodes to treeview (and resolve parents)
    For Each kvp In nodes
      Dim node As TreeNode = kvp.Value
      Dim nodeKeys As String = kvp.Key
      Dim nodeParentKeys As String = Nothing

      If nodeParents.TryGetValue(nodeKeys, nodeParentKeys) Then
        'Child node
        Dim parentNode As TreeNode = nodes(nodeParentKeys)
        parentNode.Nodes.Add(node)
      Else
        'Root node
        TreeView1.Nodes.Add(node)

      End If
    Next
  Catch ex As Exception
    MessageBox.Show("error when performing this operation:  " & ex.Message)
    Exit Sub
  Finally
    'libera os recursos da conexão usada
    conexaoSQLServer.Close()
    conexaoSQLServer.Dispose()
    conexaoSQLServer = Nothing
  End Try

End Sub

接下来,在您的 AfterSelect 活动中,我会坚持使用 TreeView1.SelectedNodee.Node。我猜它们应该都代表同一个节点。但在我看来,访问 e.Node 有点“干净”。

你没有提供所有四个文本框的名称,所以我编的。您可能需要更新代码,以便它使用正确的文本框名称。

Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
  Dim node As TreeNode = e.Node 'TreeView1.SelectedNode
  Dim nodeKey As String = TryCast(node.Tag, String)

  'A nodeKey value of a district node will look like "DIST123" if the corresponding IDUBIGEO value is 123.
  'So it should be checked if the nodeKey value starts with "DIST".

  If (nodeKey IsNot Nothing AndAlso nodeKey.StartsWith("DIST")) Then
    'It's a district node.
    'So it is also known that its parent node is its province node and its parent's parent node is its department node.

    txtdistrito.Text = node.Text
    txtprovincia.Text = node.Parent.Text
    txtdepartamento.Text = node.Parent.Parent.Text

    'The district code (the IDUBIGEO value) is also available in the nodeKey value after the first four characters ("DIST").

    txtdistritocode.Text = nodeKey.Substring(4) 'Index positions 0-3 contain "DIST", index positions 4 and higher contain the district code (the IDUBIGEO value).
  End If
End Sub

不使用节点的 Tag 属性 也可以使其工作,但是 AfterSelect 事件中的检查以查看您是否实际单击了地区节点将是在那种情况下有点困难。此外,您需要一个单独的 SQL 查询(或另一个 storage/caching 机制)来查找匹配的 IDUBIGEO 值,因为它不会存储 in/with 在树视图填充期间选定的节点.