Title: Compare of FieldValues and FieldByName
Question: Why an exception raised when I read the field value just like DataSet['Name']?
Answer:
In Steve Teixeira and Xavier Pacheco 's great book "Delphi 4 Developer's Guide", they strongly recommend that use FieldValues array property to read or write field value when you working with dataset. Because FieldValues is a set to default, so write it is easily, just like:
Label1.Caption := DataSet['Name'];
// just equals to DataSet.FieldValues['Name']
DataSet['Name'] := Label1.Caption;
The first statement works in most occasions, but when 'Name' is empty, then an exception will raise. Why? From the online help, we see that FieldValues property returns Variant, so when 'Name' Field is empty, it returns NULL, then Delphi try to convert NULL to string, then a error raised.
In this case, most of us want to get empty string when the field is empty, so to do this, we should use this safe code:
var
a: Variant;
...
a := DataSet['Name'];
if VarIsNull(a) then
Label1.Caption := EmptyStr
else
Label1.Caption := a;
How much work I have done. Is there any alternative and easy way to do this? Yes.
Just use FieldByName method. FieldByName method return TField, and you can use AsString, AsInteger and so on to convert value. When the field is empty, AsString will return empty string and no exception, and AsInteger will return 0. It is easy to finish the previous job, just like:
Label1.Caption := DataSet.FieldByName('Name').AsString;
Summary: From the article, we know when you try to read the value of a field, please use FieldByName, though you type more char, It will make your code safe. And when you try to write the value of a field, use FieldValues property, It works very well, and few typing.
Good luck.