Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...