Suggerimento di sistemaIl presente articolo fa riferimento a un sistema operativo diverso da quello in uso. Il contenuto dell'articolo che potrebbe non essere relativo al sistema in uso è disabilitato.
Per la versione di questo articolo relativa a
Microsoft Access 97, vedere
165993
(http://support.microsoft.com/kb/165993/
)
.
Utenti esperti: sono richieste conoscenze avanzate di gestione di
codice, interoperabilità e funzioni multiutente.
In questo articolo viene spiegato come utilizzare la
funzionalità di trascinamento della selezione del controllo Microsoft TreeView
versione 6.0.
Il controllo Microsoft TreeView versione 6.0 è
disponibile con Microsoft Office 2000 Developer.
Microsoft fornisce esempi di
programmazione a scopo puramente illustrativo, senza alcuna garanzia di
qualsiasi tipo, sia espressa che implicita, ivi incluse, senza limitazioni, le
garanzie implicite di commerciabilità o idoneità per uno scopo particolare. In
questo articolo si presuppone che l'utente conosca il linguaggio di
programmazione in questione e gli strumenti utilizzati per creare ed eseguire
il debug delle procedure. Gli esperti Microsoft sono autorizzati a fornire
spiegazioni in merito alla funzionalità di una particolare procedura, ma in
nessun caso a modificare questi esempi per fornire funzionalità aggiuntive o a
creare procedure atte a soddisfare specifiche esigenze.
Il controllo Microsoft TreeView versione 6.0 è
caratterizzato dalla funzionalità incorporata di trascinamento della selezione
che non era disponibile nelle versioni precedenti. Supporta eventi di
trascinamento della selezione quali OLEStartDrag, OLEDragOver, OLECompleteDrag
e OLEDragDrop.
L'esempio riportato di seguito consente di creare un
elenco gerarchico di impiegati nel database di esempio Northwind. Il controllo
TreeView consente di visualizzare gli impiegati in base alla persona a cui
fanno riferimento e permette di trascinare i nomi degli impiegati per
riordinare la gerarchia e aggiornare la tabella corrispondente.
ATTENZIONE: la procedura riportata in questo esempio comporta la modifica
del database Northwind.mdb. È consigliabile fare una copia del file
Northwind.mdb sulla quale eseguire la procedura.
Avviare Microsoft Access e aprire il database di esempio
Northwind.mdb.
In visualizzazione Struttura creare una nuova maschera che
non sia basata su alcuna tabella o query.
Scegliere Controllo ActiveX dal menu Inserisci.
Nella finestra di dialogo Inserisci controllo ActiveX selezionare l'opzione relativa al controllo Microsoft TreeView
Control versione 6.0, quindi scegliere OK.
Impostare le seguenti proprietà per il controllo TreeView:
Nome: xTree
Larghezza: 3"
Altezza: 2"
Fare doppio clic sul controllo TreeView e impostare le
seguenti proprietà personalizzate nella scheda Generale della finestra delle proprietà del controllo TreeView:
'==================================================================
'This procedure populates the TreeView control when the form opens.
'==================================================================
Private Sub Form_Load()
On Error GoTo ErrForm_Load
Dim db As Database
Dim rst As Recordset
Dim nodCurrent As Node, nodRoot As Node
Dim objTree As TreeView
Dim strText As String, bk As String
Set db = CurrentDb
'Open the Employees table.
Set rst = db.OpenRecordset("Employees", dbOpenDynaset, dbReadOnly)
'Create a reference to the TreeView Control.
Set objTree = Me!xTree.Object
'Find the first employee who is a supervisor.
rst.FindFirst "[ReportsTo] Is Null"
'Build the TreeView list of supervisors and their employees.
Do Until rst.NoMatch
'Extract the supervisor's name.
strText = rst![LastName] & (", " + rst![FirstName])
'Add a root level node to the tree for the supervisor.
Set nodCurrent = objTree.Nodes.Add(, , "a" & rst!EmployeeID, _
strText)
'Use a placeholder to save this place in the recordset.
bk = rst.Bookmark
'Run a recursive procedure to add all the child nodes
'for employees who report to this supervisor.
AddChildren nodCurrent, rst
'Return to your placeholder.
rst.Bookmark = bk
'Find the next supervisor.
rst.FindNext "[ReportsTo] Is Null"
Loop
ExitForm_Load:
Exit Sub
ErrForm_Load:
MsgBox Err.Description, vbCritical, "Form_Load"
Resume ExitForm_Load
End Sub
'===================================================================
'This procedure adds child nodes to the tree for all employees who
'report to a particular supervisor, and calls itself recursively
'to add child nodes for all other employees they supervise.
'
'Note that this procedure accepts the open Employees recordset by
'reference so you do not have to open a new recordset for each call.
'===================================================================
Sub AddChildren(nodBoss As Node, rst As Recordset)
On Error GoTo ErrAddChildren
Dim nodCurrent As Node
Dim objTree As TreeView
Dim strText As String, bk As String
'Create a reference to the TreeView control.
Set objTree = Me!xTree.Object
'Find the first employee who reports to the supervisor for this node.
rst.FindFirst "[ReportsTo] =" & Mid(nodBoss.Key, 2)
'Build the list of employees who report to this supervisor.
Do Until rst.NoMatch
'Extract the employee's name.
strText = rst![LastName] & (", " + rst![FirstName])
'Add as a child node to the tree.
Set nodCurrent = objTree.Nodes.Add(nodBoss, tvwChild, "a" & _
rst!EmployeeID, strText)
'Save your place in the recordset.
bk = rst.Bookmark
'Add any employees for whom the current node is a supervisor.
AddChildren nodCurrent, rst
'Return to your place in the recordset and continue to search.
rst.Bookmark = bk
'Find the next employee who reports to this supervisor.
rst.FindNext "[ReportsTo]=" & Mid(nodBoss.Key, 2)
Loop
ExitAddChildren:
Exit Sub
ErrAddChildren:
MsgBox "Can't add child: " & Err.Description, vbCritical, _
"AddChildren(nodBoss As Node) Error:"
Resume ExitAddChildren
End Sub
'==================================================================
'This procedure in the OLEStartDrag event of the TreeView control
'clears the selected node so you can choose a new one.
'==================================================================
Private Sub xTree_OLEStartDrag(Data As Object, AllowedEffects As _
Long)
Me!xTree.Object.SelectedItem = Nothing
End Sub
'====================================================================
'Use the OLEDragOver event of the TreeView control to select the
'node to drag, and to highlight the target nodes where the drop will
'occur when you release the mouse. This procedure sets the selected
'node to drag once. After that, if a node is already selected, the
'procedure assumes it was set during an earlier call in the dragging
'process and it does not reset it. The second half of this procedure
'highlights the node you are dragging over.
'====================================================================
Private Sub xTree_OLEDragOver(Data As Object, Effect As Long, _
Button As Integer, Shift As Integer, x As Single, y As Single, _
State As Integer)
Dim oTree As TreeView
'Create a reference to the TreeView control.
Set oTree = Me!xTree.Object
'If no node is selected, select the first node you dragged over.
If oTree.SelectedItem Is Nothing Then
Set oTree.SelectedItem = oTree.HitTest(x, y)
End If
'Highlight the node being dragged over as a potential drop target.
Set oTree.DropHighlight = oTree.HitTest(x, y)
End Sub
'==================================================================
'The OLEDragDrop event moves the selected node on the TreeView
'control to its new location and changes the corresponding record in
'the Employees table. The procedure first checks that the TreeView
'has a selected node. If so, it continues to check if a drop target
'node is highlighted. If no node is highlighted, then the user has
'dragged the node off the tree and dropped it into a blank area, and
'the procedure adds a branch to the root of the tree. If a node is
'highlighted, the procedure modifies the Employee table's ReportTo
'field accordingly and sets the selected node's parent property
'to the node that has the drop highlight.
'==================================================================
Private Sub xTree_OLEDragDrop(Data As Object, Effect As Long, _
Button As Integer, Shift As Integer, x As Single, y As Single)
On Error GoTo ErrxTree_OLEDragDrop
Dim oTree As TreeView
Dim strKey As String, strText As String
Dim nodNew As Node, nodDragged As Node
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
'Open the Employees table for editing.
Set rs = db.OpenRecordset("Employees", dbOpenDynaset)
'Create a reference to the TreeView control.
Set oTree = Me!xTree.Object
'If nothing is selected for drag, do nothing.
If oTree.SelectedItem Is Nothing Then
Else
'Reference the selected node as the one being dragged.
Set nodDragged = oTree.SelectedItem
'If the node was dragged to an empty space, update the
'Employees table and make this employee a root node.
If oTree.DropHighlight Is Nothing Then
'Save the key and the text to use when you re-add the node.
strKey = nodDragged.Key
strText = nodDragged.Text
'Delete the current node for the employee.
oTree.Nodes.Remove nodDragged.Index
'Locate the record in the Employees table and update it.
rs.FindFirst "[EmployeeID]=" & Mid(strKey, 2)
rs.Edit
rs![ReportsTo] = Null
rs.Update
'Add this employee as a root node.
Set nodNew = oTree.Nodes.Add(, , strKey, strText)
'Add all the child nodes for this employee.
AddChildren nodNew, rs
'If you are not dropping the node on itself.
ElseIf nodDragged.Index <> oTree.DropHighlight.Index Then
'Set the drop target as the selected node's parent.
Set nodDragged.Parent = oTree.DropHighlight
'Locate the record in the Employees table and update it.
rs.FindFirst "[EmployeeID]=" & Mid(nodDragged.Key, 2)
rs.Edit
rs![ReportsTo] = Mid(oTree.DropHighlight.Key, 2)
rs.Update
End If
End If
'Deselect the node
Set nodDragged = Nothing
'Unhighlight the nodes.
Set oTree.DropHighlight = Nothing
ExitxTree_OLEDragDrop:
Exit Sub
ErrxTree_OLEDragDrop:
'If you create a circular branch.
If Err.Number = 35614 Then
MsgBox "A supervisor cannot report to a subordinate.", _
vbCritical, "Move Cancelled"
Else
MsgBox "An error occurred while trying to move the node. " & _
"Please try again." & vbCrLf & Error.Description
End If
Resume ExitxTree_OLEDragDrop
End Sub
Scegliere Compila Northwind dal menu Debug.
Chiudere Microsoft Visual Basic Editor, quindi passare alla
visualizzazione Maschera. Provare a trascinare i nomi degli impiegati del
controllo TreeView e verificare il modo in cui la struttura e la tabella degli
impiegati vengono aggiornati con le nuove informazioni.
Per ulteriori informazioni sull'utilizzo
del controllo TreeView, in Visual Basic Editor scegliere Guida in linea Microsoft Visual Basic dal menu ?, digitare controllo TreeView nella casella dell'Assistente di Office o della Ricerca libera e
infine fare clic su Cerca per visualizzare l'argomento.
Per
ulteriori informazioni sul controllo TreeView, vedere il seguente articolo
della Microsoft Knowledge Base:
162523
(http://support.microsoft.com/kb/162523/
)
Passaggio dal controllo Data Outline al controllo
TreeView
Per
ulteriori informazioni sull'utilizzo della ricorsione in Microsoft Access, in
Visual Basic Editor scegliere Guida in linea Microsoft Visual Basic dal menu ?, digitare procedure ricorsive nella casella dell'Assistente di Office o della Ricerca libera e
infine fare clic su Cerca per visualizzare l'argomento.
LE INFORMAZIONI CONTENUTE NELLA MICROSOFT KNOWLEDGE BASE SONO FORNITE SENZA GARANZIA DI ALCUN TIPO, IMPLICITA OD ESPLICITA, COMPRESA QUELLA RIGUARDO ALLA COMMERCIALIZZAZIONE E/O COMPATIBILITA' IN IMPIEGHI PARTICOLARI. L'UTENTE SI ASSUME L'INTERA RESPONSABILITA' PER L'UTILIZZO DI QUESTE INFORMAZIONI. IN NESSUN CASO MICROSOFT CORPORATION E I SUOI FORNITORI SI RENDONO RESPONSABILI PER DANNI DIRETTI, INDIRETTI O ACCIDENTALI CHE POSSANO PROVOCARE PERDITA DI DENARO O DI DATI, ANCHE SE MICROSOFT O I SUOI FORNITORI FOSSERO STATI AVVISATI. IL DOCUMENTO PUO' ESSERE COPIATO E DISTRIBUITO ALLE SEGUENTI CONDIZIONI: 1) IL TESTO DEVE ESSERE COPIATO INTEGRALMENTE E TUTTE LE PAGINE DEVONO ESSERE INCLUSE. 2) I PROGRAMMI SE PRESENTI, DEVONO ESSERE COPIATI SENZA MODIFICHE, 3) IL DOCUMENTO DEVE ESSERE DISTRIBUITO INTERAMENTE IN OGNI SUA PARTE. 4) IL DOCUMENTO NON PUO' ESSERE DISTRIBUITO A SCOPO DI LUCRO.
Queste informazioni sono state utili?
Sì
No
In parte
Quanto impegno ti ha richiesto il corretto utilizzo di questo articolo?
Molto basso
Basso
Medio
Elevato
Molto elevato
Inviare commenti e suggerimenti
Grazie. I commenti e suggerimenti forniti verranno utilizzati per migliorare la qualità dei contenuti di supporto tecnico. Per ulteriori opzioni di assistenza, visitare la home page del Supporto Tecnico Microsoft.