Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Storing objects in the Tag property

Total Hit ( 4553)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


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):

Click here to copy the following block
' 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:

Click here to copy the following block
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.


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.