Mega Code Archive

 
Categories / Delphi / Strings
 

How to Store a String value to a Tag Property of a Delphi control

Title: How to Store a String value to a Tag Property of a Delphi control Every Delphi component exposes the Tag property which can be used to store an integer value as part of a component. Tag property in Delphi controls (and components) has no predefined meaning, it can be used for storing an additional integer value or it can be typecast to any 32-bit value such as a component reference or a pointer. Store a String in the Tag Property You might want to store a string value in the tag property of a control (TEdit, TButton, etc.) to let every control cary an additional string value. Storing a string value in the Tag property involves creating a pointer to a string and casting the string value to an Integer value.. For example, to store the current value of the Text property of a TEdit control, when it receives the focus, use the next code: //handles Edit1 OnEnter event procedure TForm1.Edit1Enter(Sender: TObject) ; var tagString : PChar; begin //copy current Edit1.Text to the Tag property. GetMem(tagString, 1 + Length(Edit1.Text)) ; StrPCopy(tagString, Edit1.Text) ; Edit1.Tag := Integer(tagString) ; end; Since the Tag property expects an integer value, we can use a pointer type variable and type cast it to an Integer. A 32 bit Integer occupies the same number of bytes in memory as a pointer variable. In the above example, the StrPCopy RTL function takes a string value (Edit1.Text) and copies it to a null-terminated string (tagString) variable. The tagString is the PChar (pointer to a string) type variable. Before we transform a string to a null-terminated string, we need to make sure we have enough space for it. This is what GetMem's job is. When we are finished we need to free the memory used, using FreeMem. Extract the String from the Tag Property To get back the string from the Tag property of a control, we need to cast the stored pointer back to a string value. var s : string; begin s := PChar(Edit1.Tag) ; ShowMessage(s) ; end; Note: you must be sure to free the memory occupied in the OnEnter event handler. You can do that in the Edit1's OnExit event hanlder: //Edit1 OnExit even handler procedure TESCUndoForm.Edit1Exit(Sender: TObject) ; begin FreeMem(PChar(Edit1.Tag)) ; end; Warning: it might be possible to close the form hosting the Edit1 edit box without executing the code in the OnExit event. Make sure to call this event manually, then. Final warning: this technique of storing a string in the integer type variable (Tag property) is a nasty hack. If possible you should find another way of "attaching" an extra string value to a control.