Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a TDBGrid column by name instead of by Index?

Tags:

delphi

How can I access a TDBGrid column by name instead of Index?

For example, now I use:

 grdInvoiceItems.Columns[2].Visible := False;

but it would be much better to write something like:

 grdInvoiceItems.Columns['UnitPrice'].Visible := False;

In the mean time I use a for cycle like in:

  for idx := 0 to grdInvoiceItems.Columns.Count - 1 do
    begin
    if (
         (grdInvoiceItems.Columns[idx].FieldName = 'UnitPrice') or
         (grdInvoiceItems.Columns[idx].FieldName = 'Discount') or
         (grdInvoiceItems.Columns[idx].FieldName = 'SecretCode')
       ) then
      grdInvoiceItems.Columns[idx].Visible := False;
    end;

Using colum name is IMO much better tham column index since index is subject to change more often than name.

Any idea on how to encapsulate it better?

like image 934
Fabio Vitale Avatar asked Jun 16 '16 07:06

Fabio Vitale


1 Answers

You could try something like this:

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;

Of course, if you are using a version of Delphi which is recent enough to support Class Helpers, you could wrap this function into a Class Helper for TDBGrid, like this

type
  TGridHelper = class helper for TDBGrid
    function ColumnByName(const AName : String) : TColumn;
  end;
[...]

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;

Then, you could do this

Col := DBGrid1.ColumnByName('SomeName');

Obviously, you could write a similar function which searches by the column's title, rather than the associated Field's FieldName.

like image 119
MartynA Avatar answered Oct 05 '22 07:10

MartynA