简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM