Mega Code Archive

 
Categories / Delphi / ADO Database
 

Reading not required dataset fields

Title: Reading not required dataset fields Question: how to avoid the "invalid Variant conversion" Exception when reading a NULL Field Answer: function GetFieldValueDefault(ds:TDataSet; const FieldName:string; default:Variant):Variant; var f : TField; begin f := ds.FieldByName(FieldName); if not f.IsNull then Result := f.Value else Result := default; end; procedure Example; var s : string; i : integer; begin // not safe, because a Variant conversion Exception could be trown s := table1.FieldValues['Field1']; i := table1.FieldValues['Field2']; // safe s := GetFieldValueDefault(table1, 'Field1', ''); i := GetFieldValueDefault(table1, 'Field2', 0); // you could provide a default value if the field is NULL s := GetFieldValueDefault(table1, 'Field1', '(unassigned)'); i := GetFieldValueDefault(table1, 'Field2', -1); end; // If you are not shure, if the field exists at all // use this function function GetFieldValueDefault2(ds:TDataSet; const FieldName:string; default:Variant):Variant; var f : TField; begin f := ds.FindField(FieldName); if Assigned(f) and not f.IsNull then Result := f.Value else Result := default end;