问题
I have just seen a bit of code (D5) where they used...
aStr:=tblAcct.FieldByName('Name').Text;
It seems to work fine but I have always used...
aStr:=tblAcct.FieldByName('Name').AsString;
I have used both when loading a TMemo and again there seems no difference.
aMemo.Lines.Text:=tblAcct.FieldByName('History').Text;
aMemo.Lines.Text:=tblAcct.FieldByName('History').AsString;
Is there a reason why I should use one over the other? If so, which one?
Actually for TMemo, I usually use...
aMemo.Lines.Assign(tblAcct.FieldByName('History'))
which seems to work fine too.
Thanks
回答1:
The Text property is meant to be used to obtain the textual representation of a field being edited in a DataAware control, in contrast with the DisplayText property that gives you a string to represent the value to the user (it may contain punctuation or other decoration to the plain value).
Contains the string to display in a data-aware control when the field is in edit mode
A typical example is a TFloatField with the Currency
property set to True
. The DisplayText
gives you a string with the number containing commas (if needed), the decimal separator and a currency symbol. The Text
property gives you a string without commas or currency symbol.
begin
MyFloatField.Currency := True;
MyFloatField.AsFloat := 1234.56;
A := MyFloatField.Text; //'1234.56'
B := MyFloatField.DisplayText; //'$1,234.56', depends on your locale
end;
Both above properties can be customized writing a OnGetText event handler where you can write custom logic to convert the value to a string representation. The DisplayText
parameter indicates if the wanted string is meant to represent the value for edit or not.
On the other hand, the AsString
property uses a more plain conversion between the base data type and string. Each TField descendant implements the virtual GetAsString method using functions from the RTL to perform that representation. Following the TFloatField example, this class calls FloatToStr() for that purpose.
All this said, the answer to your question is: AsString
returns the same string as the Text
property if there's no OnGetText event handler, but it may be different if there's a event handler or a non-standard TField descendant.
I can't tell what is more appropriate for you, because it depends on what's the intended use for the returned value, but if you're using it to display the values to the user in the UI (as your code example), I advise you to use the DisplayText property.
回答2:
AsString
contains field's value as string.
Text
contains the string to display in a data-aware control when the field is in edit mode.
So in your case I think you should use AsString.
来源:https://stackoverflow.com/questions/15768278/using-asstring-or-text