devxlogo

Storing objects in the Tag property

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 projectDim myObject As New CPersonmyObject.FirstName = "Francesco"myObject.LastName = "Balena"' currNode is a TreeView's Node objectcurrNode.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 CPersonCopyMemory 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 crashCopyMemory 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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist