Using .AsString or .Text?

寵の児 提交于 2020-01-14 07:34:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!