Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: VB4/32,VB5,VB6
Expertise: Advanced
Apr 20, 1999

Storing objects in the Tag property

The Tag property exposed by many Windows Common Controls (including TreeView's Node objects and ListView's ListItem objects) is more versatile than the ListBox and ComboBox controls' ItemData property, because it is of Variant type and can therefore accept values of most data types.

However, it can't be used to store an object reference, probably because of an implementation bug. If you want to associate an item to an object you can use the Tag property as an index into an object array, but fortunately there is a simpler and more efficient method.

When you want to store an object reference into a Tag property, assign it the pointer to the object (a Long value):


' assumes that a CPerson class module is defined
' elsewhere in the current project
Dim myObject As New CPerson
myObject.FirstName = "Francesco"
myObject.LastName = "Balena"

' currNode is a TreeView's Node object
currNode.Tag = ObjPtr(myObject)
When you later need to rebuild the object reference, you use the CopyMemory API function to manually store the object pointer into a suitable object variable:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As _
    Any, source As Any, ByVal bytes As Long)

Dim myObject As CPerson
CopyMemory myObject, CLng(currNode.Tag), 4
' here you use myObject's methods and properties
' ....
' you must manually destroy this reference before it
' gets out of scope, or VB will crash
CopyMemory myObject, 0&, 4
You can use the same technique with the ItemData property of ListBox and ComboBox controls. It is mandatory, however, that the object be referenced by at least another object variable, because the weak reference held in the Tag property doesn't keep it alive. If the object is destroyed and you later try to access it in the way described above, you get a runtime error or - worse - a GPF error.
Francesco Balena
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date