You can use a simple function like this to access a TDBGrid column by fieldname:
function ColumnByName(Grid : TDBGrid; const AName: String): TColumn;
var
i : Integer;
begin
Result := Nil;
for i := 0 to Grid.Columns.Count - 1 do begin
if (Grid.Columns[i].Field <> Nil) and (CompareText(Grid.Columns[i].FieldName, AName) = 0) then begin
Result := Grid.Columns[i];
exit;
end;
end;
end;
Then, you could do this:
ColumnByName(dbgrid1, 'Payment').AsString:= 'SomeValue';
If you are using FireDAC, your Delphi version is recent enough to support class helpers, so you could use a class helper instead:
type
TGridHelper = class helper for TDBGrid
function ColumnByName(const AName : String) : TColumn;
end;
[...]
{ TGridHelper }
function TGridHelper.ColumnByName(const AName: String): TColumn;
var
i : Integer;
begin
Result := Nil;
for i := 0 to Columns.Count - 1 do begin
if (Columns[i].Field <> Nil) and (CompareText(Columns[i].FieldName, AName) = 0) then begin
Result := Columns[i];
exit;
end;
end;
end;
and then
dbgrid1.ColumnByName('Payment').AsString := 'SomeValue';
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…