Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

firedac - Delphi dbGrid - Column Names

I often refer to the values in a field in a dbgrid with the index number, for example:

dbgrid1.Fields[8].AsString:= 'SomeValue'; //index 8 refering to a field named 'Payment'

This works OK until I change the fields about that the dbgrid has listed in the field editor, at which time I have to search for all the above usage and change the index number.

It would be far simpler, and less opportunity for problems, if I could refer to the field with something like:

dbgrid1.Field('Payment').AsString:= 'SomeValue';

Is there a way of doing this?

question from:https://stackoverflow.com/questions/65833997/delphi-dbgrid-column-names

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...