【发布时间】:2021-04-05 15:49:59
【问题描述】:
我有这个错误,我不确定是什么原因造成的:
已添加具有相同键的元素
我在树形视图中显示数据如下:DEPARTMENT / PROVINCE / DISTRICT 用 Visual Basic 制作的附件代码:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim conexaoSQLServer As SqlConnection = Nothing
Dim cmd As SqlCommand
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Dim strCon As String = "Data Source = SOPORTE-ERP\SQLEXPRESS; Initial Catalog = prueba; 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 PROVINCIAS UNION 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 nodes2 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 nodeText2 As String = row.Field(Of String)("nodeText")
Dim nodeKey2 As String = row.Field(Of String)("nodeKey")
Dim nodeParentKey2 As String = row.Field(Of String)("nodeParentKey")
nodes2.Add(nodeKey2, New TreeNode(nodeText2))
If Not String.IsNullOrEmpty(nodeParentKey2) Then
nodeParents.Add(nodeKey2, nodeParentKey2)
End If
Next
'Add nodes to treeview (and resolve parents)
For Each kvp In nodes2
Dim node1 As TreeNode = kvp.Value
Dim nodeKeys1 As String = kvp.Key
Dim nodeParentKeys1 As String = Nothing
If nodeParents.TryGetValue(nodeKeys1, nodeParentKeys1) Then
'Child node
Dim parentNode As TreeNode = nodes2(nodeParentKeys1)
parentNode.Nodes.Add(node1)
Else
'Root node
TreeView1.Nodes.Add(node1)
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
我验证了每个表的 ID 字段都是唯一的并且是自动递增的。这似乎是字典的错误。我做错了什么?
【问题讨论】:
-
调用
.Close()、.Dispose()并设置为Nothing是从 vb6/vbscript 时代遗留下来的,不再需要或没有帮助,并且在极少数情况下可能会产生积极的危害..Dispose()对 VB.Net 来说就足够了 -
假设您已经单步执行了代码并查看了断点或错误处的错误值,那么有问题的值是什么?错误发生在哪一行?
nodes2.Add(nodeKey2, New TreeNode(nodeText2))?parentNode.Nodes.Add(node1)?请提供更详细的信息。